@aiwg/cli 2026.10.14 → 2026.10.16

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 (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,297 @@
1
+ /**
2
+ * Chat handler for 2-way AI communication via messaging platforms.
3
+ *
4
+ * Spawns `claude -p` to process free-text messages and returns responses.
5
+ * Tracks conversation context per chat/user for multi-turn conversations.
6
+ *
7
+ * @implements @.aiwg/requirements/use-cases/UC-CHAT-001.md
8
+ * @tests @test/unit/messaging/chat-handler.test.js
9
+ */
10
+
11
+ import { importImpl } from '../_resolve-impl.mjs';
12
+ import { spawn } from 'node:child_process';
13
+ import path from 'path';
14
+ const { signalChild } = await importImpl(import.meta.url, 'process/signal-child.mjs');
15
+
16
+ /**
17
+ * @typedef {Object} ChatHandlerOptions
18
+ * @property {string} [agentCommand='claude'] - Command to spawn for AI processing
19
+ * @property {string[]} [agentArgs=[]] - Additional args for the agent command
20
+ * @property {string} [cwd] - Working directory for spawned processes
21
+ * @property {Object} [environment] - Recipient-filtered worker environment
22
+ * @property {number} [maxContextMessages=10] - Max messages to include as context
23
+ * @property {number} [timeoutMs=120000] - Timeout for AI response (2 minutes)
24
+ * @property {number} [maxConcurrent=3] - Max concurrent AI processes
25
+ * @property {number} [maxResponseLength=4000] - Max response chars (Telegram limit)
26
+ */
27
+
28
+ export class ChatHandler {
29
+ /** @type {string} */
30
+ #agentCommand;
31
+
32
+ /** @type {string[]} */
33
+ #agentArgs;
34
+
35
+ /** @type {string} */
36
+ #cwd;
37
+ #environment;
38
+
39
+ /** @type {number} */
40
+ #maxContextMessages;
41
+
42
+ /** @type {number} */
43
+ #timeoutMs;
44
+
45
+ /** @type {number} */
46
+ #maxConcurrent;
47
+
48
+ /** @type {number} */
49
+ #maxResponseLength;
50
+
51
+ /** @type {Map<string, Array<{role: string, content: string, timestamp: string}>>} */
52
+ #conversations;
53
+
54
+ /** @type {number} */
55
+ #activeProcesses;
56
+
57
+ /** @type {Map<string, boolean>} */
58
+ #processingChats;
59
+
60
+ /**
61
+ * @param {ChatHandlerOptions} options
62
+ */
63
+ constructor(options = {}) {
64
+ this.#agentCommand = options.agentCommand || 'claude';
65
+ this.#agentArgs = options.agentArgs || [];
66
+ this.#cwd = options.cwd || process.cwd();
67
+ this.#environment = options.environment;
68
+ this.#maxContextMessages = options.maxContextMessages || 10;
69
+ this.#timeoutMs = options.timeoutMs || 120_000;
70
+ this.#maxConcurrent = options.maxConcurrent || 3;
71
+ this.#maxResponseLength = options.maxResponseLength || 4000;
72
+ this.#conversations = new Map();
73
+ this.#activeProcesses = 0;
74
+ this.#processingChats = new Map();
75
+ }
76
+
77
+ /**
78
+ * Process a chat message and return the AI response.
79
+ *
80
+ * @param {string} text - The user's message
81
+ * @param {Object} context - Platform context
82
+ * @param {string} context.chatId - Chat/conversation identifier
83
+ * @param {string} context.platform - Platform name
84
+ * @param {Object} [context.from] - Sender info
85
+ * @returns {Promise<{response: string, conversationId: string}>}
86
+ */
87
+ async processMessage(text, context) {
88
+ const conversationId = this.#getConversationId(context);
89
+
90
+ // Check if this chat is already being processed
91
+ if (this.#processingChats.get(conversationId)) {
92
+ return {
93
+ response: 'Still processing your previous message. Please wait.',
94
+ conversationId,
95
+ };
96
+ }
97
+
98
+ // Check concurrency limit
99
+ if (this.#activeProcesses >= this.#maxConcurrent) {
100
+ return {
101
+ response: `AI is busy (${this.#activeProcesses}/${this.#maxConcurrent} active). Please try again shortly.`,
102
+ conversationId,
103
+ };
104
+ }
105
+
106
+ // Record user message in conversation history
107
+ this.#addMessage(conversationId, 'user', text);
108
+
109
+ // Build prompt with conversation context
110
+ const prompt = this.#buildPrompt(conversationId, text);
111
+
112
+ this.#processingChats.set(conversationId, true);
113
+ this.#activeProcesses++;
114
+
115
+ try {
116
+ const response = await this.#spawnAgent(prompt);
117
+ const truncated = this.#truncateResponse(response);
118
+
119
+ // Record assistant response
120
+ this.#addMessage(conversationId, 'assistant', truncated);
121
+
122
+ return { response: truncated, conversationId };
123
+ } catch (error) {
124
+ return {
125
+ response: `Error: ${error.message}`,
126
+ conversationId,
127
+ };
128
+ } finally {
129
+ this.#activeProcesses--;
130
+ this.#processingChats.set(conversationId, false);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Get conversation history for a chat.
136
+ *
137
+ * @param {string} conversationId
138
+ * @returns {Array<{role: string, content: string, timestamp: string}>}
139
+ */
140
+ getConversation(conversationId) {
141
+ return [...(this.#conversations.get(conversationId) || [])];
142
+ }
143
+
144
+ /**
145
+ * Clear conversation history for a chat.
146
+ *
147
+ * @param {string} conversationId
148
+ */
149
+ clearConversation(conversationId) {
150
+ this.#conversations.delete(conversationId);
151
+ }
152
+
153
+ /**
154
+ * Get stats about active processing.
155
+ *
156
+ * @returns {{activeProcesses: number, maxConcurrent: number, conversationCount: number}}
157
+ */
158
+ getStats() {
159
+ return {
160
+ activeProcesses: this.#activeProcesses,
161
+ maxConcurrent: this.#maxConcurrent,
162
+ conversationCount: this.#conversations.size,
163
+ };
164
+ }
165
+
166
+ // --- Private methods ---
167
+
168
+ /**
169
+ * Get a stable conversation ID from context.
170
+ *
171
+ * @param {Object} context
172
+ * @returns {string}
173
+ */
174
+ #getConversationId(context) {
175
+ return `${context.platform || 'unknown'}:${context.chatId || 'default'}`;
176
+ }
177
+
178
+ /**
179
+ * Add a message to conversation history.
180
+ *
181
+ * @param {string} conversationId
182
+ * @param {string} role
183
+ * @param {string} content
184
+ */
185
+ #addMessage(conversationId, role, content) {
186
+ if (!this.#conversations.has(conversationId)) {
187
+ this.#conversations.set(conversationId, []);
188
+ }
189
+
190
+ const history = this.#conversations.get(conversationId);
191
+ history.push({
192
+ role,
193
+ content,
194
+ timestamp: new Date().toISOString(),
195
+ });
196
+
197
+ // Trim to max context size
198
+ while (history.length > this.#maxContextMessages * 2) {
199
+ history.shift();
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Build a prompt that includes conversation context.
205
+ *
206
+ * @param {string} conversationId
207
+ * @param {string} currentMessage
208
+ * @returns {string}
209
+ */
210
+ #buildPrompt(conversationId, currentMessage) {
211
+ const history = this.#conversations.get(conversationId) || [];
212
+
213
+ // If there's only the current message, just return it
214
+ if (history.length <= 1) {
215
+ return currentMessage;
216
+ }
217
+
218
+ // Build context from previous messages (excluding the current one which was just added)
219
+ const contextMessages = history.slice(0, -1).slice(-this.#maxContextMessages);
220
+
221
+ if (contextMessages.length === 0) {
222
+ return currentMessage;
223
+ }
224
+
225
+ const contextBlock = contextMessages
226
+ .map((msg) => `${msg.role === 'user' ? 'User' : 'Assistant'}: ${msg.content}`)
227
+ .join('\n');
228
+
229
+ return `Previous conversation context:\n${contextBlock}\n\nCurrent message:\n${currentMessage}`;
230
+ }
231
+
232
+ /**
233
+ * Spawn the AI agent and return its response.
234
+ *
235
+ * @param {string} prompt
236
+ * @returns {Promise<string>}
237
+ */
238
+ #spawnAgent(prompt) {
239
+ return new Promise((resolve, reject) => {
240
+ const args = [...this.#agentArgs, '-p', prompt];
241
+ let stdout = '';
242
+ let stderr = '';
243
+
244
+ const proc = spawn(this.#agentCommand, args, {
245
+ cwd: this.#cwd,
246
+ stdio: ['ignore', 'pipe', 'pipe'],
247
+ env: { ...(this.#environment ?? process.env) },
248
+ });
249
+
250
+ const timeout = setTimeout(() => {
251
+ try {
252
+ signalChild(proc, 'SIGTERM');
253
+ } catch {
254
+ // Process may have already exited
255
+ }
256
+ reject(new Error('AI response timed out'));
257
+ }, this.#timeoutMs);
258
+
259
+ proc.stdout.on('data', (chunk) => {
260
+ stdout += chunk.toString();
261
+ });
262
+
263
+ proc.stderr.on('data', (chunk) => {
264
+ stderr += chunk.toString();
265
+ });
266
+
267
+ proc.on('exit', (code, signal) => {
268
+ clearTimeout(timeout);
269
+ if (signal === 'SIGTERM' || signal === 'SIGKILL') {
270
+ reject(new Error('AI process was terminated'));
271
+ } else if (code === 0) {
272
+ resolve(stdout.trim());
273
+ } else {
274
+ reject(new Error(`AI process exited with code ${code}`));
275
+ }
276
+ });
277
+
278
+ proc.on('error', (err) => {
279
+ clearTimeout(timeout);
280
+ reject(new Error(`Failed to spawn AI: ${err.message}`));
281
+ });
282
+ });
283
+ }
284
+
285
+ /**
286
+ * Truncate response to fit platform limits.
287
+ *
288
+ * @param {string} response
289
+ * @returns {string}
290
+ */
291
+ #truncateResponse(response) {
292
+ if (response.length <= this.#maxResponseLength) {
293
+ return response;
294
+ }
295
+ return response.slice(0, this.#maxResponseLength - 20) + '\n\n[...truncated]';
296
+ }
297
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Inbound command router for messaging platform commands.
3
+ *
4
+ * Parses commands from messaging platforms (e.g., /status, /approve gate-123)
5
+ * and dispatches them to registered handlers with permission checking.
6
+ *
7
+ * @implements @.aiwg/architecture/adrs/ADR-messaging-bot-mode.md
8
+ */
9
+
10
+ import { COMMANDS, CommandPermission } from './types.mjs';
11
+
12
+ /**
13
+ * @typedef {Object} CommandContext
14
+ * @property {string} platform - Source platform (slack, discord, telegram)
15
+ * @property {string} userId - Platform user ID
16
+ * @property {string} channelId - Channel/chat ID
17
+ * @property {string} [threadId] - Thread/reply ID if applicable
18
+ * @property {string} [guildId] - Discord guild ID if applicable
19
+ * @property {Record<string, unknown>} [metadata] - Platform-specific metadata
20
+ */
21
+
22
+ /**
23
+ * @typedef {Object} CommandResult
24
+ * @property {boolean} success
25
+ * @property {string} [message] - Response message
26
+ * @property {Record<string, unknown>} [data] - Structured response data
27
+ * @property {string} [error] - Error message if !success
28
+ */
29
+
30
+ /**
31
+ * @callback CommandHandler
32
+ * @param {string[]} args - Parsed command arguments
33
+ * @param {CommandContext} context
34
+ * @returns {Promise<CommandResult>}
35
+ */
36
+
37
+ export class CommandRouter {
38
+ /** @type {Map<string, CommandHandler>} */
39
+ #handlers;
40
+
41
+ /** @type {Map<string, Set<string>>} */
42
+ #userPermissions;
43
+
44
+ /** @type {Set<string>} */
45
+ #defaultReadUsers;
46
+
47
+ /** @type {(userId: string, permission: string) => boolean} */
48
+ #permissionChecker;
49
+
50
+ /** @type {number} */
51
+ #rateLimitWindowMs;
52
+
53
+ /** @type {number} */
54
+ #rateLimitMaxRequests;
55
+
56
+ /** @type {Map<string, {count: number, resetAt: number}>} */
57
+ #rateLimitBuckets;
58
+
59
+ /**
60
+ * @param {Object} [options]
61
+ * @param {(userId: string, permission: string) => boolean} [options.permissionChecker]
62
+ * @param {number} [options.rateLimitWindowMs=60000]
63
+ * @param {number} [options.rateLimitMaxRequests=10]
64
+ */
65
+ constructor({
66
+ permissionChecker,
67
+ rateLimitWindowMs = 60_000,
68
+ rateLimitMaxRequests = 10,
69
+ } = {}) {
70
+ this.#handlers = new Map();
71
+ this.#userPermissions = new Map();
72
+ this.#defaultReadUsers = new Set();
73
+ this.#permissionChecker = permissionChecker || this.#defaultPermissionCheck.bind(this);
74
+ this.#rateLimitWindowMs = rateLimitWindowMs;
75
+ this.#rateLimitMaxRequests = rateLimitMaxRequests;
76
+ this.#rateLimitBuckets = new Map();
77
+ }
78
+
79
+ /**
80
+ * Register a command handler.
81
+ *
82
+ * @param {string} command - Command name (without /)
83
+ * @param {CommandHandler} handler
84
+ */
85
+ registerHandler(command, handler) {
86
+ this.#handlers.set(command, handler);
87
+ }
88
+
89
+ /**
90
+ * Parse and dispatch a command string.
91
+ *
92
+ * @param {string} rawInput - Raw command input (e.g., "/status" or "approve gate-123")
93
+ * @param {CommandContext} context
94
+ * @returns {Promise<CommandResult>}
95
+ */
96
+ async dispatch(rawInput, context) {
97
+ // Parse command and arguments
98
+ const { command, args } = this.#parseCommand(rawInput);
99
+
100
+ if (!command) {
101
+ return { success: false, error: 'Empty command' };
102
+ }
103
+
104
+ // Check if command exists
105
+ const commandDef = COMMANDS[command];
106
+ if (!commandDef) {
107
+ return {
108
+ success: false,
109
+ error: `Unknown command: "${command}". Available: ${Object.keys(COMMANDS).join(', ')}`,
110
+ };
111
+ }
112
+
113
+ // Check rate limit
114
+ if (!this.#checkRateLimit(context.userId)) {
115
+ return {
116
+ success: false,
117
+ error: 'Rate limit exceeded. Please wait before sending more commands.',
118
+ };
119
+ }
120
+
121
+ // Check permission
122
+ if (!this.#permissionChecker(context.userId, commandDef.permission)) {
123
+ return {
124
+ success: false,
125
+ error: `Permission denied: "${command}" requires "${commandDef.permission}" permission`,
126
+ };
127
+ }
128
+
129
+ // Find handler
130
+ const handler = this.#handlers.get(command);
131
+ if (!handler) {
132
+ return {
133
+ success: false,
134
+ error: `No handler registered for command: "${command}"`,
135
+ };
136
+ }
137
+
138
+ // Execute handler
139
+ try {
140
+ const result = await handler(args, context);
141
+ return result;
142
+ } catch (error) {
143
+ console.error(`[CommandRouter] Error executing "${command}":`, error);
144
+ return {
145
+ success: false,
146
+ error: `Command failed: ${error.message}`,
147
+ };
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Grant a permission level to a user.
153
+ *
154
+ * @param {string} userId
155
+ * @param {string} permission - 'read' or 'write'
156
+ */
157
+ grantPermission(userId, permission) {
158
+ if (!this.#userPermissions.has(userId)) {
159
+ this.#userPermissions.set(userId, new Set());
160
+ }
161
+ this.#userPermissions.get(userId).add(permission);
162
+ }
163
+
164
+ /**
165
+ * Revoke a permission from a user.
166
+ *
167
+ * @param {string} userId
168
+ * @param {string} permission
169
+ */
170
+ revokePermission(userId, permission) {
171
+ const perms = this.#userPermissions.get(userId);
172
+ if (perms) {
173
+ perms.delete(permission);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Grant default read access to a user (any user can read by default).
179
+ *
180
+ * @param {string} userId
181
+ */
182
+ grantDefaultRead(userId) {
183
+ this.#defaultReadUsers.add(userId);
184
+ }
185
+
186
+ /**
187
+ * Get help text for all commands.
188
+ *
189
+ * @returns {string}
190
+ */
191
+ getHelpText() {
192
+ const lines = ['Available commands:', ''];
193
+ for (const [name, def] of Object.entries(COMMANDS)) {
194
+ const permBadge = def.permission === CommandPermission.WRITE ? '[WRITE]' : '[READ]';
195
+ lines.push(` /${name} ${permBadge} - ${def.description}`);
196
+ }
197
+ return lines.join('\n');
198
+ }
199
+
200
+ /**
201
+ * Get registered handler count.
202
+ *
203
+ * @returns {number}
204
+ */
205
+ get handlerCount() {
206
+ return this.#handlers.size;
207
+ }
208
+
209
+ /**
210
+ * Parse raw command input into command name and arguments.
211
+ *
212
+ * @param {string} rawInput
213
+ * @returns {{command: string|null, args: string[]}}
214
+ */
215
+ #parseCommand(rawInput) {
216
+ const trimmed = rawInput.trim();
217
+ if (!trimmed) {
218
+ return { command: null, args: [] };
219
+ }
220
+
221
+ // Remove leading / if present
222
+ const normalized = trimmed.startsWith('/') ? trimmed.slice(1) : trimmed;
223
+ const parts = normalized.split(/\s+/);
224
+ const command = parts[0].toLowerCase();
225
+ const args = parts.slice(1);
226
+
227
+ return { command, args };
228
+ }
229
+
230
+ /**
231
+ * Default permission checker - read is open, write requires explicit grant.
232
+ *
233
+ * @param {string} userId
234
+ * @param {string} requiredPermission
235
+ * @returns {boolean}
236
+ */
237
+ #defaultPermissionCheck(userId, requiredPermission) {
238
+ // Read is open to everyone
239
+ if (requiredPermission === CommandPermission.READ) {
240
+ return true;
241
+ }
242
+
243
+ // Write requires explicit permission
244
+ const perms = this.#userPermissions.get(userId);
245
+ return perms?.has(CommandPermission.WRITE) || false;
246
+ }
247
+
248
+ /**
249
+ * Check and update rate limit for a user.
250
+ *
251
+ * @param {string} userId
252
+ * @returns {boolean} true if within limit
253
+ */
254
+ #checkRateLimit(userId) {
255
+ const now = Date.now();
256
+ const bucket = this.#rateLimitBuckets.get(userId);
257
+
258
+ if (!bucket || now > bucket.resetAt) {
259
+ this.#rateLimitBuckets.set(userId, {
260
+ count: 1,
261
+ resetAt: now + this.#rateLimitWindowMs,
262
+ });
263
+ return true;
264
+ }
265
+
266
+ bucket.count++;
267
+ return bucket.count <= this.#rateLimitMaxRequests;
268
+ }
269
+ }