@aiwg/cli 2026.10.15 → 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.
- package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
- package/dist/src/artifacts/citation-parser.js +7 -6
- package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
- package/dist/src/artifacts/corpus-tools/cli.js +8 -3
- package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
- package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
- package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
- package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
- package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
- package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
- package/dist/src/artifacts/corpus-tools/expand.js +16 -17
- package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
- package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
- package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
- package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
- package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
- package/dist/src/artifacts/corpus-tools/resolve.js +23 -9
- package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
- package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
- package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
- package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
- package/dist/src/artifacts/graph-query.js +5 -3
- package/dist/src/artifacts/hybrid-query.js +11 -2
- package/dist/src/artifacts/index-refresh.js +2 -0
- package/dist/src/cli/handlers/daemon.js +17 -1
- package/dist/src/cli/handlers/doctor-args.js +10 -5
- package/dist/src/cli/handlers/doctor-help.js +4 -1
- package/dist/src/cli/handlers/index.js +2 -2
- package/dist/src/cli/handlers/models-resource-sample.js +10 -0
- package/dist/src/cli/handlers/models.js +3 -2
- package/dist/src/cli/handlers/regenerate.js +8 -16
- package/dist/src/cli/handlers/sessions.js +7 -7
- package/dist/src/cli/handlers/subcommands.js +8 -0
- package/dist/src/cli/handlers/update.js +157 -0
- package/dist/src/cli/handlers/use.js +14 -4
- package/dist/src/cli/handlers/utilities.js +3 -560
- package/dist/src/cli/handlers/utility-doctor.js +412 -0
- package/dist/src/cli/services/deployment-verification.js +0 -1
- package/dist/src/config/aiwg-config.js +2 -1
- package/dist/src/config/authorization-cli.js +7 -3
- package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
- package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
- package/dist/src/config/framework-aliases.js +12 -0
- package/dist/src/config/host-resource-report.d.mts +19 -0
- package/dist/src/config/host-resource-report.mjs +80 -0
- package/dist/src/config/host-resource-runtime.d.mts +34 -0
- package/dist/src/config/host-resource-runtime.mjs +293 -0
- package/dist/src/config/installed-selection.js +22 -0
- package/dist/src/config/worker-invocation-marker.d.mts +1 -0
- package/dist/src/config/worker-invocation-marker.mjs +2 -0
- package/dist/src/decision/heldout/access.js +74 -0
- package/dist/src/decision/heldout/calibration.js +1 -0
- package/dist/src/decision/heldout/collector.js +8 -1
- package/dist/src/effects/verifiers/file.js +22 -5
- package/dist/src/extensions/claude-attribution.js +82 -0
- package/dist/src/extensions/claude-hooks-installer.js +115 -69
- package/dist/src/extensions/commands/daemon.js +109 -0
- package/dist/src/extensions/commands/definitions.js +5 -89
- package/dist/src/gates/heldout.js +17 -7
- package/dist/src/lint/check-patterns.js +163 -0
- package/dist/src/lint/checks.js +268 -0
- package/dist/src/lint/reference-resolution.js +54 -0
- package/dist/src/lint/runner.js +3 -465
- package/dist/src/mcp/helpers.mjs +11 -1
- package/dist/src/memory/project-registry.js +44 -4
- package/dist/src/models/worker-plan.js +36 -5
- package/dist/src/models/wrapper-deployment.js +25 -12
- package/dist/src/models/wrapper-enforcement.js +47 -7
- package/dist/src/network-analysis/research.js +2 -1
- package/dist/src/policy/hitl-check.js +14 -4
- package/dist/src/policy/hitl-consume.js +54 -0
- package/dist/src/policy/hitl-receipt.js +2 -0
- package/dist/src/policy/hitl.js +11 -3
- package/dist/src/providers/provider-context-contracts.js +162 -0
- package/dist/src/providers/provider-definition-schema.js +136 -0
- package/dist/src/providers/provider-definitions.js +8 -1298
- package/dist/src/providers/provider-seeds-1.js +360 -0
- package/dist/src/providers/provider-seeds-2.js +387 -0
- package/dist/src/providers/provider-seeds-3.js +262 -0
- package/dist/src/research/clients/arxiv.js +4 -30
- package/dist/src/research/clients/base.js +48 -22
- package/dist/src/research/identity.js +34 -2
- package/dist/src/research/query-cli.js +3 -87
- package/dist/src/research/query-options.js +87 -0
- package/dist/src/research/reference-match.js +70 -24
- package/dist/src/research/services/acquisition.js +9 -7
- package/dist/src/research/services/citation.js +5 -2
- package/dist/src/research/types.js +2 -0
- package/dist/src/serve/mission-conductor.js +48 -4
- package/dist/src/sessions/adapters/grok-build-native.js +23 -0
- package/dist/src/sessions/adapters/grok-build.js +14 -7
- package/dist/src/sessions/workspace-discovery.js +5 -5
- package/dist/src/smiths/context-pipeline/aiwg-md.js +16 -46
- package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
- package/dist/src/smiths/context-pipeline/finalization.js +81 -51
- package/dist/src/smiths/context-pipeline/generator.js +9 -10
- package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
- package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
- package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
- package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
- package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
- package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
- package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
- package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
- package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
- package/package.json +10 -1
- package/schemas/decision/D29Study.v10.schema.json +65 -0
- package/tools/agents/deploy-agents.mjs +10 -0
- package/tools/agents/providers/claude-post-deploy.mjs +12 -1
- package/tools/agents/providers/context-write.mjs +4 -0
- package/tools/agents/providers/pi.mjs +3 -1
- package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
- package/tools/agents/providers/rule-delivery.mjs +20 -1144
- package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
- package/tools/agents/providers/rule-deployment-state.mjs +300 -0
- package/tools/daemon/README.md +511 -0
- package/tools/daemon/adapters/base-adapter.mjs +84 -0
- package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
- package/tools/daemon/agent-supervisor.mjs +299 -0
- package/tools/daemon/automation-engine.mjs +310 -0
- package/tools/daemon/autonomous-engine.mjs +346 -0
- package/tools/daemon/behavior-loader.mjs +316 -0
- package/tools/daemon/behavior.mjs +174 -0
- package/tools/daemon/concierge/intent-router.mjs +401 -0
- package/tools/daemon/concierge/orchestrator.mjs +272 -0
- package/tools/daemon/concierge/response-translator.mjs +462 -0
- package/tools/daemon/config.mjs +377 -0
- package/tools/daemon/cron-scheduler.mjs +178 -0
- package/tools/daemon/daemon-main.mjs +1169 -0
- package/tools/daemon/event-router.mjs +84 -0
- package/tools/daemon/file-watcher.mjs +383 -0
- package/tools/daemon/index.mjs +1181 -0
- package/tools/daemon/init-profile.mjs +124 -0
- package/tools/daemon/ipc-client.mjs +197 -0
- package/tools/daemon/ipc-ops-handlers.mjs +236 -0
- package/tools/daemon/ipc-server.mjs +275 -0
- package/tools/daemon/maintenance-owner.mjs +79 -0
- package/tools/daemon/memory-manager.mjs +386 -0
- package/tools/daemon/message-router.mjs +194 -0
- package/tools/daemon/provider-watcher.mjs +585 -0
- package/tools/daemon/pty-adapter.mjs +420 -0
- package/tools/daemon/repl-chat.mjs +359 -0
- package/tools/daemon/resource-bounds.mjs +88 -0
- package/tools/daemon/sandbox-transport.mjs +295 -0
- package/tools/daemon/scheduled-task-runner.mjs +535 -0
- package/tools/daemon/task-store.mjs +450 -0
- package/tools/daemon/tmux-manager.mjs +324 -0
- package/tools/daemon/update-policy.mjs +517 -0
- package/tools/daemon/web-server.mjs +399 -0
- package/tools/daemon/web-ui/index.html +585 -0
- package/tools/daemon/web-ui/styles.css +156 -0
- package/tools/docker/Dockerfile.daemon +35 -0
- package/tools/docker/container-manager.mjs +291 -0
- package/tools/messaging/adapter-registry.mjs +230 -0
- package/tools/messaging/adapters/base.mjs +326 -0
- package/tools/messaging/adapters/discord.mjs +462 -0
- package/tools/messaging/adapters/slack.mjs +402 -0
- package/tools/messaging/adapters/telegram.mjs +552 -0
- package/tools/messaging/chat-handler.mjs +297 -0
- package/tools/messaging/command-router.mjs +269 -0
- package/tools/messaging/event-bus.mjs +199 -0
- package/tools/messaging/index.mjs +456 -0
- package/tools/messaging/message-formatter.mjs +320 -0
- package/tools/messaging/room-manager.mjs +277 -0
- package/tools/messaging/types.mjs +94 -0
- package/tools/providers/pi-bridge-policy.mjs +4 -0
- package/tools/ralph-external/daemon-supervisor.mjs +394 -0
- package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
- package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
- package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
- package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
- package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
- package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
- package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
- package/tools/ralph-external/session-launcher.mjs +7 -7
- 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
|
+
}
|