@mainwp/control 1.1.0-beta.1 → 2.0.0

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