doukui 0.0.0-stage → 0.3.1

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 (137) 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 +1443 -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 +1411 -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 +588 -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 +415 -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-lint.js +100 -0
  118. package/plugins/runtime/plan-reader.js +763 -0
  119. package/plugins/runtime/plugin-loader.js +798 -0
  120. package/plugins/runtime/plugin-trust.js +182 -0
  121. package/plugins/runtime/plugin-validator.js +491 -0
  122. package/plugins/runtime/provider-failover.js +114 -0
  123. package/plugins/runtime/provider-resolver.js +342 -0
  124. package/plugins/runtime/reflection-evaluator.js +545 -0
  125. package/plugins/runtime/resolve-plugin-path.js +297 -0
  126. package/plugins/runtime/safe-path.js +119 -0
  127. package/plugins/runtime/sandbox-context.js +235 -0
  128. package/plugins/runtime/sandbox-manager.js +609 -0
  129. package/plugins/runtime/sandbox-worker.js +215 -0
  130. package/plugins/runtime/self-rescue-ladder.js +38 -0
  131. package/plugins/runtime/settings-merger.js +172 -0
  132. package/plugins/runtime/state-store.js +527 -0
  133. package/plugins/runtime/team-cleanup.js +497 -0
  134. package/plugins/runtime/text-tokenize.js +25 -0
  135. package/plugins/runtime/validator-pipeline.js +475 -0
  136. package/plugins/runtime/yaml-parser.js +692 -0
  137. package/templates/harness-config.yaml +394 -0
@@ -0,0 +1,320 @@
1
+ /**
2
+ * ConfigValidator - Schema-based configuration validator for harness-config.yaml
3
+ *
4
+ * Validates the configuration file structure and reports missing or invalid fields.
5
+ * Provides detailed error messages for each validation failure.
6
+ *
7
+ * Usage:
8
+ * var validator = new ConfigValidator();
9
+ * var result = validator.validate(configPath);
10
+ * if (!result.valid) {
11
+ * console.error(result.errors);
12
+ * }
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ var fs = require('fs');
18
+ var path = require('path');
19
+
20
+ /**
21
+ * Schema definition for harness-config.yaml (loaded from external file).
22
+ * Each field can have:
23
+ * - type: expected type ('string', 'number', 'boolean', 'object', 'array')
24
+ * - required: whether the field is required
25
+ * - default: default value if not present
26
+ * - allowedValues: array of allowed values (for enums)
27
+ * - properties: nested schema (for objects)
28
+ * - items: schema for array items
29
+ */
30
+ var CONFIG_SCHEMA = require('../contracts/config-schema.json');
31
+
32
+ /**
33
+ * Minimal YAML-like parser — S8/A3 consolidated.
34
+ *
35
+ * Delegates to the shared `yaml-parser.parseSimpleYaml`. Previously this
36
+ * module had its own divergent copy; the shared parser now covers the same
37
+ * surface (flat keys, nested objects, lists, list-of-objects, inline flow
38
+ * arrays, quoted strings, comments) plus MAX_YAML_SIZE / MAX_DEPTH guards.
39
+ * @internal
40
+ */
41
+ function parseSimpleYaml(content) {
42
+ var sharedParser = require('./yaml-parser');
43
+ return sharedParser.parseSimpleYaml(content);
44
+ }
45
+
46
+ /**
47
+ * Parse a YAML scalar value.
48
+ * Supports strings, numbers, booleans, null, and inline arrays.
49
+ */
50
+ function parseValue(val) {
51
+ if (val === 'true') return true;
52
+ if (val === 'false') return false;
53
+ if (val === 'null' || val === '~') return null;
54
+
55
+ // Remove surrounding quotes
56
+ if ((val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') ||
57
+ (val.charAt(0) === "'" && val.charAt(val.length - 1) === "'")) {
58
+ return val.substring(1, val.length - 1);
59
+ }
60
+
61
+ // Check for inline array [item1, item2]
62
+ if (val.charAt(0) === '[' && val.charAt(val.length - 1) === ']') {
63
+ var inner = val.substring(1, val.length - 1).trim();
64
+ if (inner === '') return [];
65
+ var items = [];
66
+ var current = '';
67
+ var inQuotes = false;
68
+ var quoteChar = '';
69
+
70
+ for (var i = 0; i < inner.length; i++) {
71
+ var ch = inner.charAt(i);
72
+ if ((ch === '"' || ch === "'") && (i === 0 || inner.charAt(i - 1) !== '\\')) {
73
+ if (!inQuotes) {
74
+ inQuotes = true;
75
+ quoteChar = ch;
76
+ } else if (ch === quoteChar) {
77
+ inQuotes = false;
78
+ quoteChar = '';
79
+ } else {
80
+ current += ch;
81
+ }
82
+ } else if (ch === ',' && !inQuotes) {
83
+ items.push(parseValue(current.trim()));
84
+ current = '';
85
+ } else {
86
+ current += ch;
87
+ }
88
+ }
89
+ if (current.trim() !== '' || items.length > 0) {
90
+ items.push(parseValue(current.trim()));
91
+ }
92
+ return items;
93
+ }
94
+
95
+ // Try number
96
+ var num = Number(val);
97
+ if (!isNaN(num) && val !== '') return num;
98
+
99
+ return val;
100
+ }
101
+
102
+ class ConfigValidator {
103
+ /**
104
+ * Create a new validator instance.
105
+ * @public
106
+ * @param {object} [options]
107
+ * @param {object} [options.schema] - custom schema to use (default: CONFIG_SCHEMA)
108
+ */
109
+ constructor(options) {
110
+ options = options || {};
111
+ this._schema = options.schema || CONFIG_SCHEMA;
112
+ }
113
+
114
+ /**
115
+ * Validate a configuration file.
116
+ * @public
117
+ * @param {string} configPath - path to harness-config.yaml
118
+ * @returns {{valid: boolean, errors: string[], warnings: string[]}}
119
+ */
120
+ validateFile(configPath) {
121
+ var result = {
122
+ valid: true,
123
+ errors: [],
124
+ warnings: []
125
+ };
126
+
127
+ // Check if file exists
128
+ if (!fs.existsSync(configPath)) {
129
+ // Degrade to warning - allow build to proceed with defaults
130
+ result.valid = true;
131
+ result.warnings.push('Configuration file not found: ' + configPath);
132
+ return result;
133
+ }
134
+
135
+ // Read and parse file
136
+ var content;
137
+ try {
138
+ content = fs.readFileSync(configPath, 'utf-8');
139
+ } catch (err) {
140
+ result.valid = false;
141
+ result.errors.push('Failed to read configuration file: ' + err.message);
142
+ return result;
143
+ }
144
+
145
+ var config;
146
+ try {
147
+ config = parseSimpleYaml(content);
148
+ } catch (err) {
149
+ result.valid = false;
150
+ result.errors.push('Failed to parse configuration file: ' + err.message);
151
+ return result;
152
+ }
153
+
154
+ // Validate against schema
155
+ return this.validate(config);
156
+ }
157
+
158
+ /**
159
+ * Validate a configuration object.
160
+ * @public
161
+ * @param {object} config - parsed configuration object
162
+ * @returns {{valid: boolean, errors: string[], warnings: string[]}}
163
+ */
164
+ validate(config) {
165
+ var result = {
166
+ valid: true,
167
+ errors: [],
168
+ warnings: []
169
+ };
170
+
171
+ if (!config || typeof config !== 'object') {
172
+ result.valid = false;
173
+ result.errors.push('Configuration must be an object');
174
+ return result;
175
+ }
176
+
177
+ // Validate each top-level section
178
+ for (var key in this._schema) {
179
+ var schema = this._schema[key];
180
+ var value = config[key];
181
+
182
+ if (value === undefined) {
183
+ if (schema.required) {
184
+ result.valid = false;
185
+ result.errors.push('Missing required field: ' + key);
186
+ }
187
+ continue;
188
+ }
189
+
190
+ var sectionResult = this._validateField(value, schema, key);
191
+ if (!sectionResult.valid) {
192
+ result.valid = false;
193
+ result.errors = result.errors.concat(sectionResult.errors);
194
+ }
195
+ result.warnings = result.warnings.concat(sectionResult.warnings);
196
+ }
197
+
198
+ return result;
199
+ }
200
+
201
+ /**
202
+ * Validate a single field against its schema.
203
+ * @private
204
+ */
205
+ _validateField(value, schema, path) {
206
+ var result = {
207
+ valid: true,
208
+ errors: [],
209
+ warnings: []
210
+ };
211
+
212
+ // Type check
213
+ if (!this._checkType(value, schema.type)) {
214
+ result.valid = false;
215
+ result.errors.push('Field "' + path + '" must be of type ' + schema.type + ', got ' + typeof value);
216
+ return result;
217
+ }
218
+
219
+ // Allowed values check
220
+ if (schema.allowedValues && schema.allowedValues.indexOf(value) === -1) {
221
+ result.valid = false;
222
+ result.errors.push('Field "' + path + '" has invalid value "' + value + '". Allowed values: ' + schema.allowedValues.join(', '));
223
+ }
224
+
225
+ // Object properties validation
226
+ if (schema.type === 'object' && schema.properties && value !== null) {
227
+ for (var propKey in schema.properties) {
228
+ var propSchema = schema.properties[propKey];
229
+ var propValue = value[propKey];
230
+
231
+ if (propValue === undefined) {
232
+ if (propSchema.required) {
233
+ result.valid = false;
234
+ result.errors.push('Missing required field: ' + path + '.' + propKey);
235
+ }
236
+ continue;
237
+ }
238
+
239
+ var propResult = this._validateField(propValue, propSchema, path + '.' + propKey);
240
+ if (!propResult.valid) {
241
+ result.valid = false;
242
+ result.errors = result.errors.concat(propResult.errors);
243
+ }
244
+ result.warnings = result.warnings.concat(propResult.warnings);
245
+ }
246
+ }
247
+
248
+ // Array items validation
249
+ if (schema.type === 'array' && schema.items && Array.isArray(value)) {
250
+ for (var i = 0; i < value.length; i++) {
251
+ var itemResult = this._validateField(value[i], schema.items, path + '[' + i + ']');
252
+ if (!itemResult.valid) {
253
+ result.valid = false;
254
+ result.errors = result.errors.concat(itemResult.errors);
255
+ }
256
+ result.warnings = result.warnings.concat(itemResult.warnings);
257
+ }
258
+ }
259
+
260
+ return result;
261
+ }
262
+
263
+ /**
264
+ * Check if a value matches the expected type.
265
+ * @private
266
+ */
267
+ _checkType(value, type) {
268
+ switch (type) {
269
+ case 'string':
270
+ return typeof value === 'string';
271
+ case 'number':
272
+ return typeof value === 'number' && !isNaN(value);
273
+ case 'boolean':
274
+ return typeof value === 'boolean';
275
+ case 'object':
276
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
277
+ case 'array':
278
+ return Array.isArray(value);
279
+ default:
280
+ return true;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Get the default configuration object.
286
+ * @public
287
+ * @returns {object}
288
+ */
289
+ getDefaults() {
290
+ var defaults = {};
291
+
292
+ for (var key in this._schema) {
293
+ defaults[key] = this._getSchemaDefaults(this._schema[key]);
294
+ }
295
+
296
+ return defaults;
297
+ }
298
+
299
+ /**
300
+ * Get default values from a schema.
301
+ * @private
302
+ */
303
+ _getSchemaDefaults(schema) {
304
+ var result = schema.default !== undefined ? schema.default : null;
305
+
306
+ if (schema.type === 'object' && schema.properties) {
307
+ result = {};
308
+ for (var key in schema.properties) {
309
+ var propDefault = this._getSchemaDefaults(schema.properties[key]);
310
+ if (propDefault !== null) {
311
+ result[key] = propDefault;
312
+ }
313
+ }
314
+ }
315
+
316
+ return result;
317
+ }
318
+ }
319
+
320
+ module.exports = ConfigValidator;
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // 上下文窗口分档(Phase B-2)
5
+ // ---------------------------------------------------------------------------
6
+ // 原框架 context_window.max_tokens 硬默认 200000,与 2026 年模型窗口现状脱节
7
+ // (DeepSeek V4-Pro 官方 1M;其余 provider 档位以官方文档为准)。分档只在
8
+ // loop 运行时才有意义——build 期不知道用户会用哪个 provider。
9
+ //
10
+ // 解析优先级:
11
+ // 1. provider profile 显式声明 `context_window_tokens`(harness-config.yaml
12
+ // 的 loop.providers 段,一份 profile 一档)
13
+ // 2. 内置档位表按模型名前缀匹配(最长前缀优先)
14
+ // 3. 保守默认 200000(unknown / 未声明 / 旧模型)
15
+ //
16
+ // 本模块只做「解析 + 告知」:把窗口预算交给 executor prompt(会话内分块读取
17
+ // 策略用对预算),不做 prompt 裁剪——裁剪属独立功能,不混入。
18
+ // ---------------------------------------------------------------------------
19
+
20
+ // 保守默认:未知 provider / 未声明 / 档位表未命中
21
+ var DEFAULT_CONTEXT_WINDOW = 200000;
22
+
23
+ // 内置档位表:模型名前缀 → 窗口 tokens(最长前缀优先)。
24
+ // 仅收录有官方公开依据的档位;新 provider 档位优先用 profile.context_window_tokens
25
+ // 显式声明,不要凭猜测改本表。
26
+ var TIERS = Object.freeze([
27
+ Object.freeze({ prefix: 'deepseek-v4', tokens: 1000000 }), // DeepSeek V4-Pro 官方 1M
28
+ ]);
29
+
30
+ /**
31
+ * 按模型名前缀匹配档位(最长前缀优先)。
32
+ * @param {string|null} model 生效模型名(如 "deepseek-v4-pro"、"glm-5.2")
33
+ * @returns {number|null} 命中的窗口 tokens;未命中返回 null(走默认)
34
+ */
35
+ function matchTiers(model) {
36
+ if (!model || typeof model !== 'string') return null;
37
+ var lower = model.toLowerCase();
38
+ var best = null;
39
+ var bestLen = -1;
40
+ for (var i = 0; i < TIERS.length; i++) {
41
+ var tier = TIERS[i];
42
+ if (lower.indexOf(tier.prefix) === 0 && tier.prefix.length > bestLen) {
43
+ best = tier.tokens;
44
+ bestLen = tier.prefix.length;
45
+ }
46
+ }
47
+ return best;
48
+ }
49
+
50
+ /**
51
+ * 解析当前生效模型的上下文窗口预算。
52
+ * @param {object} [opts]
53
+ * @param {string|null} [opts.model] 生效模型名
54
+ * @param {object|null} [opts.profile] provider-resolver 匹配的 provider 规则对象;
55
+ * 可选字段 `context_window_tokens`(显式档位,最高优先)
56
+ * @returns {{ tokens: number, source: 'profile'|'tiers'|'default', model: string|null }}
57
+ * source 说明预算来源,供日志/测试断言
58
+ */
59
+ function resolveContextWindow(opts) {
60
+ opts = opts || {};
61
+ var model = opts.model || null;
62
+ var profile = opts.profile && typeof opts.profile === 'object' ? opts.profile : null;
63
+
64
+ if (profile && typeof profile.context_window_tokens === 'number' && profile.context_window_tokens > 0) {
65
+ return { tokens: profile.context_window_tokens, source: 'profile', model: model };
66
+ }
67
+
68
+ var tierHit = matchTiers(model);
69
+ if (tierHit !== null) {
70
+ return { tokens: tierHit, source: 'tiers', model: model };
71
+ }
72
+
73
+ return { tokens: DEFAULT_CONTEXT_WINDOW, source: 'default', model: model };
74
+ }
75
+
76
+ module.exports = {
77
+ resolveContextWindow: resolveContextWindow,
78
+ matchTiers: matchTiers,
79
+ TIERS: TIERS,
80
+ DEFAULT_CONTEXT_WINDOW: DEFAULT_CONTEXT_WINDOW,
81
+ };
@@ -0,0 +1,207 @@
1
+ /**
2
+ * EventBus - Event dispatch system for AI Agent Harness
3
+ *
4
+ * @module event-bus
5
+ *
6
+ * Features:
7
+ * - on(event, handler) register a listener
8
+ * - once(event, handler) one-time listener
9
+ * - off(event, handler) unregister a listener
10
+ * - emit(event, data) dispatch an event
11
+ * - History recording and query for debugging
12
+ * - Subscription objects with unsubscribe() support
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ var Logger = require('./logger');
18
+ var logger = new Logger();
19
+
20
+ class EventBus {
21
+ /**
22
+ * @public
23
+ * @param {object} [options]
24
+ * @param {number} [options.maxHistory=100] - max event history entries
25
+ */
26
+ constructor(options) {
27
+ options = options || {};
28
+ /** @type {Map<string, Set<Function>>} event -> handlers */
29
+ this._handlers = new Map();
30
+ /** @type {object[]} */
31
+ this._history = [];
32
+ /** @type {number} */
33
+ this._maxHistory = options.maxHistory || 100;
34
+ }
35
+
36
+ // --- public API ---
37
+
38
+ /**
39
+ * Register an event handler.
40
+ * @public
41
+ * @param {string} event - event name
42
+ * @param {Function} handler - callback(eventData)
43
+ * @returns {{ unsubscribe: Function }} subscription handle
44
+ */
45
+ on(event, handler) {
46
+ if (typeof handler !== 'function') {
47
+ throw new TypeError('EventBus.on(): handler must be a function');
48
+ }
49
+ if (!this._handlers.has(event)) {
50
+ this._handlers.set(event, new Set());
51
+ }
52
+ this._handlers.get(event).add(handler);
53
+
54
+ var self = this;
55
+ var handlers = this._handlers.get(event);
56
+ return {
57
+ unsubscribe: function () {
58
+ handlers.delete(handler);
59
+ if (handlers.size === 0) {
60
+ self._handlers.delete(event);
61
+ }
62
+ },
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Register a one-time event handler. Automatically removed after first invocation.
68
+ * @public
69
+ * @param {string} event
70
+ * @param {Function} handler - callback(eventData)
71
+ * @returns {{ unsubscribe: Function }}
72
+ */
73
+ once(event, handler) {
74
+ if (typeof handler !== 'function') {
75
+ throw new TypeError('EventBus.once(): handler must be a function');
76
+ }
77
+ var self = this;
78
+ var wrapped = function (data) {
79
+ handler(data);
80
+ innerSub.unsubscribe();
81
+ };
82
+ var innerSub = this.on(event, wrapped);
83
+ return innerSub;
84
+ }
85
+
86
+ /**
87
+ * Unregister a specific handler from an event.
88
+ * @public
89
+ * @param {string} event
90
+ * @param {Function} handler - the exact function reference originally passed to on()
91
+ */
92
+ off(event, handler) {
93
+ var handlers = this._handlers.get(event);
94
+ if (!handlers) return;
95
+ handlers.delete(handler);
96
+ if (handlers.size === 0) {
97
+ this._handlers.delete(event);
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Emit an event, calling all registered handlers synchronously.
103
+ * Errors in individual handlers are caught and logged, not propagated.
104
+ * @public
105
+ * @param {string} event
106
+ * @param {*} data
107
+ */
108
+ emit(event, data) {
109
+ // Record in history
110
+ this._history.push({
111
+ event: event,
112
+ data: data,
113
+ timestamp: Date.now(),
114
+ });
115
+ if (this._history.length > this._maxHistory) {
116
+ this._history.shift();
117
+ }
118
+
119
+ // Dispatch to handlers
120
+ var handlers = this._handlers.get(event);
121
+ if (!handlers) return;
122
+
123
+ handlers.forEach(function (handler) {
124
+ try {
125
+ handler(data);
126
+ } catch (err) {
127
+ logger.error('event-bus', 'Error in handler for event "' + event + '": ' + err.message);
128
+ }
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Query event history for debugging.
134
+ * @public
135
+ * @param {object} [filter]
136
+ * @param {string} [filter.event] - substring match on event name
137
+ * @param {number} [filter.since] - timestamp lower bound (ms)
138
+ * @param {number} [filter.until] - timestamp upper bound (ms)
139
+ * @param {number} [filter.limit] - max entries to return
140
+ * @returns {object[]}
141
+ */
142
+ getHistory(filter) {
143
+ filter = filter || {};
144
+ var results = this._history;
145
+
146
+ if (filter.event) {
147
+ var substr = filter.event;
148
+ results = results.filter(function (e) {
149
+ return e.event.indexOf(substr) !== -1;
150
+ });
151
+ }
152
+ if (filter.since) {
153
+ results = results.filter(function (e) { return e.timestamp >= filter.since; });
154
+ }
155
+ if (filter.until) {
156
+ results = results.filter(function (e) { return e.timestamp <= filter.until; });
157
+ }
158
+ if (filter.limit) {
159
+ results = results.slice(-filter.limit);
160
+ }
161
+
162
+ return results;
163
+ }
164
+
165
+ /**
166
+ * Clear all event history.
167
+ * @public
168
+ */
169
+ clearHistory() {
170
+ this._history = [];
171
+ }
172
+
173
+ /**
174
+ * Remove all handlers for a specific event, or all events.
175
+ * @public
176
+ * @param {string} [event] - if omitted, clears all handlers
177
+ */
178
+ removeAllListeners(event) {
179
+ if (event) {
180
+ this._handlers.delete(event);
181
+ } else {
182
+ this._handlers.clear();
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Get the number of handlers registered for a given event.
188
+ * @public
189
+ * @param {string} event
190
+ * @returns {number}
191
+ */
192
+ listenerCount(event) {
193
+ var handlers = this._handlers.get(event);
194
+ return handlers ? handlers.size : 0;
195
+ }
196
+
197
+ /**
198
+ * Getter for event history (for testing compatibility).
199
+ * @internal Use getHistory() for public access
200
+ * @returns {object[]}
201
+ */
202
+ get events() {
203
+ return this._history;
204
+ }
205
+ }
206
+
207
+ module.exports = EventBus;