hammer-ai 0.2.14 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2071,24 +2071,6 @@ declare function parseResponseWithRecovery(content: string, options?: ParseRespo
2071
2071
  * consistent tool result truncation and safe execution wrapping.
2072
2072
  */
2073
2073
 
2074
- /** Default maximum characters for tool result strings. */
2075
- declare const MAX_TOOL_RESULT_CHARS = 30000;
2076
- interface TruncateOptions {
2077
- /** Maximum character length (default: 30,000). */
2078
- maxChars?: number;
2079
- /**
2080
- * Truncation strategy:
2081
- * - `"head-tail"`: Keep first half + last half (preserves end of large outputs).
2082
- * - `"head-only"`: Keep the first N characters.
2083
- */
2084
- strategy?: "head-tail" | "head-only";
2085
- }
2086
- /**
2087
- * Truncate an oversized tool result string to stay within LLM context limits.
2088
- *
2089
- * @returns The original string if within limit, otherwise a truncated version.
2090
- */
2091
- declare function truncateToolResult(resultStr: string, options?: TruncateOptions): string;
2092
2074
  declare function formatToolResultMessage(toolCall: ToolCall, result: ToolResult): string;
2093
2075
  declare function parseToolResultMessage(content: string): {
2094
2076
  success: boolean;
@@ -2468,4 +2450,4 @@ declare function runStructuredLLMCompaction<TMessage extends MemoryMessage, TSta
2468
2450
  parseState: (obj: Record<string, unknown>) => TState | null;
2469
2451
  }): Promise<TState | null>;
2470
2452
 
2471
- export { AGENT_MACHINE_STATES, AgentLoop, type AgentLoopCallbacks, type AgentLoopDeps, type AgentMachineContext, type AgentMachineEvent, type AgentMachineState, type AgentMemoryCitation, type AgentMemoryConstraint, type AgentMemoryEvidence, type AgentMemoryFactoryOverrides, AgentMemoryLayer, type AgentMemoryLayerConfig, type AgentMemoryLogger, type AgentMemoryNote, type AgentMemoryTask, type AgentMessage, type AgentPhase, type AgentState, ApiError, type BackgroundBashAction, BackgroundBashRunCommand, BaseMemoryLayer, BaseValidationEnforcer, BashRunCommand, type BuildMemoryCompactionPromptOptions, CODE_QUALITY_RULE_LINE, CharTokenEstimator, type ChatMessage, type CommandRuntime, type CommandTargetInfo, type CompactionCursor, type CompactionLLMClient, type ConversationAdapter, type ConversationSink, type CreateWebRuntimeSetupOptions, DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT, DEFAULT_ALLOWED_RUN_TARGETS, DEFAULT_RUN_COMMAND_REGISTRY, DEFAULT_THREAD_AUTO_SCROLL_BOTTOM_THRESHOLD, DEFAULT_TOOL_MEMORY_EXTRACTOR, ERROR_RECOVERY_RULE_LINE, ERROR_TRUNCATED_RESPONSE, type EnforcerResult, type ExecuteWebLoopRunOptions, type FetchLike, type FetchResponseLike, type HammerAgentConfig, type HammerAgentProviderPreset, INCREMENTAL_TESTING_RULE_LINE, JUST_BASH_SCRIPT_EXECUTION_RESTRICTION_LINES, JUST_BASH_SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES, LLMClient, type LLMClientResponse, type LLMProviderConfig, type LLMRequest, type LLMRequestOptions, type LLMResponse, LLMResponseSchema, type LoopOutcome, MAX_TOOL_RESULT_CHARS, type MemoryMessage, type MemoryProvenance, type MemoryStorage, PORT_CONFLICT_RULE_LINE, type ParseAgentResponseOptions, type ParsedAgentResponse, type ParsedBackgroundBashCommand, type ParsedStepInput, PendingAgentMessageBuffer, type PersistedMemoryData, type ProviderName, ProxyTool, type ProxyToolExecutor, ROOT_CAUSES_RULE_LINE, type RawMessage, RunCommand, type RunCommandParseResult, type RunCommandPromptAvailability, RunCommandRegistry, type RunInvocationTarget, type RuntimeController, type RuntimeSnapshotUpdater, type RuntimeStore, type RuntimeSubscriber, SHARED_TOOL_CALL_EXAMPLE_LINES, SHARED_TOOL_USAGE_RULE, SINGLE_TOOL_CALL_RUN_LINE_EXAMPLE, SKILL_INVOKE_READ_RULE_LINE, STANDARD_TOOL_CALL_FORMAT_RULES, SUPPORTED_RUN_TARGETS, type SkillSummaryLike, type StepResult, type StreamCallbacks, StreamingToolParser, type StreamingToolParserCallbacks, SubAgentTool, type SubAgentToolOptions, type SystemPromptBuildContext, type SystemPromptCustomizer, type SystemPromptSections, TODO_LIST_FIRST_RESPONSE_RULE_LINE, TOOL_CALL_SEPARATOR_RULE, type TodoItem, type TodoStatus, type TokenEstimator, Tool, type ToolCall, ToolCallSchema, type ToolDataPrimitive, type ToolDataSchema, type ToolDataValue, type ToolDefinition, type ToolDefinitionMetadata, type ToolExecutionResult, type ToolLike, ToolLoopAgentRuntime, type ToolLoopAgentRuntimeDeps, type ToolLoopRuntimeExecuteStepResult, type ToolLoopRuntimeHooks, type ToolLoopRuntimeInfrastructure, type ToolLoopRuntimeLLMRequest, type ToolLoopRuntimeLLMResponse, type ToolLoopRuntimeRunStepOptions, type ToolLoopRuntimeRunStepResult, type ToolLoopRuntimeSetup, type ToolLoopRuntimeStepContext, type ToolLoopStepExecutionResult, type ToolLoopStepExecutorCallbacks, type ToolLoopStepExecutorOptions, type ToolLoopStepExecutorResponse, type ToolMemoryCitationKind, type ToolMemoryEvidenceKind, type ToolMemoryEvidencePolicy, type ToolMemoryExtractor, type ToolMemoryMetadata, type ToolMemoryNoteKind, type ToolMemoryNotePolicy, type ToolMemoryNoteScope, type ToolMetadata, type ToolParameterDefinition, ToolRegistry, type ToolRegistryBeforeExecuteContext, type ToolRegistryMissingToolContext, type ToolRegistryOptions, type ToolResult, ToolRunCommand, type ToolSchema, type TruncatedToolInfo, VALIDATE_AFTER_CHANGES_RULE_LINE, type WebSearchToolActionInput, WebToolLoopAgentRuntime, type WebToolLoopAgentRuntimeConstructorOptions, type WebToolLoopRuntimeStateLike, WebValidationEnforcer, type WorkspaceCodingStaticRulesOptions, agentMachine, applyIdleWebAgentState, applyInitialWebAgentRunState, buildAgentIdentityLine, buildAgentSystemPrompt, buildCompactionEntry, buildCoreStaticRules, buildNoStructuredResponseFoundError, buildSkillAwareStaticContext, buildSkillsSection, buildStepUserMessage, buildToolLogRevealFrames, buildToolUsageExample, buildValidationErrorMessage, buildWebRuntimeRules, buildWorkspaceCodingStaticRules, canonicalizeCompactionText, coerceToolCallToDefinition, configure, containsStandaloneStructuredInvocationStart, createAgentMemoryLayer, createAppendToolsSectionCustomizer, createBackgroundBashDefinition, createConversationSink, createCustomRunCommandRegistry, createInitialWebAgentState, createRunCommandRuntimeBindings, createRuntimeStore, createToolAgentMessage, createToolRegistry, createToolsSectionOverrideCustomizer, createWebAgentMessageIdGenerator, createWebSearchToolActions, createWebToolLoopCallbacks, decodeEscapedShellText, defineRuntimeController, enrichToolResultWithUnixMetadata, executeBackgroundUnixCommandString, executeToolCallWithRunCommands, executeToolLoopStep, executeToolSafe, executeUnixCommandString, extractPrimaryCommandMetadata, extractTruncatedToolInfo, formatToolCallAsUnixCommand, formatToolDefinitions, formatToolResultMessage, formatToolsSection, formatUnixToolSurface, formatZodValidationError, getDiagnosticSummaryLine, getProviderConfig, getRunCommandPromptAvailability, getToolLogSummaryLine, isBackgroundBashToolCall, isBashToolCall, limitEntriesByRecency, machineStateToWebAgentPhase, mapConversationRoleToAgentRole, parseAgentResponse, parseResponseWithRecovery, parseStructuredAgentText, parseToolResultMessage, parseUnixToolCommand, readDiagnosticLevel, readDiagnosticSource, resolveToolDefinitionForInvocation, runStructuredLLMCompaction, selectLatestByKey, shouldAutoScrollThread, shouldSkipStepUserMessage, stripDiagnosticMessagePrefix, suppressWebValidationLog, tokenizeUnixCommand, truncateToolResult };
2453
+ export { AGENT_MACHINE_STATES, AgentLoop, type AgentLoopCallbacks, type AgentLoopDeps, type AgentMachineContext, type AgentMachineEvent, type AgentMachineState, type AgentMemoryCitation, type AgentMemoryConstraint, type AgentMemoryEvidence, type AgentMemoryFactoryOverrides, AgentMemoryLayer, type AgentMemoryLayerConfig, type AgentMemoryLogger, type AgentMemoryNote, type AgentMemoryTask, type AgentMessage, type AgentPhase, type AgentState, ApiError, type BackgroundBashAction, BackgroundBashRunCommand, BaseMemoryLayer, BaseValidationEnforcer, BashRunCommand, type BuildMemoryCompactionPromptOptions, CODE_QUALITY_RULE_LINE, CharTokenEstimator, type ChatMessage, type CommandRuntime, type CommandTargetInfo, type CompactionCursor, type CompactionLLMClient, type ConversationAdapter, type ConversationSink, type CreateWebRuntimeSetupOptions, DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT, DEFAULT_ALLOWED_RUN_TARGETS, DEFAULT_RUN_COMMAND_REGISTRY, DEFAULT_THREAD_AUTO_SCROLL_BOTTOM_THRESHOLD, DEFAULT_TOOL_MEMORY_EXTRACTOR, ERROR_RECOVERY_RULE_LINE, ERROR_TRUNCATED_RESPONSE, type EnforcerResult, type ExecuteWebLoopRunOptions, type FetchLike, type FetchResponseLike, type HammerAgentConfig, type HammerAgentProviderPreset, INCREMENTAL_TESTING_RULE_LINE, JUST_BASH_SCRIPT_EXECUTION_RESTRICTION_LINES, JUST_BASH_SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES, LLMClient, type LLMClientResponse, type LLMProviderConfig, type LLMRequest, type LLMRequestOptions, type LLMResponse, LLMResponseSchema, type LoopOutcome, type MemoryMessage, type MemoryProvenance, type MemoryStorage, PORT_CONFLICT_RULE_LINE, type ParseAgentResponseOptions, type ParsedAgentResponse, type ParsedBackgroundBashCommand, type ParsedStepInput, PendingAgentMessageBuffer, type PersistedMemoryData, type ProviderName, ProxyTool, type ProxyToolExecutor, ROOT_CAUSES_RULE_LINE, type RawMessage, RunCommand, type RunCommandParseResult, type RunCommandPromptAvailability, RunCommandRegistry, type RunInvocationTarget, type RuntimeController, type RuntimeSnapshotUpdater, type RuntimeStore, type RuntimeSubscriber, SHARED_TOOL_CALL_EXAMPLE_LINES, SHARED_TOOL_USAGE_RULE, SINGLE_TOOL_CALL_RUN_LINE_EXAMPLE, SKILL_INVOKE_READ_RULE_LINE, STANDARD_TOOL_CALL_FORMAT_RULES, SUPPORTED_RUN_TARGETS, type SkillSummaryLike, type StepResult, type StreamCallbacks, StreamingToolParser, type StreamingToolParserCallbacks, SubAgentTool, type SubAgentToolOptions, type SystemPromptBuildContext, type SystemPromptCustomizer, type SystemPromptSections, TODO_LIST_FIRST_RESPONSE_RULE_LINE, TOOL_CALL_SEPARATOR_RULE, type TodoItem, type TodoStatus, type TokenEstimator, Tool, type ToolCall, ToolCallSchema, type ToolDataPrimitive, type ToolDataSchema, type ToolDataValue, type ToolDefinition, type ToolDefinitionMetadata, type ToolExecutionResult, type ToolLike, ToolLoopAgentRuntime, type ToolLoopAgentRuntimeDeps, type ToolLoopRuntimeExecuteStepResult, type ToolLoopRuntimeHooks, type ToolLoopRuntimeInfrastructure, type ToolLoopRuntimeLLMRequest, type ToolLoopRuntimeLLMResponse, type ToolLoopRuntimeRunStepOptions, type ToolLoopRuntimeRunStepResult, type ToolLoopRuntimeSetup, type ToolLoopRuntimeStepContext, type ToolLoopStepExecutionResult, type ToolLoopStepExecutorCallbacks, type ToolLoopStepExecutorOptions, type ToolLoopStepExecutorResponse, type ToolMemoryCitationKind, type ToolMemoryEvidenceKind, type ToolMemoryEvidencePolicy, type ToolMemoryExtractor, type ToolMemoryMetadata, type ToolMemoryNoteKind, type ToolMemoryNotePolicy, type ToolMemoryNoteScope, type ToolMetadata, type ToolParameterDefinition, ToolRegistry, type ToolRegistryBeforeExecuteContext, type ToolRegistryMissingToolContext, type ToolRegistryOptions, type ToolResult, ToolRunCommand, type ToolSchema, type TruncatedToolInfo, VALIDATE_AFTER_CHANGES_RULE_LINE, type WebSearchToolActionInput, WebToolLoopAgentRuntime, type WebToolLoopAgentRuntimeConstructorOptions, type WebToolLoopRuntimeStateLike, WebValidationEnforcer, type WorkspaceCodingStaticRulesOptions, agentMachine, applyIdleWebAgentState, applyInitialWebAgentRunState, buildAgentIdentityLine, buildAgentSystemPrompt, buildCompactionEntry, buildCoreStaticRules, buildNoStructuredResponseFoundError, buildSkillAwareStaticContext, buildSkillsSection, buildStepUserMessage, buildToolLogRevealFrames, buildToolUsageExample, buildValidationErrorMessage, buildWebRuntimeRules, buildWorkspaceCodingStaticRules, canonicalizeCompactionText, coerceToolCallToDefinition, configure, containsStandaloneStructuredInvocationStart, createAgentMemoryLayer, createAppendToolsSectionCustomizer, createBackgroundBashDefinition, createConversationSink, createCustomRunCommandRegistry, createInitialWebAgentState, createRunCommandRuntimeBindings, createRuntimeStore, createToolAgentMessage, createToolRegistry, createToolsSectionOverrideCustomizer, createWebAgentMessageIdGenerator, createWebSearchToolActions, createWebToolLoopCallbacks, decodeEscapedShellText, defineRuntimeController, enrichToolResultWithUnixMetadata, executeBackgroundUnixCommandString, executeToolCallWithRunCommands, executeToolLoopStep, executeToolSafe, executeUnixCommandString, extractPrimaryCommandMetadata, extractTruncatedToolInfo, formatToolCallAsUnixCommand, formatToolDefinitions, formatToolResultMessage, formatToolsSection, formatUnixToolSurface, formatZodValidationError, getDiagnosticSummaryLine, getProviderConfig, getRunCommandPromptAvailability, getToolLogSummaryLine, isBackgroundBashToolCall, isBashToolCall, limitEntriesByRecency, machineStateToWebAgentPhase, mapConversationRoleToAgentRole, parseAgentResponse, parseResponseWithRecovery, parseStructuredAgentText, parseToolResultMessage, parseUnixToolCommand, readDiagnosticLevel, readDiagnosticSource, resolveToolDefinitionForInvocation, runStructuredLLMCompaction, selectLatestByKey, shouldAutoScrollThread, shouldSkipStepUserMessage, stripDiagnosticMessagePrefix, suppressWebValidationLog, tokenizeUnixCommand };
package/dist/index.js CHANGED
@@ -3133,31 +3133,194 @@ function extractTruncatedToolInfo(calls) {
3133
3133
  }
3134
3134
 
3135
3135
  // src/tool-helpers.ts
3136
- var MAX_TOOL_RESULT_CHARS = 3e4;
3137
- var MAX_PRESENTATION_LINES = 200;
3138
- var MAX_PRESENTATION_CHARS = 5e4;
3139
- function truncateToolResult(resultStr, options) {
3140
- const maxChars = options?.maxChars ?? MAX_TOOL_RESULT_CHARS;
3141
- const strategy = options?.strategy ?? "head-tail";
3142
- if (resultStr.length <= maxChars) return resultStr;
3143
- if (strategy === "head-only") {
3144
- return resultStr.substring(0, maxChars) + "\n...(truncated)";
3145
- }
3146
- const half = Math.floor(maxChars / 2);
3147
- const head = resultStr.substring(0, half);
3148
- const tail = resultStr.substring(resultStr.length - half);
3149
- const omitted = resultStr.length - maxChars;
3150
- return `${head}
3151
- ... [${omitted} chars truncated] ...
3152
- ${tail}`;
3136
+ var DEFAULT_MAX_LINES = 2e3;
3137
+ var DEFAULT_MAX_BYTES = 50 * 1024;
3138
+ function splitLinesForCounting(content) {
3139
+ if (content.length === 0) {
3140
+ return [];
3141
+ }
3142
+ const lines = content.split("\n");
3143
+ if (content.endsWith("\n")) {
3144
+ lines.pop();
3145
+ }
3146
+ return lines;
3147
+ }
3148
+ function truncateHead(content, options = {}) {
3149
+ const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
3150
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
3151
+ const totalBytes = utf8ByteLength(content);
3152
+ const lines = splitLinesForCounting(content);
3153
+ const totalLines = lines.length;
3154
+ if (totalLines <= maxLines && totalBytes <= maxBytes) {
3155
+ return {
3156
+ content,
3157
+ truncated: false,
3158
+ truncatedBy: null,
3159
+ totalLines,
3160
+ totalBytes,
3161
+ outputLines: totalLines,
3162
+ outputBytes: totalBytes,
3163
+ lastLinePartial: false,
3164
+ firstLineExceedsLimit: false,
3165
+ maxLines,
3166
+ maxBytes
3167
+ };
3168
+ }
3169
+ if (lines.length > 0 && utf8ByteLength(lines[0]) > maxBytes) {
3170
+ return {
3171
+ content: "",
3172
+ truncated: true,
3173
+ truncatedBy: "bytes",
3174
+ totalLines,
3175
+ totalBytes,
3176
+ outputLines: 0,
3177
+ outputBytes: 0,
3178
+ lastLinePartial: false,
3179
+ firstLineExceedsLimit: true,
3180
+ maxLines,
3181
+ maxBytes
3182
+ };
3183
+ }
3184
+ const outputLinesArr = [];
3185
+ let outputBytesCount = 0;
3186
+ let truncatedBy = "lines";
3187
+ for (let i = 0; i < lines.length && i < maxLines; i++) {
3188
+ const line = lines[i];
3189
+ const lineBytes = utf8ByteLength(line) + (i > 0 ? 1 : 0);
3190
+ if (outputBytesCount + lineBytes > maxBytes) {
3191
+ truncatedBy = "bytes";
3192
+ break;
3193
+ }
3194
+ outputLinesArr.push(line);
3195
+ outputBytesCount += lineBytes;
3196
+ }
3197
+ if (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {
3198
+ truncatedBy = "lines";
3199
+ }
3200
+ const outputContent = outputLinesArr.join("\n");
3201
+ const finalOutputBytes = utf8ByteLength(outputContent);
3202
+ return {
3203
+ content: outputContent,
3204
+ truncated: true,
3205
+ truncatedBy,
3206
+ totalLines,
3207
+ totalBytes,
3208
+ outputLines: outputLinesArr.length,
3209
+ outputBytes: finalOutputBytes,
3210
+ lastLinePartial: false,
3211
+ firstLineExceedsLimit: false,
3212
+ maxLines,
3213
+ maxBytes
3214
+ };
3215
+ }
3216
+ function truncateTail(content, options = {}) {
3217
+ const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
3218
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
3219
+ const totalBytes = utf8ByteLength(content);
3220
+ const lines = splitLinesForCounting(content);
3221
+ const totalLines = lines.length;
3222
+ if (totalLines <= maxLines && totalBytes <= maxBytes) {
3223
+ return {
3224
+ content,
3225
+ truncated: false,
3226
+ truncatedBy: null,
3227
+ totalLines,
3228
+ totalBytes,
3229
+ outputLines: totalLines,
3230
+ outputBytes: totalBytes,
3231
+ lastLinePartial: false,
3232
+ firstLineExceedsLimit: false,
3233
+ maxLines,
3234
+ maxBytes
3235
+ };
3236
+ }
3237
+ const outputLinesArr = [];
3238
+ let outputBytesCount = 0;
3239
+ let truncatedBy = "lines";
3240
+ let lastLinePartial = false;
3241
+ for (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) {
3242
+ const line = lines[i];
3243
+ const lineBytes = utf8ByteLength(line) + (outputLinesArr.length > 0 ? 1 : 0);
3244
+ if (outputBytesCount + lineBytes > maxBytes) {
3245
+ truncatedBy = "bytes";
3246
+ if (outputLinesArr.length === 0) {
3247
+ const truncatedLine = truncateStringToBytesFromEnd(line, maxBytes);
3248
+ outputLinesArr.unshift(truncatedLine);
3249
+ outputBytesCount = utf8ByteLength(truncatedLine);
3250
+ lastLinePartial = true;
3251
+ }
3252
+ break;
3253
+ }
3254
+ outputLinesArr.unshift(line);
3255
+ outputBytesCount += lineBytes;
3256
+ }
3257
+ if (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {
3258
+ truncatedBy = "lines";
3259
+ }
3260
+ const outputContent = outputLinesArr.join("\n");
3261
+ const finalOutputBytes = utf8ByteLength(outputContent);
3262
+ return {
3263
+ content: outputContent,
3264
+ truncated: true,
3265
+ truncatedBy,
3266
+ totalLines,
3267
+ totalBytes,
3268
+ outputLines: outputLinesArr.length,
3269
+ outputBytes: finalOutputBytes,
3270
+ lastLinePartial,
3271
+ firstLineExceedsLimit: false,
3272
+ maxLines,
3273
+ maxBytes
3274
+ };
3153
3275
  }
3154
3276
  function formatToolResultMessage(toolCall, result) {
3155
3277
  const exitCode = typeof result.exit_code === "number" ? result.exit_code : result.success === true ? 0 : 1;
3156
3278
  const durationMs = typeof result.duration_ms === "number" ? result.duration_ms : 0;
3157
- const command = typeof result.command === "string" && result.command.length > 0 ? result.command : formatPseudoCommand(toolCall);
3158
- const stdout = truncatePresentationOutput(renderToolStdout(result));
3159
- const stderr = renderToolStderr(result, exitCode);
3160
- const metaLine = buildMetaLine(toolCall, result);
3279
+ const command = typeof result.command === "string" && result.command.length > 0 ? result.command : (() => {
3280
+ const unixCommand = formatToolCallAsUnixCommand(toolCall);
3281
+ if (unixCommand) {
3282
+ return unixCommand;
3283
+ }
3284
+ const parts = [toolCall.name];
3285
+ for (const [name, value] of Object.entries(toolCall.parameters ?? {})) {
3286
+ if (value === void 0 || value === null) {
3287
+ continue;
3288
+ }
3289
+ if (typeof value === "boolean") {
3290
+ parts.push(value ? `--${name}` : `--no-${name}`);
3291
+ continue;
3292
+ }
3293
+ if (typeof value === "string" && !value.includes("\n") && !/\s/.test(value)) {
3294
+ parts.push(`--${name}`, value);
3295
+ continue;
3296
+ }
3297
+ parts.push(`--${name}`, JSON.stringify(value));
3298
+ }
3299
+ return parts.join(" ");
3300
+ })();
3301
+ const stdout = truncatePresentationOutput(renderToolStdout(result), toolCall);
3302
+ const stderr = typeof result.stderr === "string" && result.stderr.length > 0 ? result.stderr : exitCode !== 0 && typeof result.error === "string" ? result.error : "";
3303
+ const metaLine = (() => {
3304
+ const commandName = result.command_name;
3305
+ const route = result.route;
3306
+ const metadata = {
3307
+ tool: typeof commandName === "string" ? commandName : toolCall.name,
3308
+ route: typeof route === "string" ? route : toolCall.name
3309
+ };
3310
+ for (const source of [toolCall.parameters ?? {}, result]) {
3311
+ for (const key of ["path", "url", "query", "taskId", "task_id", "pattern"]) {
3312
+ const value = source[key];
3313
+ if (typeof value === "string" && value.length > 0) {
3314
+ metadata[key] = value;
3315
+ }
3316
+ }
3317
+ }
3318
+ const pairs = Object.entries(metadata);
3319
+ if (pairs.length === 0) {
3320
+ return "";
3321
+ }
3322
+ return `[meta] ${pairs.map(([key, value]) => `${key}=${typeof value === "string" ? JSON.stringify(value) : String(value)}`).join(" ")}`;
3323
+ })();
3161
3324
  const lines = [`$ ${command}`];
3162
3325
  if (stdout) {
3163
3326
  lines.push(stdout);
@@ -3176,7 +3339,8 @@ ${stderr}`);
3176
3339
  if (metaLine) {
3177
3340
  lines.push(metaLine);
3178
3341
  }
3179
- lines.push(`[exit:${exitCode} | ${formatDuration(durationMs)}]`);
3342
+ const duration = durationMs >= 1e3 ? `${(durationMs / 1e3).toFixed(1)}s` : `${Math.max(0, Math.round(durationMs))}ms`;
3343
+ lines.push(`[exit:${exitCode} | ${duration}]`);
3180
3344
  return lines.join("\n");
3181
3345
  }
3182
3346
  function parseToolResultMessage(content) {
@@ -3221,7 +3385,14 @@ function parseToolResultMessage(content) {
3221
3385
  const exitMatch = line.match(/^\[exit:(-?\d+)\s*\|\s*([^\]]+)\]$/);
3222
3386
  if (exitMatch) {
3223
3387
  exitCode = Number(exitMatch[1]);
3224
- durationMs = parseDuration(exitMatch[2]);
3388
+ const rawDuration = exitMatch[2].trim().toLowerCase();
3389
+ if (rawDuration.endsWith("ms")) {
3390
+ durationMs = Number(rawDuration.slice(0, -2)) || 0;
3391
+ } else if (rawDuration.endsWith("s")) {
3392
+ durationMs = Math.round((Number(rawDuration.slice(0, -1)) || 0) * 1e3);
3393
+ } else {
3394
+ durationMs = Number(rawDuration) || 0;
3395
+ }
3225
3396
  inStderr = false;
3226
3397
  continue;
3227
3398
  }
@@ -3231,7 +3402,36 @@ function parseToolResultMessage(content) {
3231
3402
  stdoutLines.push(line);
3232
3403
  }
3233
3404
  }
3234
- const metadata = parseMetadata(metaLine);
3405
+ const metadata = (() => {
3406
+ if (!metaLine) {
3407
+ return {};
3408
+ }
3409
+ const values = {};
3410
+ const regex = /(\w+)=((?:"(?:[^"\\]|\\.)*")|\S+)/g;
3411
+ let match;
3412
+ while ((match = regex.exec(metaLine)) !== null) {
3413
+ const key = match[1];
3414
+ const rawValue = match[2];
3415
+ if (rawValue.startsWith('"')) {
3416
+ try {
3417
+ values[key] = JSON.parse(rawValue);
3418
+ } catch {
3419
+ values[key] = rawValue.slice(1, -1);
3420
+ }
3421
+ continue;
3422
+ }
3423
+ if (rawValue === "true") {
3424
+ values[key] = true;
3425
+ } else if (rawValue === "false") {
3426
+ values[key] = false;
3427
+ } else if (!Number.isNaN(Number(rawValue))) {
3428
+ values[key] = Number(rawValue);
3429
+ } else {
3430
+ values[key] = rawValue;
3431
+ }
3432
+ }
3433
+ return values;
3434
+ })();
3235
3435
  const stdout = stdoutLines.join("\n").trim();
3236
3436
  const stderr = stderrLines.join("\n").trim();
3237
3437
  const error = errorLine ?? (exitCode === 0 ? void 0 : stderr || void 0);
@@ -3307,116 +3507,122 @@ function renderToolStdout(result) {
3307
3507
  }
3308
3508
  return JSON.stringify(remainder, null, 2);
3309
3509
  }
3310
- function renderToolStderr(result, exitCode) {
3311
- if (typeof result.stderr === "string" && result.stderr.length > 0) {
3312
- return result.stderr;
3313
- }
3314
- if (exitCode !== 0 && typeof result.error === "string") {
3315
- return result.error;
3316
- }
3317
- return "";
3318
- }
3319
- function truncatePresentationOutput(output) {
3510
+ function truncatePresentationOutput(output, toolCall) {
3320
3511
  if (!output) {
3321
3512
  return "";
3322
3513
  }
3323
- const lines = output.split(/\r?\n/);
3324
- if (lines.length <= MAX_PRESENTATION_LINES && output.length <= MAX_PRESENTATION_CHARS) {
3514
+ const isBash = isBashLikeToolCall(toolCall);
3515
+ const truncation = isBash ? truncateTail(output, { maxLines: DEFAULT_MAX_LINES, maxBytes: DEFAULT_MAX_BYTES }) : truncateHead(output, { maxLines: DEFAULT_MAX_LINES, maxBytes: DEFAULT_MAX_BYTES });
3516
+ if (!truncation.truncated) {
3325
3517
  return output;
3326
3518
  }
3327
- const truncated = lines.slice(0, MAX_PRESENTATION_LINES).join("\n");
3328
- return `${truncated}
3329
- --- output truncated (${lines.length} lines, ${output.length} chars) ---
3330
- Use more specific commands, filters, or line ranges to narrow the result.`;
3331
- }
3332
- function formatPseudoCommand(toolCall) {
3333
- const unixCommand = formatToolCallAsUnixCommand(toolCall);
3334
- if (unixCommand) {
3335
- return unixCommand;
3519
+ const suffix = buildTruncationNotice(toolCall, truncation);
3520
+ if (!suffix) {
3521
+ return truncation.content;
3336
3522
  }
3337
- const parts = [toolCall.name];
3338
- for (const [name, value] of Object.entries(toolCall.parameters ?? {})) {
3339
- if (value === void 0 || value === null) {
3340
- continue;
3523
+ if (!truncation.content) {
3524
+ return suffix;
3525
+ }
3526
+ return `${truncation.content}
3527
+
3528
+ ${suffix}`;
3529
+ }
3530
+ function buildTruncationNotice(toolCall, truncation) {
3531
+ const kind = (() => {
3532
+ if (isBashLikeToolCall(toolCall)) {
3533
+ return "bash";
3341
3534
  }
3342
- if (typeof value === "boolean") {
3343
- parts.push(value ? `--${name}` : `--no-${name}`);
3344
- continue;
3535
+ const normalized = toolCall.name.toLowerCase();
3536
+ if (normalized.includes("read")) return "read";
3537
+ if (normalized === "ls" || normalized.includes("list")) return "ls";
3538
+ if (normalized.includes("grep") || normalized.includes("search")) return "grep";
3539
+ if (normalized.includes("find")) return "find";
3540
+ return "default";
3541
+ })();
3542
+ if (kind === "read") {
3543
+ if (truncation.firstLineExceedsLimit) {
3544
+ return `[Line 1 exceeds ${formatSize(truncation.maxBytes)} limit. Use bash to read a bounded byte range.]`;
3345
3545
  }
3346
- if (typeof value === "string" && !value.includes("\n") && !/\s/.test(value)) {
3347
- parts.push(`--${name}`, value);
3348
- continue;
3546
+ const endLine = Math.max(0, truncation.outputLines);
3547
+ const nextOffset = endLine + 1;
3548
+ if (truncation.truncatedBy === "lines") {
3549
+ return `[Showing lines 1-${endLine} of ${truncation.totalLines}. Use offset=${nextOffset} to continue.]`;
3349
3550
  }
3350
- parts.push(`--${name}`, JSON.stringify(value));
3551
+ return `[Showing lines 1-${endLine} of ${truncation.totalLines} (${formatSize(truncation.maxBytes)} limit). Use offset=${nextOffset} to continue.]`;
3351
3552
  }
3352
- return parts.join(" ");
3353
- }
3354
- function buildMetaLine(toolCall, result) {
3355
- const commandName = result.command_name;
3356
- const route = result.route;
3357
- const metadata = {
3358
- tool: typeof commandName === "string" ? commandName : toolCall.name,
3359
- route: typeof route === "string" ? route : toolCall.name
3360
- };
3361
- for (const source of [toolCall.parameters ?? {}, result]) {
3362
- for (const key of ["path", "url", "query", "taskId", "task_id", "pattern"]) {
3363
- const value = source[key];
3364
- if (typeof value === "string" && value.length > 0) {
3365
- metadata[key] = value;
3366
- }
3553
+ if (kind === "bash") {
3554
+ const startLine = truncation.totalLines - truncation.outputLines + 1;
3555
+ const endLine = truncation.totalLines;
3556
+ if (truncation.lastLinePartial) {
3557
+ return `[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line exceeds ${formatSize(truncation.maxBytes)}).]`;
3558
+ }
3559
+ if (truncation.truncatedBy === "lines") {
3560
+ return `[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.]`;
3367
3561
  }
3562
+ return `[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(truncation.maxBytes)} limit).]`;
3368
3563
  }
3369
- const pairs = Object.entries(metadata);
3370
- if (pairs.length === 0) {
3371
- return "";
3564
+ if (kind === "grep") {
3565
+ return `[${formatSize(truncation.maxBytes)} limit reached. Refine pattern or narrow path.]`;
3372
3566
  }
3373
- return `[meta] ${pairs.map(([key, value]) => `${key}=${typeof value === "string" ? JSON.stringify(value) : String(value)}`).join(" ")}`;
3567
+ if (kind === "find") {
3568
+ return `[${formatSize(truncation.maxBytes)} limit reached. Refine pattern or increase limit.]`;
3569
+ }
3570
+ if (kind === "ls") {
3571
+ return `[${formatSize(truncation.maxBytes)} limit reached. Use a narrower path.]`;
3572
+ }
3573
+ return `[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).]`;
3374
3574
  }
3375
- function parseMetadata(text) {
3376
- if (!text) {
3377
- return {};
3575
+ function isBashLikeToolCall(toolCall) {
3576
+ if (toolCall.kind === "bash" || toolCall.kind === "background_bash") {
3577
+ return true;
3378
3578
  }
3379
- const values = {};
3380
- const regex = /(\w+)=((?:"(?:[^"\\]|\\.)*")|\S+)/g;
3381
- let match;
3382
- while ((match = regex.exec(text)) !== null) {
3383
- const key = match[1];
3384
- const rawValue = match[2];
3385
- if (rawValue.startsWith('"')) {
3386
- try {
3387
- values[key] = JSON.parse(rawValue);
3388
- } catch {
3389
- values[key] = rawValue.slice(1, -1);
3579
+ const normalized = toolCall.name.toLowerCase();
3580
+ return normalized === "bash" || normalized === "backgroundbash";
3581
+ }
3582
+ function utf8ByteLength(text) {
3583
+ if (!text) {
3584
+ return 0;
3585
+ }
3586
+ return new TextEncoder().encode(text).length;
3587
+ }
3588
+ function truncateStringToBytesFromEnd(str, maxBytes) {
3589
+ if (maxBytes <= 0) return "";
3590
+ let outputBytes = 0;
3591
+ let start = str.length;
3592
+ for (let i = str.length; i > 0; ) {
3593
+ let characterStart = i - 1;
3594
+ const code = str.charCodeAt(characterStart);
3595
+ let characterBytes;
3596
+ if (code >= 56320 && code <= 57343 && characterStart > 0) {
3597
+ const previous = str.charCodeAt(characterStart - 1);
3598
+ if (previous >= 55296 && previous <= 56319) {
3599
+ characterStart--;
3600
+ characterBytes = 4;
3601
+ } else {
3602
+ characterBytes = 3;
3390
3603
  }
3391
- continue;
3392
- }
3393
- if (rawValue === "true") {
3394
- values[key] = true;
3395
- } else if (rawValue === "false") {
3396
- values[key] = false;
3397
- } else if (!Number.isNaN(Number(rawValue))) {
3398
- values[key] = Number(rawValue);
3604
+ } else if (code >= 55296 && code <= 56319) {
3605
+ characterBytes = 3;
3399
3606
  } else {
3400
- values[key] = rawValue;
3607
+ characterBytes = code <= 127 ? 1 : code <= 2047 ? 2 : 3;
3401
3608
  }
3609
+ if (outputBytes + characterBytes > maxBytes) break;
3610
+ outputBytes += characterBytes;
3611
+ start = characterStart;
3612
+ i = characterStart;
3402
3613
  }
3403
- return values;
3614
+ return str.slice(start);
3404
3615
  }
3405
- function formatDuration(durationMs) {
3406
- if (durationMs >= 1e3) {
3407
- return `${(durationMs / 1e3).toFixed(1)}s`;
3616
+ function formatSize(bytes) {
3617
+ if (bytes < 1024) {
3618
+ return `${bytes}B`;
3408
3619
  }
3409
- return `${Math.max(0, Math.round(durationMs))}ms`;
3410
- }
3411
- function parseDuration(raw) {
3412
- const trimmed = raw.trim().toLowerCase();
3413
- if (trimmed.endsWith("ms")) {
3414
- return Number(trimmed.slice(0, -2)) || 0;
3620
+ const kb = bytes / 1024;
3621
+ if (kb < 1024) {
3622
+ return `${kb.toFixed(1)}KB`;
3415
3623
  }
3416
- if (trimmed.endsWith("s")) {
3417
- return Math.round((Number(trimmed.slice(0, -1)) || 0) * 1e3);
3418
- }
3419
- return Number(trimmed) || 0;
3624
+ const mb = kb / 1024;
3625
+ return `${mb.toFixed(1)}MB`;
3420
3626
  }
3421
3627
 
3422
3628
  // src/agent-response-parser.ts
@@ -3788,10 +3994,7 @@ var AgentLoop = class {
3788
3994
  if (this.deps.formatToolResult) {
3789
3995
  result = this.deps.formatToolResult(result, tc.name);
3790
3996
  }
3791
- let resultStr = formatToolResultMessage(tc, result);
3792
- resultStr = truncateToolResult(resultStr, {
3793
- strategy: "head-tail"
3794
- });
3997
+ const resultStr = formatToolResultMessage(tc, result);
3795
3998
  if (wasTruncated && this._truncatedToolInfo && i === 0) {
3796
3999
  this._truncatedToolInfo.executionSucceeded = result.success === true;
3797
4000
  }
@@ -7494,6 +7697,6 @@ async function executeToolLoopStep(options) {
7494
7697
  };
7495
7698
  }
7496
7699
 
7497
- export { AGENT_MACHINE_STATES, AgentLoop, AgentMemoryLayer, ApiError, BackgroundBashRunCommand, BaseMemoryLayer, BaseValidationEnforcer, BashRunCommand, CODE_QUALITY_RULE_LINE, CharTokenEstimator, DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT, DEFAULT_ALLOWED_RUN_TARGETS, DEFAULT_RUN_COMMAND_REGISTRY, DEFAULT_THREAD_AUTO_SCROLL_BOTTOM_THRESHOLD, DEFAULT_TOOL_MEMORY_EXTRACTOR, ERROR_RECOVERY_RULE_LINE, ERROR_TRUNCATED_RESPONSE, INCREMENTAL_TESTING_RULE_LINE, JUST_BASH_SCRIPT_EXECUTION_RESTRICTION_LINES, JUST_BASH_SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES, LLMClient, LLMResponseSchema, MAX_TOOL_RESULT_CHARS, PORT_CONFLICT_RULE_LINE, PendingAgentMessageBuffer, ProxyTool, ROOT_CAUSES_RULE_LINE, RunCommand, RunCommandRegistry, SHARED_TOOL_CALL_EXAMPLE_LINES, SHARED_TOOL_USAGE_RULE, SINGLE_TOOL_CALL_RUN_LINE_EXAMPLE, SKILL_INVOKE_READ_RULE_LINE, STANDARD_TOOL_CALL_FORMAT_RULES, SUPPORTED_RUN_TARGETS, StreamingToolParser, SubAgentTool, TODO_LIST_FIRST_RESPONSE_RULE_LINE, TOOL_CALL_SEPARATOR_RULE, Tool, ToolCallSchema, ToolLoopAgentRuntime, ToolRegistry, ToolRunCommand, VALIDATE_AFTER_CHANGES_RULE_LINE, WebToolLoopAgentRuntime, WebValidationEnforcer, agentMachine, applyIdleWebAgentState, applyInitialWebAgentRunState, buildAgentIdentityLine, buildAgentSystemPrompt, buildCompactionEntry, buildCoreStaticRules, buildNoStructuredResponseFoundError, buildSkillAwareStaticContext, buildSkillsSection, buildStepUserMessage, buildToolLogRevealFrames, buildToolUsageExample, buildValidationErrorMessage, buildWebRuntimeRules, buildWorkspaceCodingStaticRules, canonicalizeCompactionText, coerceToolCallToDefinition, configure, containsStandaloneStructuredInvocationStart, createAgentMemoryLayer, createAppendToolsSectionCustomizer, createBackgroundBashDefinition, createConversationSink, createCustomRunCommandRegistry, createInitialWebAgentState, createRunCommandRuntimeBindings, createRuntimeStore, createToolAgentMessage, createToolRegistry, createToolsSectionOverrideCustomizer, createWebAgentMessageIdGenerator, createWebSearchToolActions, createWebToolLoopCallbacks, decodeEscapedShellText, defineRuntimeController, enrichToolResultWithUnixMetadata, executeBackgroundUnixCommandString, executeToolCallWithRunCommands, executeToolLoopStep, executeToolSafe, executeUnixCommandString, extractPrimaryCommandMetadata, extractTruncatedToolInfo, formatToolCallAsUnixCommand, formatToolDefinitions, formatToolResultMessage, formatToolsSection, formatUnixToolSurface, formatZodValidationError, getDiagnosticSummaryLine, getProviderConfig, getRunCommandPromptAvailability, getToolLogSummaryLine, isBackgroundBashToolCall, isBashToolCall, limitEntriesByRecency, machineStateToWebAgentPhase, mapConversationRoleToAgentRole, parseAgentResponse, parseResponseWithRecovery, parseStructuredAgentText, parseToolResultMessage, parseUnixToolCommand, readDiagnosticLevel, readDiagnosticSource, resolveToolDefinitionForInvocation, runStructuredLLMCompaction, selectLatestByKey, shouldAutoScrollThread, shouldSkipStepUserMessage, stripDiagnosticMessagePrefix, suppressWebValidationLog, tokenizeUnixCommand, truncateToolResult };
7700
+ export { AGENT_MACHINE_STATES, AgentLoop, AgentMemoryLayer, ApiError, BackgroundBashRunCommand, BaseMemoryLayer, BaseValidationEnforcer, BashRunCommand, CODE_QUALITY_RULE_LINE, CharTokenEstimator, DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT, DEFAULT_ALLOWED_RUN_TARGETS, DEFAULT_RUN_COMMAND_REGISTRY, DEFAULT_THREAD_AUTO_SCROLL_BOTTOM_THRESHOLD, DEFAULT_TOOL_MEMORY_EXTRACTOR, ERROR_RECOVERY_RULE_LINE, ERROR_TRUNCATED_RESPONSE, INCREMENTAL_TESTING_RULE_LINE, JUST_BASH_SCRIPT_EXECUTION_RESTRICTION_LINES, JUST_BASH_SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES, LLMClient, LLMResponseSchema, PORT_CONFLICT_RULE_LINE, PendingAgentMessageBuffer, ProxyTool, ROOT_CAUSES_RULE_LINE, RunCommand, RunCommandRegistry, SHARED_TOOL_CALL_EXAMPLE_LINES, SHARED_TOOL_USAGE_RULE, SINGLE_TOOL_CALL_RUN_LINE_EXAMPLE, SKILL_INVOKE_READ_RULE_LINE, STANDARD_TOOL_CALL_FORMAT_RULES, SUPPORTED_RUN_TARGETS, StreamingToolParser, SubAgentTool, TODO_LIST_FIRST_RESPONSE_RULE_LINE, TOOL_CALL_SEPARATOR_RULE, Tool, ToolCallSchema, ToolLoopAgentRuntime, ToolRegistry, ToolRunCommand, VALIDATE_AFTER_CHANGES_RULE_LINE, WebToolLoopAgentRuntime, WebValidationEnforcer, agentMachine, applyIdleWebAgentState, applyInitialWebAgentRunState, buildAgentIdentityLine, buildAgentSystemPrompt, buildCompactionEntry, buildCoreStaticRules, buildNoStructuredResponseFoundError, buildSkillAwareStaticContext, buildSkillsSection, buildStepUserMessage, buildToolLogRevealFrames, buildToolUsageExample, buildValidationErrorMessage, buildWebRuntimeRules, buildWorkspaceCodingStaticRules, canonicalizeCompactionText, coerceToolCallToDefinition, configure, containsStandaloneStructuredInvocationStart, createAgentMemoryLayer, createAppendToolsSectionCustomizer, createBackgroundBashDefinition, createConversationSink, createCustomRunCommandRegistry, createInitialWebAgentState, createRunCommandRuntimeBindings, createRuntimeStore, createToolAgentMessage, createToolRegistry, createToolsSectionOverrideCustomizer, createWebAgentMessageIdGenerator, createWebSearchToolActions, createWebToolLoopCallbacks, decodeEscapedShellText, defineRuntimeController, enrichToolResultWithUnixMetadata, executeBackgroundUnixCommandString, executeToolCallWithRunCommands, executeToolLoopStep, executeToolSafe, executeUnixCommandString, extractPrimaryCommandMetadata, extractTruncatedToolInfo, formatToolCallAsUnixCommand, formatToolDefinitions, formatToolResultMessage, formatToolsSection, formatUnixToolSurface, formatZodValidationError, getDiagnosticSummaryLine, getProviderConfig, getRunCommandPromptAvailability, getToolLogSummaryLine, isBackgroundBashToolCall, isBashToolCall, limitEntriesByRecency, machineStateToWebAgentPhase, mapConversationRoleToAgentRole, parseAgentResponse, parseResponseWithRecovery, parseStructuredAgentText, parseToolResultMessage, parseUnixToolCommand, readDiagnosticLevel, readDiagnosticSource, resolveToolDefinitionForInvocation, runStructuredLLMCompaction, selectLatestByKey, shouldAutoScrollThread, shouldSkipStepUserMessage, stripDiagnosticMessagePrefix, suppressWebValidationLog, tokenizeUnixCommand };
7498
7701
  //# sourceMappingURL=index.js.map
7499
7702
  //# sourceMappingURL=index.js.map