@mainwp/control 1.0.1 → 1.1.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 (169) hide show
  1. package/CHANGELOG.md +156 -0
  2. package/README.md +136 -516
  3. package/dist/chat/chat-engine.d.ts +24 -54
  4. package/dist/chat/chat-engine.d.ts.map +1 -1
  5. package/dist/chat/chat-engine.js +345 -166
  6. package/dist/chat/chat-engine.js.map +1 -1
  7. package/dist/chat/context-window.d.ts +57 -0
  8. package/dist/chat/context-window.d.ts.map +1 -0
  9. package/dist/chat/context-window.js +94 -0
  10. package/dist/chat/context-window.js.map +1 -0
  11. package/dist/chat/providers/anthropic.d.ts +0 -4
  12. package/dist/chat/providers/anthropic.d.ts.map +1 -1
  13. package/dist/chat/providers/anthropic.js +67 -45
  14. package/dist/chat/providers/anthropic.js.map +1 -1
  15. package/dist/chat/providers/gemini.d.ts +2 -2
  16. package/dist/chat/providers/gemini.d.ts.map +1 -1
  17. package/dist/chat/providers/gemini.js +67 -43
  18. package/dist/chat/providers/gemini.js.map +1 -1
  19. package/dist/chat/providers/openai-compatible.d.ts +1 -1
  20. package/dist/chat/providers/openai-compatible.d.ts.map +1 -1
  21. package/dist/chat/providers/openai-compatible.js +91 -29
  22. package/dist/chat/providers/openai-compatible.js.map +1 -1
  23. package/dist/chat/providers/provider-fetch.d.ts +11 -0
  24. package/dist/chat/providers/provider-fetch.d.ts.map +1 -1
  25. package/dist/chat/providers/provider-fetch.js +86 -4
  26. package/dist/chat/providers/provider-fetch.js.map +1 -1
  27. package/dist/chat/providers/provider.d.ts +74 -1
  28. package/dist/chat/providers/provider.d.ts.map +1 -1
  29. package/dist/chat/providers/provider.js +112 -2
  30. package/dist/chat/providers/provider.js.map +1 -1
  31. package/dist/chat/providers/sse-reader.d.ts +3 -0
  32. package/dist/chat/providers/sse-reader.d.ts.map +1 -1
  33. package/dist/chat/providers/sse-reader.js +75 -15
  34. package/dist/chat/providers/sse-reader.js.map +1 -1
  35. package/dist/chat/system-prompt.d.ts +0 -2
  36. package/dist/chat/system-prompt.d.ts.map +1 -1
  37. package/dist/chat/system-prompt.js +10 -6
  38. package/dist/chat/system-prompt.js.map +1 -1
  39. package/dist/chat/tool-envelope.d.ts +3 -0
  40. package/dist/chat/tool-envelope.d.ts.map +1 -1
  41. package/dist/chat/tool-envelope.js +156 -10
  42. package/dist/chat/tool-envelope.js.map +1 -1
  43. package/dist/commands/abilities/info.d.ts.map +1 -1
  44. package/dist/commands/abilities/info.js +6 -3
  45. package/dist/commands/abilities/info.js.map +1 -1
  46. package/dist/commands/abilities/list.d.ts.map +1 -1
  47. package/dist/commands/abilities/list.js +59 -3
  48. package/dist/commands/abilities/list.js.map +1 -1
  49. package/dist/commands/abilities/run.d.ts.map +1 -1
  50. package/dist/commands/abilities/run.js +126 -41
  51. package/dist/commands/abilities/run.js.map +1 -1
  52. package/dist/commands/chat.d.ts +12 -0
  53. package/dist/commands/chat.d.ts.map +1 -1
  54. package/dist/commands/chat.js +61 -27
  55. package/dist/commands/chat.js.map +1 -1
  56. package/dist/commands/config/show.d.ts.map +1 -1
  57. package/dist/commands/config/show.js +59 -47
  58. package/dist/commands/config/show.js.map +1 -1
  59. package/dist/commands/doctor.d.ts +0 -8
  60. package/dist/commands/doctor.d.ts.map +1 -1
  61. package/dist/commands/doctor.js +23 -37
  62. package/dist/commands/doctor.js.map +1 -1
  63. package/dist/commands/jobs/watch.d.ts +4 -0
  64. package/dist/commands/jobs/watch.d.ts.map +1 -1
  65. package/dist/commands/jobs/watch.js +66 -27
  66. package/dist/commands/jobs/watch.js.map +1 -1
  67. package/dist/commands/login.d.ts.map +1 -1
  68. package/dist/commands/login.js +59 -10
  69. package/dist/commands/login.js.map +1 -1
  70. package/dist/commands/profile/delete.d.ts.map +1 -1
  71. package/dist/commands/profile/delete.js +19 -3
  72. package/dist/commands/profile/delete.js.map +1 -1
  73. package/dist/commands/profile/list.d.ts.map +1 -1
  74. package/dist/commands/profile/list.js +6 -2
  75. package/dist/commands/profile/list.js.map +1 -1
  76. package/dist/commands/profile/use.d.ts.map +1 -1
  77. package/dist/commands/profile/use.js +4 -1
  78. package/dist/commands/profile/use.js.map +1 -1
  79. package/dist/config/fs-utils.d.ts.map +1 -1
  80. package/dist/config/fs-utils.js +19 -6
  81. package/dist/config/fs-utils.js.map +1 -1
  82. package/dist/config/keychain.d.ts +78 -6
  83. package/dist/config/keychain.d.ts.map +1 -1
  84. package/dist/config/keychain.js +194 -27
  85. package/dist/config/keychain.js.map +1 -1
  86. package/dist/config/profile-store.d.ts +11 -3
  87. package/dist/config/profile-store.d.ts.map +1 -1
  88. package/dist/config/profile-store.js +53 -19
  89. package/dist/config/profile-store.js.map +1 -1
  90. package/dist/core/abilities-executor.d.ts +23 -5
  91. package/dist/core/abilities-executor.d.ts.map +1 -1
  92. package/dist/core/abilities-executor.js +137 -42
  93. package/dist/core/abilities-executor.js.map +1 -1
  94. package/dist/core/batch-manager.d.ts +10 -5
  95. package/dist/core/batch-manager.d.ts.map +1 -1
  96. package/dist/core/batch-manager.js +78 -22
  97. package/dist/core/batch-manager.js.map +1 -1
  98. package/dist/core/execute-ability-with-policy.d.ts +8 -0
  99. package/dist/core/execute-ability-with-policy.d.ts.map +1 -0
  100. package/dist/core/execute-ability-with-policy.js +19 -0
  101. package/dist/core/execute-ability-with-policy.js.map +1 -0
  102. package/dist/core/http-client.d.ts +4 -0
  103. package/dist/core/http-client.d.ts.map +1 -1
  104. package/dist/core/http-client.js +116 -44
  105. package/dist/core/http-client.js.map +1 -1
  106. package/dist/core/job-id.d.ts +2 -0
  107. package/dist/core/job-id.d.ts.map +1 -0
  108. package/dist/core/job-id.js +22 -0
  109. package/dist/core/job-id.js.map +1 -0
  110. package/dist/core/safety-controller.d.ts +20 -10
  111. package/dist/core/safety-controller.d.ts.map +1 -1
  112. package/dist/core/safety-controller.js +87 -35
  113. package/dist/core/safety-controller.js.map +1 -1
  114. package/dist/lib/base-command.d.ts +20 -0
  115. package/dist/lib/base-command.d.ts.map +1 -1
  116. package/dist/lib/base-command.js +92 -35
  117. package/dist/lib/base-command.js.map +1 -1
  118. package/dist/output/formatter.d.ts +36 -0
  119. package/dist/output/formatter.d.ts.map +1 -1
  120. package/dist/output/formatter.js +105 -15
  121. package/dist/output/formatter.js.map +1 -1
  122. package/dist/output/json-envelope.d.ts.map +1 -1
  123. package/dist/output/json-envelope.js +8 -5
  124. package/dist/output/json-envelope.js.map +1 -1
  125. package/dist/utils/audit-logger.d.ts +26 -8
  126. package/dist/utils/audit-logger.d.ts.map +1 -1
  127. package/dist/utils/audit-logger.js +93 -20
  128. package/dist/utils/audit-logger.js.map +1 -1
  129. package/dist/utils/error-sanitizer.d.ts +6 -0
  130. package/dist/utils/error-sanitizer.d.ts.map +1 -0
  131. package/dist/utils/error-sanitizer.js +120 -0
  132. package/dist/utils/error-sanitizer.js.map +1 -0
  133. package/dist/utils/errors.d.ts +12 -0
  134. package/dist/utils/errors.d.ts.map +1 -1
  135. package/dist/utils/errors.js +14 -0
  136. package/dist/utils/errors.js.map +1 -1
  137. package/dist/utils/format.d.ts +68 -0
  138. package/dist/utils/format.d.ts.map +1 -1
  139. package/dist/utils/format.js +668 -0
  140. package/dist/utils/format.js.map +1 -1
  141. package/dist/utils/prompt.d.ts.map +1 -1
  142. package/dist/utils/prompt.js +25 -24
  143. package/dist/utils/prompt.js.map +1 -1
  144. package/dist/utils/redaction.d.ts +21 -0
  145. package/dist/utils/redaction.d.ts.map +1 -0
  146. package/dist/utils/redaction.js +85 -0
  147. package/dist/utils/redaction.js.map +1 -0
  148. package/dist/utils/retry.d.ts +0 -4
  149. package/dist/utils/retry.d.ts.map +1 -1
  150. package/dist/utils/retry.js +0 -9
  151. package/dist/utils/retry.js.map +1 -1
  152. package/dist/utils/terminal-sanitizer.d.ts +21 -0
  153. package/dist/utils/terminal-sanitizer.d.ts.map +1 -1
  154. package/dist/utils/terminal-sanitizer.js +80 -14
  155. package/dist/utils/terminal-sanitizer.js.map +1 -1
  156. package/dist/validation/input-sanitizer.d.ts +0 -4
  157. package/dist/validation/input-sanitizer.d.ts.map +1 -1
  158. package/dist/validation/input-sanitizer.js +15 -64
  159. package/dist/validation/input-sanitizer.js.map +1 -1
  160. package/dist/validation/sanitize-schema.d.ts +31 -0
  161. package/dist/validation/sanitize-schema.d.ts.map +1 -0
  162. package/dist/validation/sanitize-schema.js +158 -0
  163. package/dist/validation/sanitize-schema.js.map +1 -0
  164. package/dist/validation/schema-validator.d.ts +10 -0
  165. package/dist/validation/schema-validator.d.ts.map +1 -1
  166. package/dist/validation/schema-validator.js +50 -5
  167. package/dist/validation/schema-validator.js.map +1 -1
  168. package/oclif.manifest.json +23 -1
  169. package/package.json +21 -7
@@ -14,8 +14,71 @@ import { buildConfiguredPrompt, defaultConfig as defaultPromptConfig, } from './
14
14
  import { parseResponse, isRetryable, buildRetryPrompt, } from './tool-envelope.js';
15
15
  import { SafetyController, } from '../core/safety-controller.js';
16
16
  import { abilityToTool } from './providers/provider.js';
17
+ import { ContextWindow } from './context-window.js';
17
18
  import { logDestructiveActionSafe } from '../utils/audit-logger.js';
18
19
  import { getInputSanitizer } from '../validation/input-sanitizer.js';
20
+ import { getSchemaValidator } from '../validation/schema-validator.js';
21
+ import { SchemaValidationError } from '../utils/errors.js';
22
+ import { stripControlChars } from '../utils/terminal-sanitizer.js';
23
+ import { redactSensitiveKeys } from '../utils/redaction.js';
24
+ import { executeAbilityWithPolicy } from '../core/execute-ability-with-policy.js';
25
+ /**
26
+ * Largest streamed response body accumulated into a single LLM response.
27
+ *
28
+ * The provider stream is unbounded on its own and the SSE window runs for
29
+ * minutes, so this is the size cap for the non-streaming path's equivalent.
30
+ * 1MB is far beyond any real tool envelope or chat answer.
31
+ */
32
+ const MAX_STREAM_CONTENT_LENGTH = 1_048_576;
33
+ /**
34
+ * Tool calls retained from one streamed response.
35
+ *
36
+ * The envelope accepts exactly one call, so two is everything a truthful
37
+ * "received N" protocol error needs; the rest is memory a hostile endpoint
38
+ * controls. Without this, thousands of calls accumulate before the envelope
39
+ * ever sees the response.
40
+ */
41
+ const MAX_STREAM_TOOL_CALLS = 2;
42
+ /**
43
+ * Aggregate size of the tool-call arguments retained from one streamed
44
+ * response, mirroring the content cap.
45
+ */
46
+ const MAX_STREAM_TOOL_ARGUMENTS_LENGTH = 1_048_576;
47
+ /**
48
+ * Size of one streamed tool call's arguments, for the aggregate cap.
49
+ *
50
+ * Arguments are the provider's parsed JSON, or the raw string when it did not
51
+ * parse (the envelope rejects that as a protocol error). Serializing is the
52
+ * only way to price the parsed form; a value that cannot be serialized is
53
+ * charged the whole budget rather than being treated as free.
54
+ */
55
+ function measureToolArguments(args) {
56
+ if (typeof args === 'string') {
57
+ return args.length;
58
+ }
59
+ try {
60
+ return JSON.stringify(args)?.length ?? 0;
61
+ }
62
+ catch {
63
+ return MAX_STREAM_TOOL_ARGUMENTS_LENGTH;
64
+ }
65
+ }
66
+ /**
67
+ * Truncate to `limit` UTF-16 units without splitting a surrogate pair.
68
+ *
69
+ * A plain slice can cut between the halves of an astral character (emoji,
70
+ * many CJK extensions) and leave a lone surrogate, which serializes as a
71
+ * replacement character and can corrupt the tail of the response.
72
+ */
73
+ function truncateWholeCodePoints(text, limit) {
74
+ const cut = text.slice(0, limit);
75
+ const lastCode = cut.charCodeAt(cut.length - 1);
76
+ // High surrogate at the boundary means its low half was cut off.
77
+ if (lastCode >= 0xd800 && lastCode <= 0xdbff) {
78
+ return cut.slice(0, -1);
79
+ }
80
+ return cut;
81
+ }
19
82
  /**
20
83
  * Chat engine class
21
84
  *
@@ -35,14 +98,20 @@ export class ChatEngine {
35
98
  model;
36
99
  temperature;
37
100
  promptConfig;
38
- maxContextMessages;
101
+ contextWindow;
39
102
  stream;
40
103
  onStreamChunk;
41
104
  messages = [];
42
105
  abilities = [];
43
106
  tools = [];
107
+ toolAliases = new Map();
108
+ abilityAliases = new Map();
44
109
  pendingPreview = null;
45
110
  initialized = false;
111
+ // Engine-lifetime counter for fallback tool-call IDs. A per-turn counter
112
+ // would repeat call_1, call_2, ... across turns while history is retained,
113
+ // producing duplicate IDs in the conversation sent to providers.
114
+ fallbackToolCallId = 0;
46
115
  constructor(options) {
47
116
  this.provider = options.provider;
48
117
  this.executor = options.executor;
@@ -68,16 +137,11 @@ export class ChatEngine {
68
137
  const resolvedContextMessages = options.maxContextMessages ??
69
138
  options.promptConfig?.maxContextMessages ??
70
139
  defaultPromptConfig.maxContextMessages;
71
- this.maxContextMessages = resolvedContextMessages;
140
+ this.contextWindow = new ContextWindow(resolvedContextMessages);
72
141
  // Sync the resolved value into promptConfig for system prompt generation
73
142
  if (resolvedContextMessages !== undefined) {
74
143
  mergedPromptConfig.maxContextMessages = resolvedContextMessages;
75
144
  }
76
- // Handle optional token limit (reserved for future use)
77
- const contextTokens = options.maxContextTokens ?? options.promptConfig?.maxContextTokens;
78
- if (contextTokens !== undefined) {
79
- mergedPromptConfig.maxContextTokens = contextTokens;
80
- }
81
145
  this.promptConfig = mergedPromptConfig;
82
146
  }
83
147
  /**
@@ -88,18 +152,47 @@ export class ChatEngine {
88
152
  return;
89
153
  // Load abilities
90
154
  this.abilities = await this.executor.listAbilities();
91
- // Convert to tool definitions
92
- this.tools = this.abilities.map((a) => abilityToTool(a.name, a.description, a.input_schema));
155
+ // Convert to protocol-safe tool definitions and keep a collision-checked
156
+ // reverse map so execution always uses the real ability name.
157
+ this.tools = this.abilities.map((ability) => {
158
+ const alias = ability.name.replaceAll('/', '__');
159
+ const existing = this.toolAliases.get(alias);
160
+ if (existing && existing !== ability.name) {
161
+ throw new Error(`Tool alias collision: "${existing}" and "${ability.name}" both map to "${alias}"`);
162
+ }
163
+ this.toolAliases.set(alias, ability.name);
164
+ this.abilityAliases.set(ability.name, alias);
165
+ return abilityToTool(alias, ability.description, ability.input_schema);
166
+ });
93
167
  // Build system prompt
94
168
  const systemPrompt = buildConfiguredPrompt(this.abilities, this.promptConfig);
95
169
  // Initialize message history
96
170
  this.messages = [{ role: 'system', content: systemPrompt }];
97
171
  this.initialized = true;
98
172
  }
173
+ // Serializes sendMessage calls. History and pendingPreview are shared
174
+ // mutable state with no other concurrency protection; the readline REPL
175
+ // happens to serialize calls today, but programmatic callers may not.
176
+ inFlight = Promise.resolve();
99
177
  /**
100
178
  * Send a user message and process the response
179
+ *
180
+ * Concurrent calls are queued and run in call order; a rejected call does
181
+ * not block the calls queued behind it.
101
182
  */
102
183
  async sendMessage(userMessage) {
184
+ const previous = this.inFlight;
185
+ let release;
186
+ this.inFlight = new Promise((resolve) => (release = resolve));
187
+ await previous;
188
+ try {
189
+ return await this.sendMessageSerialized(userMessage);
190
+ }
191
+ finally {
192
+ release();
193
+ }
194
+ }
195
+ async sendMessageSerialized(userMessage) {
103
196
  if (!this.initialized) {
104
197
  await this.initialize();
105
198
  }
@@ -118,6 +211,15 @@ export class ChatEngine {
118
211
  this.truncateHistory();
119
212
  return responses;
120
213
  }
214
+ /**
215
+ * Build the audit-log preview payload for a pending preview
216
+ */
217
+ static previewAuditPayload(preview) {
218
+ return {
219
+ summary: preview.preview.summary,
220
+ affectedCount: preview.preview.affected.length,
221
+ };
222
+ }
121
223
  /**
122
224
  * Handle response to a pending preview
123
225
  */
@@ -131,6 +233,18 @@ export class ChatEngine {
131
233
  lower === 'confirm';
132
234
  if (!approved) {
133
235
  // User declined
236
+ this.messages.push({
237
+ role: 'tool',
238
+ content: JSON.stringify({
239
+ success: false,
240
+ error: {
241
+ code: 'USER_DECLINED',
242
+ message: 'The user declined the destructive action.',
243
+ },
244
+ }),
245
+ toolCallId: preview.toolCallId,
246
+ toolName: preview.toolAlias,
247
+ });
134
248
  this.messages.push({
135
249
  role: 'user',
136
250
  content: userMessage,
@@ -144,10 +258,7 @@ export class ChatEngine {
144
258
  // Log audit entry for declined action (fire-and-forget)
145
259
  await logDestructiveActionSafe({
146
260
  abilityName: preview.ability.name,
147
- preview: {
148
- summary: preview.preview.summary,
149
- affectedCount: preview.preview.affected.length,
150
- },
261
+ preview: ChatEngine.previewAuditPayload(preview),
151
262
  userDecision: 'declined',
152
263
  input: preview.input,
153
264
  });
@@ -160,12 +271,57 @@ export class ChatEngine {
160
271
  },
161
272
  ];
162
273
  }
163
- // User approved - execute with confirm
164
- this.messages.push({
165
- role: 'user',
166
- content: 'User approved: yes',
274
+ // Record the approval BEFORE dispatching the confirm call, so a transport
275
+ // failure (or process death) mid-confirm still leaves durable evidence
276
+ // that an approved destructive action may have reached the Dashboard.
277
+ await logDestructiveActionSafe({
278
+ abilityName: preview.ability.name,
279
+ preview: ChatEngine.previewAuditPayload(preview),
280
+ userDecision: 'approved',
281
+ stage: 'dispatch',
282
+ input: preview.input,
167
283
  });
168
- const result = await this.executor.execute(preview.ability.name, preview.input, { confirm: true });
284
+ // User approved - execute with confirm. A throw here arrives after
285
+ // dispatch was initiated: the outcome is unknown. Fail closed — audit the
286
+ // uncertainty, keep history coherent, and tell the user to verify before
287
+ // retrying. Never auto-retry the confirm.
288
+ let result;
289
+ try {
290
+ result = await executeAbilityWithPolicy(this.executor, preview.ability, preview.input, { confirm: true });
291
+ }
292
+ catch (error) {
293
+ const reason = getInputSanitizer().sanitizeErrorMessage(error instanceof Error ? error.message : String(error));
294
+ await logDestructiveActionSafe({
295
+ abilityName: preview.ability.name,
296
+ preview: ChatEngine.previewAuditPayload(preview),
297
+ userDecision: 'approved',
298
+ execution: { success: false, error: reason, outcomeUnknown: true },
299
+ input: preview.input,
300
+ });
301
+ this.messages.push({
302
+ role: 'tool',
303
+ content: JSON.stringify({
304
+ success: false,
305
+ error: {
306
+ code: 'OUTCOME_UNKNOWN',
307
+ message: 'The confirm call failed after dispatch; the action may or may not have executed. Do not retry without verifying Dashboard state.',
308
+ },
309
+ }),
310
+ toolCallId: preview.toolCallId,
311
+ toolName: preview.toolAlias,
312
+ });
313
+ this.messages.push({ role: 'user', content: userMessage });
314
+ this.truncateHistory();
315
+ return [
316
+ {
317
+ type: 'error',
318
+ error: `Confirm call for "${preview.ability.name}" failed after dispatch: ${reason}. ` +
319
+ 'The Dashboard may or may not have executed the action — verify its state before retrying.',
320
+ tool: preview.ability.name,
321
+ code: 'OUTCOME_UNKNOWN',
322
+ },
323
+ ];
324
+ }
169
325
  // Log audit entry for approved and executed action (fire-and-forget)
170
326
  const executionAudit = {
171
327
  success: result.success,
@@ -175,22 +331,25 @@ export class ChatEngine {
175
331
  }
176
332
  await logDestructiveActionSafe({
177
333
  abilityName: preview.ability.name,
178
- preview: {
179
- summary: preview.preview.summary,
180
- affectedCount: preview.preview.affected.length,
181
- },
334
+ preview: ChatEngine.previewAuditPayload(preview),
182
335
  userDecision: 'approved',
183
336
  execution: executionAudit,
184
337
  input: preview.input,
185
338
  });
186
- // Add result to context
339
+ // Add result to context. PROVIDER BOUNDARY: only a key-redacted copy of
340
+ // the result enters the history sent to the LLM provider; the unredacted
341
+ // result still goes back to the local user below.
187
342
  const toolResultMsg = {
188
343
  role: 'tool',
189
- content: JSON.stringify(result),
190
- toolCallId: `execute_${preview.ability.name}`,
191
- toolName: preview.ability.name,
344
+ content: JSON.stringify(redactSensitiveKeys(result)),
345
+ toolCallId: preview.toolCallId,
346
+ toolName: preview.toolAlias,
192
347
  };
193
348
  this.messages.push(toolResultMsg);
349
+ this.messages.push({
350
+ role: 'user',
351
+ content: 'User approved: yes',
352
+ });
194
353
  // Truncate after preview resolution (safe boundary)
195
354
  this.truncateHistory();
196
355
  return [
@@ -237,6 +396,7 @@ export class ChatEngine {
237
396
  const parseResult = parseResponse(llmResponse, {
238
397
  abilities: this.abilities,
239
398
  validateToolExists: true,
399
+ toolAliases: this.toolAliases,
240
400
  });
241
401
  // Handle parse errors with retry
242
402
  if (parseResult.response.type === 'error') {
@@ -245,7 +405,8 @@ export class ChatEngine {
245
405
  // Add retry prompt
246
406
  this.messages.push({
247
407
  role: 'assistant',
248
- content: llmResponse.content,
408
+ content: llmResponse.content ||
409
+ 'Invalid tool call omitted due to a protocol error.',
249
410
  });
250
411
  this.messages.push({
251
412
  role: 'user',
@@ -276,29 +437,45 @@ export class ChatEngine {
276
437
  // Handle tool call
277
438
  const toolResponse = parseResult.response;
278
439
  toolCallCount++;
440
+ const toolCallId = toolResponse.id ?? `call_${++this.fallbackToolCallId}`;
441
+ const toolAlias = this.abilityAliases.get(toolResponse.tool) ?? toolResponse.tool;
279
442
  // Add assistant message with tool call
280
443
  this.messages.push({
281
444
  role: 'assistant',
282
445
  content: llmResponse.content,
446
+ toolCalls: [
447
+ {
448
+ id: toolCallId,
449
+ name: toolAlias,
450
+ arguments: toolResponse.input,
451
+ ...(toolResponse.thoughtSignature !== undefined
452
+ ? { thoughtSignature: toolResponse.thoughtSignature }
453
+ : {}),
454
+ },
455
+ ],
283
456
  });
284
457
  // Execute tool
285
- const toolResult = await this.executeTool(toolResponse.tool, toolResponse.input);
458
+ const toolResult = await this.executeTool(toolResponse.tool, toolResponse.input, toolCallId, toolAlias);
286
459
  if (toolResult.type === 'preview') {
287
460
  // Preview requires user approval - stop here
288
461
  responses.push(toolResult);
289
462
  break;
290
463
  }
291
464
  responses.push(toolResult);
292
- // Add tool result to context
465
+ // Add tool result to context. PROVIDER BOUNDARY: ability output is
466
+ // Dashboard-controlled data leaving the machine for a third-party LLM
467
+ // provider — redact sensitive-looking keys before it enters history
468
+ // (AGENTS.md: "minimize and redact secrets/customer data"). The
469
+ // unredacted result was already returned to the local user above.
293
470
  if (toolResult.type === 'tool_result') {
294
471
  const resultContent = toolResult.result.success
295
- ? JSON.stringify(toolResult.result.data)
296
- : JSON.stringify(toolResult.result.error);
472
+ ? JSON.stringify(redactSensitiveKeys(toolResult.result.data))
473
+ : JSON.stringify(redactSensitiveKeys(toolResult.result.error));
297
474
  this.messages.push({
298
475
  role: 'tool',
299
476
  content: resultContent,
300
- toolCallId: toolResponse.id ?? `call_${toolCallCount}`,
301
- toolName: toolResponse.tool,
477
+ toolCallId,
478
+ toolName: toolAlias,
302
479
  });
303
480
  // Truncate between tool-call iterations to enforce context limit
304
481
  // This ensures each provider.chat call receives a bounded history
@@ -309,8 +486,8 @@ export class ChatEngine {
309
486
  this.messages.push({
310
487
  role: 'tool',
311
488
  content: JSON.stringify({ error: toolResult.error }),
312
- toolCallId: toolResponse.id ?? `call_${toolCallCount}`,
313
- toolName: toolResponse.tool,
489
+ toolCallId,
490
+ toolName: toolAlias,
314
491
  });
315
492
  break; // Stop on error
316
493
  }
@@ -329,7 +506,7 @@ export class ChatEngine {
329
506
  *
330
507
  * CRITICAL: All execution goes through SafetyController
331
508
  */
332
- async executeTool(toolName, input) {
509
+ async executeTool(toolName, input, toolCallId, toolAlias) {
333
510
  // Find ability
334
511
  const ability = await this.executor.getAbility(toolName);
335
512
  if (!ability) {
@@ -338,16 +515,51 @@ export class ChatEngine {
338
515
  error: `Unknown ability: ${toolName}`,
339
516
  };
340
517
  }
518
+ input = getInputSanitizer().sanitize(input);
519
+ if (ability.input_schema) {
520
+ try {
521
+ const validated = getSchemaValidator().validateOrThrow(input, ability.input_schema, ability.name);
522
+ input = validated.coerced ?? input;
523
+ }
524
+ catch (error) {
525
+ if (error instanceof SchemaValidationError) {
526
+ const validationError = {
527
+ code: error.code,
528
+ message: error.message,
529
+ details: error.details,
530
+ };
531
+ if (error.hint) {
532
+ validationError.hint = error.hint;
533
+ }
534
+ return {
535
+ type: 'tool_result',
536
+ tool: ability.name,
537
+ result: {
538
+ success: false,
539
+ error: validationError,
540
+ },
541
+ };
542
+ }
543
+ // A throw here would leave the already-pushed assistant tool call
544
+ // dangling in history (no matching tool message), corrupting the next
545
+ // provider request. Surface it like the execution catch-all below.
546
+ return {
547
+ type: 'error',
548
+ error: error instanceof Error ? error.message : String(error),
549
+ tool: ability.name,
550
+ };
551
+ }
552
+ }
341
553
  // Check if destructive
342
554
  const classification = this.safetyController.classify(ability);
343
555
  if (classification.requiresSafetyFlow) {
344
556
  // SAFETY: Destructive actions always preview first
345
557
  // AI cannot skip this step
346
- return this.executeWithPreview(ability, input);
558
+ return this.executeWithPreview(ability, input, toolCallId, toolAlias);
347
559
  }
348
560
  // Safe to execute directly
349
561
  try {
350
- const result = await this.executor.execute(ability.name, input);
562
+ const result = await executeAbilityWithPolicy(this.executor, ability, input);
351
563
  return {
352
564
  type: 'tool_result',
353
565
  tool: ability.name,
@@ -358,26 +570,28 @@ export class ChatEngine {
358
570
  return {
359
571
  type: 'error',
360
572
  error: error instanceof Error ? error.message : String(error),
573
+ tool: ability.name,
361
574
  };
362
575
  }
363
576
  }
364
577
  /**
365
578
  * Execute destructive action with preview
366
579
  */
367
- async executeWithPreview(ability, input) {
580
+ async executeWithPreview(ability, input, toolCallId, toolAlias) {
368
581
  try {
369
582
  // Execute with dry_run
370
- const previewResult = await this.executor.execute(ability.name, input, { dryRun: true });
583
+ const previewResult = await executeAbilityWithPolicy(this.executor, ability, input, { dryRun: true });
371
584
  if (!previewResult.success) {
372
585
  return {
373
586
  type: 'error',
374
587
  error: previewResult.error?.message ?? 'Preview failed',
588
+ tool: ability.name,
375
589
  };
376
590
  }
377
591
  // Format preview
378
592
  const preview = this.safetyController.formatPreviewResult(ability, input, previewResult);
379
593
  // Store pending preview for approval
380
- this.pendingPreview = { ability, input, preview };
594
+ this.pendingPreview = { ability, input, preview, toolCallId, toolAlias };
381
595
  return {
382
596
  type: 'preview',
383
597
  preview,
@@ -388,6 +602,7 @@ export class ChatEngine {
388
602
  return {
389
603
  type: 'error',
390
604
  error: error instanceof Error ? error.message : String(error),
605
+ tool: ability.name,
391
606
  };
392
607
  }
393
608
  }
@@ -403,11 +618,41 @@ export class ChatEngine {
403
618
  let content = '';
404
619
  // Providers yield complete tool calls (not deltas), so we collect them directly
405
620
  const toolCalls = [];
621
+ // A response we cut short must not be reported as a complete answer.
622
+ let contentTruncated = false;
623
+ let capReached = false;
624
+ let toolCallsTruncated = false;
625
+ let toolArgumentsLength = 0;
406
626
  try {
407
627
  for await (const chunk of stream) {
408
628
  // Handle content chunks
409
629
  if (chunk.content) {
410
- content += chunk.content;
630
+ // Bound the accumulation: the SSE window is minutes long and the
631
+ // provider stream has no size cap of its own, so an oversized
632
+ // response would otherwise grow unbounded in memory and feed the
633
+ // downstream envelope scan. Display still streams every chunk.
634
+ if (capReached) {
635
+ // Full already; this chunk is dropped. Tracked separately from
636
+ // content.length because trimming an orphaned high surrogate puts
637
+ // the length back under the cap, and testing the length alone would
638
+ // then admit the next chunk, appending its unpaired low half.
639
+ contentTruncated = true;
640
+ }
641
+ else {
642
+ const combined = content + chunk.content;
643
+ // >= not >: a surrogate pair split across chunks can land exactly on
644
+ // the cap, and a `>` test would never trim the orphaned half.
645
+ if (combined.length >= MAX_STREAM_CONTENT_LENGTH) {
646
+ capReached = true;
647
+ content = truncateWholeCodePoints(combined, MAX_STREAM_CONTENT_LENGTH);
648
+ if (combined.length > content.length) {
649
+ contentTruncated = true;
650
+ }
651
+ }
652
+ else {
653
+ content = combined;
654
+ }
655
+ }
411
656
  // Call callback for progressive display
412
657
  if (this.onStreamChunk) {
413
658
  this.onStreamChunk(chunk.content);
@@ -416,10 +661,26 @@ export class ChatEngine {
416
661
  // Handle tool call chunks - providers yield each complete tool call as a separate chunk
417
662
  // before the done chunk, so push each one immediately
418
663
  if (chunk.toolCall && chunk.toolCall.id && chunk.toolCall.name) {
664
+ // Bound both the count and the bytes, then stop consuming: past
665
+ // either cap the stream is only spending memory on a response the
666
+ // envelope will reject anyway.
667
+ if (toolCalls.length >= MAX_STREAM_TOOL_CALLS) {
668
+ toolCallsTruncated = true;
669
+ break;
670
+ }
671
+ const argumentsLength = measureToolArguments(chunk.toolCall.arguments);
672
+ if (toolArgumentsLength + argumentsLength > MAX_STREAM_TOOL_ARGUMENTS_LENGTH) {
673
+ toolCallsTruncated = true;
674
+ break;
675
+ }
676
+ toolArgumentsLength += argumentsLength;
419
677
  toolCalls.push({
420
678
  id: chunk.toolCall.id,
421
679
  name: chunk.toolCall.name,
422
- arguments: chunk.toolCall.arguments ?? {},
680
+ arguments: chunk.toolCall.arguments,
681
+ ...(chunk.toolCall.thoughtSignature !== undefined
682
+ ? { thoughtSignature: chunk.toolCall.thoughtSignature }
683
+ : {}),
423
684
  });
424
685
  }
425
686
  // When done flag is set, we've collected all tool calls
@@ -431,7 +692,7 @@ export class ChatEngine {
431
692
  catch (error) {
432
693
  // If streaming fails mid-response, return what we have so far
433
694
  if (content || toolCalls.length > 0) {
434
- console.error(`[ChatEngine] Stream interrupted: ${error instanceof Error ? error.message : String(error)}`);
695
+ console.error(`[ChatEngine] Stream interrupted: ${stripControlChars(error instanceof Error ? error.message : String(error))}`);
435
696
  return {
436
697
  content,
437
698
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
@@ -442,8 +703,44 @@ export class ChatEngine {
442
703
  // If no content accumulated, re-throw
443
704
  throw error;
444
705
  }
706
+ // A stream that ended cleanly but delivered nothing is a failed response,
707
+ // not an empty answer: reporting finishReason 'stop' here would flow into
708
+ // the envelope parser's plain-text fallback and surface as a successful
709
+ // blank reply (exit 0 in one-shot mode).
710
+ if (!content && toolCalls.length === 0) {
711
+ return {
712
+ content: '',
713
+ toolCalls: undefined,
714
+ finishReason: 'error',
715
+ model: this.provider.getDefaultModel(),
716
+ };
717
+ }
445
718
  // Return accumulated LLMResponse
446
719
  const parsedToolCalls = toolCalls;
720
+ // A stream cut at a tool-call cap is not a complete answer either. With two
721
+ // calls retained the envelope's own "received 2" error already says so, so
722
+ // only the byte cap (which can stop at one call, or at none) needs routing
723
+ // through the truncated path — a single call from a stream we abandoned
724
+ // must never be proposed for execution.
725
+ if (toolCallsTruncated && parsedToolCalls.length < MAX_STREAM_TOOL_CALLS) {
726
+ return {
727
+ content,
728
+ toolCalls: undefined,
729
+ finishReason: 'length',
730
+ model: this.provider.getDefaultModel(),
731
+ };
732
+ }
733
+ // Content we cut at the cap is not a complete answer. Reporting 'stop'
734
+ // would let a truncated response pass as a finished one; 'length' routes it
735
+ // into the envelope parser's existing protocol-error path instead.
736
+ if (contentTruncated && parsedToolCalls.length === 0) {
737
+ return {
738
+ content,
739
+ toolCalls: undefined,
740
+ finishReason: 'length',
741
+ model: this.provider.getDefaultModel(),
742
+ };
743
+ }
447
744
  return {
448
745
  content,
449
746
  toolCalls: parsedToolCalls.length > 0 ? parsedToolCalls : undefined,
@@ -463,12 +760,6 @@ export class ChatEngine {
463
760
  getPendingPreview() {
464
761
  return this.pendingPreview?.preview ?? null;
465
762
  }
466
- /**
467
- * Cancel pending preview
468
- */
469
- cancelPendingPreview() {
470
- this.pendingPreview = null;
471
- }
472
763
  /**
473
764
  * Get conversation history (for debugging)
474
765
  */
@@ -488,128 +779,16 @@ export class ChatEngine {
488
779
  this.pendingPreview = null;
489
780
  }
490
781
  /**
491
- * Get message count (excluding system prompt)
492
- */
493
- getMessageCount() {
494
- return this.messages.length - 1;
495
- }
496
- /**
497
- * Estimate tokens for a set of messages using character count as a rough proxy.
498
- * Uses character_count / 4 as a heuristic (common approximation for English text).
782
+ * Truncate message history via the context window.
499
783
  *
500
- * NOTE: This is a rough estimate. Actual token counts from LLMResponse.usage
501
- * are more accurate when available.
502
- *
503
- * @param messages - Messages to estimate tokens for
504
- * @returns Estimated token count
505
- */
506
- estimateTokens(messages) {
507
- let totalChars = 0;
508
- for (const msg of messages) {
509
- if (typeof msg.content === 'string') {
510
- totalChars += msg.content.length;
511
- }
512
- }
513
- // Character count / 4 is a common heuristic for English text tokenization
514
- return Math.ceil(totalChars / 4);
515
- }
516
- /**
517
- * Check if context truncation should occur based on message count limits.
518
- * Token-based limits are reserved for future implementation.
519
- *
520
- * @returns true if truncation should occur, false if:
521
- * - maxContextMessages is undefined (no limit)
522
- * - maxContextMessages is 0 (explicit unlimited)
523
- * - message count is within limit
524
- */
525
- shouldTruncate() {
526
- if (this.maxContextMessages === undefined || this.maxContextMessages === 0) {
527
- return false; // No limit configured or explicitly unlimited
528
- }
529
- return this.getMessageCount() > this.maxContextMessages;
530
- }
531
- /**
532
- * Find the index where truncation should start, respecting message boundaries.
533
- * This ensures we keep complete user-assistant exchanges and tool call-result pairs.
534
- *
535
- * @returns Index in the messages array where truncation should start (exclusive of system prompt)
536
- */
537
- findTruncationPoint() {
538
- if (this.maxContextMessages === undefined || this.maxContextMessages <= 0) {
539
- return 1; // Keep only system prompt
540
- }
541
- // Calculate how many messages to keep (plus 1 for system prompt)
542
- const targetLength = this.maxContextMessages + 1;
543
- if (this.messages.length <= targetLength) {
544
- return this.messages.length; // No truncation needed
545
- }
546
- // Start from where we'd ideally cut
547
- const idealTruncationIndex = this.messages.length - this.maxContextMessages;
548
- // Ensure we don't cut the system prompt
549
- let truncationIndex = Math.max(1, idealTruncationIndex);
550
- // Walk forward to find a safe boundary (start of a user message)
551
- // This ensures we don't split:
552
- // - user message + assistant response
553
- // - tool call + tool result
554
- // - retry prompts from their original failed attempt
555
- const maxSearchIndex = this.messages.length;
556
- while (truncationIndex < maxSearchIndex) {
557
- const msg = this.messages[truncationIndex];
558
- // Safe to cut at the start of a user message
559
- if (msg && msg.role === 'user') {
560
- break;
561
- }
562
- truncationIndex++;
563
- }
564
- // Fallback: if no user boundary found, keep at least maxContextMessages
565
- // This ensures we don't drop all messages when the limit is very small
566
- if (truncationIndex >= this.messages.length) {
567
- truncationIndex = Math.max(1, idealTruncationIndex);
568
- }
569
- return truncationIndex;
570
- }
571
- /**
572
- * Truncate message history using a sliding window approach.
573
- * Preserves:
574
- * - System prompt (always first message)
575
- * - Messages since pending preview (if any)
576
- * - Most recent N messages where N = maxContextMessages
577
- * - Complete message exchanges (user-assistant, tool call-result pairs)
784
+ * Safety: Never truncates while a preview is pending — this preserves
785
+ * context for the approval decision.
578
786
  */
579
787
  truncateHistory() {
580
- if (!this.shouldTruncate()) {
581
- return;
582
- }
583
- // Safety: Never truncate if there's a pending preview
584
- // This preserves context for the approval decision
585
788
  if (this.pendingPreview !== null) {
586
789
  return;
587
790
  }
588
- const systemPrompt = this.messages[0];
589
- if (!systemPrompt) {
590
- return;
591
- }
592
- const truncationIndex = this.findTruncationPoint();
593
- const messagesBefore = this.messages.length;
594
- // Keep system prompt + messages from truncation point onwards
595
- this.messages = [systemPrompt, ...this.messages.slice(truncationIndex)];
596
- // Debug logging (only if significant truncation occurred)
597
- const messagesRemoved = messagesBefore - this.messages.length;
598
- if (messagesRemoved > 0 && process.env['DEBUG']) {
599
- console.debug(`[ChatEngine] Truncated ${messagesRemoved} messages (${messagesBefore - 1} -> ${this.messages.length - 1})`);
600
- }
601
- }
602
- /**
603
- * Get context window statistics for monitoring.
604
- *
605
- * @returns Object with current message count, max limit, and estimated tokens
606
- */
607
- getContextStats() {
608
- return {
609
- messageCount: this.getMessageCount(),
610
- maxMessages: this.maxContextMessages,
611
- estimatedTokens: this.estimateTokens(this.messages),
612
- };
791
+ this.messages = this.contextWindow.truncate(this.messages);
613
792
  }
614
793
  /**
615
794
  * Get loaded abilities