All files to-acp.js

94.51% Statements 155/164
82.2% Branches 97/118
100% Functions 19/19
94.83% Lines 147/155

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438            3x                   31x   31x   31x 31x         29x 11x   29x 29x 29x 29x   29x       3x       23x 23x 23x     23x 23x 23x 12x   11x     66x 23x 23x       23x       1x       5x               9x 9x   9x   9x 9x 9x 9x 25x 5x 20x 10x   10x         9x 5x       9x 1x 1x 1x 1x 2x   1x 1x 1x 3x       8x 2x         9x 9x 1x   9x 9x 8x       9x 9x 9x 9x 9x 9x 9x 9x 9x   9x 9x       9x       4x 4x                     18x 18x               18x 5x 4x     1x 1x         1x                 18x   5x 1x     4x         4x       18x 5x 5x   1x 1x           1x                 1x     18x   2x 2x 2x                     2x       6x 6x 6x 5x 5x 5x     5x     5x                   5x 2x 2x   2x               2x         3x 3x                         6x     7x 7x 7x   1x       1x             6x   5x 5x   5x     5x   1x     1x               1x       4x     4x     5x                 5x                           1x 1x                   7x       2x 2x               2x     1x     18x       3x 1x         2x 2x           1x             5x             3x   1x    
// Convert Amp stream JSON events to ACP sessionUpdate notifications.
// Schema reference: https://ampcode.com/manual/appendix#stream-json-output
 
import { config, getToolKind, getToolTitle, getToolLocations, getInlineToolDescription } from './config.js';
import { createLogger } from './logger.js';
 
const logProtocol = createLogger('acp:protocol');
 
/**
 * State tracker for nested tool call handling
 * Tracks mapping between Amp tool_use_id and child tool metadata
 * Also tracks per-parent progress counters for consolidated display
 */
export class NestedToolTracker {
  constructor() {
    // Map: childToolUseId → { parentToolUseId, name, input, status, index }
    this.childTools = new Map();
    // Map: parentToolUseId → { total, completed, failed, children: [{id, name, input, status}] }
    this.parentStats = new Map();
    // How many completed/failed items to show before collapsing
    this.maxVisibleCompleted = 3;
    this.maxVisibleFailed = 5; // Show first 2 + last 3 when collapsed
  }
 
  registerChild(childId, parentId, name, input) {
    // Initialize parent stats if needed
    if (!this.parentStats.has(parentId)) {
      this.parentStats.set(parentId, { total: 0, completed: 0, failed: 0, children: [] });
    }
    const stats = this.parentStats.get(parentId);
    const index = stats.total;
    stats.total++;
    stats.children.push({ id: childId, name, input, status: 'running' });
 
    this.childTools.set(childId, { parentToolUseId: parentId, name, input, status: 'running', index });
  }
 
  getChild(childId) {
    return this.childTools.get(childId);
  }
 
  completeChild(childId, isError) {
    const child = this.childTools.get(childId);
    Eif (child) {
      child.status = isError ? 'failed' : 'completed';
 
      // Update parent stats
      const stats = this.parentStats.get(child.parentToolUseId);
      Eif (stats) {
        if (isError) {
          stats.failed++;
        } else {
          stats.completed++;
        }
        // Update child in children array
        const childEntry = stats.children.find((c) => c.id === childId);
        Eif (childEntry) {
          childEntry.status = child.status;
        }
      }
    }
    return child;
  }
 
  getParentStats(parentId) {
    return this.parentStats.get(parentId);
  }
 
  isChildTool(childId) {
    return this.childTools.has(childId);
  }
 
  /**
   * Get full content array for a parent tool (ACP replaces content on each update)
   * Returns array of content objects ready for ACP tool_call_update
   */
  getContentArray(parentId) {
    const stats = this.parentStats.get(parentId);
    Iif (!stats) return [];
 
    const lines = [];
    // Separate children by status for smart display
    const running = [];
    const failed = [];
    const completed = [];
    for (const child of stats.children) {
      if (child.status === 'running') {
        running.push(child);
      } else if (child.status === 'failed') {
        failed.push(child);
      } else {
        completed.push(child);
      }
    }
 
    // Always show all running items (need visibility for active work)
    for (const child of running) {
      lines.push(`◐ ${getInlineToolDescription(child.name, child.input)}`);
    }
 
    // Collapse failed items if too many (show first N + last M)
    if (failed.length > this.maxVisibleFailed) {
      const firstCount = Math.min(2, this.maxVisibleFailed);
      const lastCount = Math.max(0, this.maxVisibleFailed - firstCount);
      const hiddenFailed = failed.length - this.maxVisibleFailed;
      for (const child of failed.slice(0, firstCount)) {
        lines.push(`✗ ${getInlineToolDescription(child.name, child.input)}`);
      }
      lines.push(`✗ ... ${hiddenFailed} more failed`);
      Eif (lastCount > 0) {
        for (const child of failed.slice(-lastCount)) {
          lines.push(`✗ ${getInlineToolDescription(child.name, child.input)}`);
        }
      }
    } else {
      for (const child of failed) {
        lines.push(`✗ ${getInlineToolDescription(child.name, child.input)}`);
      }
    }
 
    // Show only the most recent completed items, collapse older ones
    const hiddenCompleted = completed.length - this.maxVisibleCompleted;
    if (hiddenCompleted > 0) {
      lines.push(`✓ ... ${hiddenCompleted} more completed`);
    }
    const visibleCompleted = completed.slice(-this.maxVisibleCompleted);
    for (const child of visibleCompleted) {
      lines.push(`✓ ${getInlineToolDescription(child.name, child.input)}`);
    }
 
    // Add progress summary using stats counts (not local arrays)
    const completedCount = stats.completed;
    const failedCount = stats.failed;
    const totalCount = stats.total;
    const doneCount = completedCount + failedCount;
    const runningCount = totalCount - doneCount;
    const parts = [];
    if (runningCount > 0) parts.push(`${runningCount} running`);
    if (completedCount > 0) parts.push(`${completedCount} done`);
    if (failedCount > 0) parts.push(`${failedCount} failed`);
 
    Eif (parts.length > 0) {
      lines.push(`── ${parts.join(', ')} (${doneCount}/${totalCount}) ──`);
    }
 
    // Return as ACP content array (single text block with all lines)
    return [{ type: 'content', content: { type: 'text', text: lines.join('\n') } }];
  }
 
  clear() {
    this.childTools.clear();
    this.parentStats.clear();
  }
}
 
export function toAcpNotifications(
  msg,
  sessionId,
  activeToolCalls = new Map(),
  _clientCapabilities = {},
  nestedTracker = null
) {
  const output = [];
  const inlineMode = config.nestedToolMode === 'inline';
 
  /**
   * Generate a session-unique ACP tool call ID from an Amp tool_use_id
   * If the ID already exists, generate a unique replacement and track the mapping
   * @param {string} ampId - Original Amp tool_use_id
   * @returns {string} - Session-unique ACP tool call ID
   */
  const getUniqueToolCallId = (ampId) => {
    if (!activeToolCalls.has(ampId)) {
      return ampId; // ID is unique, use as-is
    }
    // Generate unique replacement ID
    const uniqueId = `${ampId}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
    logProtocol.warn('Generated unique toolCallId for duplicate', {
      originalId: ampId,
      uniqueId,
      sessionId,
    });
    return uniqueId;
  };
 
  /**
   * Find the ACP tool call ID for a given Amp tool_use_id
   * Handles both direct matches and ampId->acpId mappings
   * @param {string} ampId - Original Amp tool_use_id from tool_result
   * @returns {string|null} - ACP tool call ID or null if not found
   */
  const findAcpToolCallId = (ampId) => {
    // Direct match (most common case - ID wasn't remapped)
    if (activeToolCalls.has(ampId)) {
      return ampId;
    }
    // Search for mapped ID
    for (const [acpId, toolCall] of activeToolCalls) {
      if (toolCall.ampId === ampId) {
        return acpId;
      }
    }
    return null;
  };
 
  // Track tool call state transitions for validation
  const validateStatusTransition = (toolCallId, newStatus) => {
    const existingCall = activeToolCalls.get(toolCallId);
    if (!existingCall) return true; // New tool call
 
    const currentStatus = existingCall.lastStatus;
    const validTransitions = {
      in_progress: ['completed', 'failed'],
      completed: [], // Terminal state
      failed: [], // Terminal state
    };
 
    Iif (!validTransitions[currentStatus]?.includes(newStatus)) {
      logProtocol.warn('Invalid status transition', {
        toolCallId,
        from: currentStatus,
        to: newStatus,
        validTransitions: validTransitions[currentStatus],
      });
      return false;
    }
    return true;
  };
 
  switch (msg.type) {
    case 'system':
      Eif (msg.subtype === 'init') {
        const mcpList = msg.mcp_servers?.map((s) => `${s.name} (${s.status})`).join(', ') || 'none';
        output.push({
          sessionId,
          update: {
            sessionUpdate: 'agent_thought_chunk',
            content: {
              type: 'text',
              text: `Session started. Tools: ${msg.tools?.length || 0}, MCP Servers: ${mcpList}`,
            },
          },
        });
      }
      break;
 
    case 'user':
      // User messages contain tool_result content
      Eif (Array.isArray(msg.message?.content)) {
        for (const chunk of msg.message.content) {
          if (chunk.type === 'tool_result') {
            const isError = chunk.is_error;
            const status = isError ? 'failed' : 'completed';
            const ampId = chunk.tool_use_id;
 
            // Find the ACP tool call ID (handles remapped IDs)
            const acpToolCallId = findAcpToolCallId(ampId) || ampId;
 
            // Validate status transition before emitting
            Iif (!validateStatusTransition(acpToolCallId, status)) {
              logProtocol.warn('Skipping invalid tool result status transition', {
                toolCallId: acpToolCallId,
                ampId,
                attemptedStatus: status,
              });
              continue;
            }
 
            // Check if this is a child tool result in inline mode
            if (inlineMode && nestedTracker) {
              const childInfo = nestedTracker.completeChild(ampId, isError);
              Eif (childInfo) {
                // Emit full content array on PARENT (ACP replaces content, not appends)
                output.push({
                  sessionId,
                  update: {
                    toolCallId: childInfo.parentToolUseId,
                    sessionUpdate: 'tool_call_update',
                    content: nestedTracker.getContentArray(childInfo.parentToolUseId),
                  },
                });
                continue; // Don't emit separate tool_call_update for child
              }
            }
 
            // Normal (non-child) tool result
            activeToolCalls.delete(acpToolCallId);
            output.push({
              sessionId,
              update: {
                toolCallId: acpToolCallId,
                sessionUpdate: 'tool_call_update',
                status,
                content: toAcpContentArray(chunk.content, isError),
              },
            });
          }
          // Ignore text chunks in user messages - they're internal model context, not user input
        }
      }
      break;
 
    case 'assistant':
      Eif (Array.isArray(msg.message?.content)) {
        for (const chunk of msg.message.content) {
          if (chunk.type === 'text') {
            // Text from subagent goes to parent as thought, not message
            Iif (msg.parent_tool_use_id && inlineMode) {
              // Skip subagent text in inline mode - the summary comes in tool_result
              continue;
            }
            output.push({
              sessionId,
              update: {
                sessionUpdate: 'agent_message_chunk',
                content: { type: 'text', text: chunk.text },
              },
            });
          } else if (chunk.type === 'tool_use') {
            // Generate session-unique tool call ID (handles duplicates)
            const ampId = chunk.id;
            const acpToolCallId = getUniqueToolCallId(ampId);
 
            const isChildTool = !!msg.parent_tool_use_id;
 
            // In inline mode, embed child tool calls into parent's content
            if (inlineMode && isChildTool && nestedTracker) {
              // Register this child tool (use original ampId for Amp correlation)
              nestedTracker.registerChild(ampId, msg.parent_tool_use_id, chunk.name, chunk.input);
 
              // Emit full content array on the parent (ACP replaces content, not appends)
              output.push({
                sessionId,
                update: {
                  toolCallId: msg.parent_tool_use_id,
                  sessionUpdate: 'tool_call_update',
                  content: nestedTracker.getContentArray(msg.parent_tool_use_id),
                },
              });
              continue; // Don't emit separate tool_call for child
            }
 
            // Build locations array for file-based tools
            const locations = getToolLocations(chunk.name, chunk.input);
 
            // Build _meta for nested tool calls (subagent/oracle) in separate mode
            const meta = msg.parent_tool_use_id ? { parentToolCallId: msg.parent_tool_use_id } : undefined;
 
            // Track tool call state with ampId mapping - start directly as in_progress
            activeToolCalls.set(acpToolCallId, {
              ampId, // Store original Amp ID for correlation
              name: chunk.name,
              startTime: Date.now(),
              lastStatus: 'in_progress',
            });
 
            // Emit tool_call with status: in_progress directly (skip pending for atomic emission)
            // This prevents orphan states if the first emission fails
            output.push({
              sessionId,
              update: {
                toolCallId: acpToolCallId,
                sessionUpdate: 'tool_call',
                rawInput: JSON.stringify(chunk.input),
                status: 'in_progress',
                title: getToolTitle(chunk.name, msg.parent_tool_use_id, chunk.input),
                kind: getToolKind(chunk.name),
                content: [],
                ...(locations.length > 0 && { locations }),
                ...(meta && { _meta: meta }),
              },
            });
          } else Eif (chunk.type === 'thinking') {
            output.push({
              sessionId,
              update: {
                sessionUpdate: 'agent_thought_chunk',
                content: { type: 'text', text: chunk.thinking },
              },
            });
          }
        }
      }
      break;
 
    case 'result':
      // Final result - could emit a summary if needed
      Eif (msg.subtype === 'error_during_execution' || msg.subtype === 'error_max_turns') {
        output.push({
          sessionId,
          update: {
            sessionUpdate: 'agent_message_chunk',
            content: { type: 'text', text: `Error: ${msg.error}` },
          },
        });
      }
      break;
 
    default:
      break;
  }
 
  return output;
}
 
function toAcpContentArray(content, isError = false) {
  if (Array.isArray(content) && content.length > 0) {
    return content.map((c) => ({
      type: 'content',
      content: c.type === 'text' ? { type: 'text', text: isError ? wrapCode(c.text) : c.text } : c,
    }));
  }
  Eif (typeof content === 'string' && content.length > 0) {
    return [{ type: 'content', content: { type: 'text', text: isError ? wrapCode(content) : content } }];
  }
  return [];
}
 
function wrapCode(t) {
  return '```\n' + t + '\n```';
}
 
/**
 * Check if a message chunk is a Bash tool_use
 */
export function isBashToolUse(chunk) {
  return chunk?.type === 'tool_use' && chunk?.name === 'Bash';
}
 
/**
 * Extract tool result info from a tool_result chunk
 */
export function getToolResult(chunk) {
  if (chunk?.type !== 'tool_result') return null;
  // Return the tool_use_id; caller tracks which tool type it was
  return { toolUseId: chunk.tool_use_id };
}