@eminent337/aery-core 0.67.120 → 0.67.121
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/README.md +14 -0
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +31 -1
- package/dist/agent-loop.js.map +1 -1
- package/dist/agent.d.ts +4 -3
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +7 -3
- package/dist/agent.js.map +1 -1
- package/dist/harness/agent-harness.d.ts +103 -0
- package/dist/harness/agent-harness.d.ts.map +1 -0
- package/dist/harness/agent-harness.js +788 -0
- package/dist/harness/agent-harness.js.map +1 -0
- package/dist/harness/compaction/branch-summarization.d.ts +88 -0
- package/dist/harness/compaction/branch-summarization.d.ts.map +1 -0
- package/dist/harness/compaction/branch-summarization.js +243 -0
- package/dist/harness/compaction/branch-summarization.js.map +1 -0
- package/dist/harness/compaction/compaction.d.ts +122 -0
- package/dist/harness/compaction/compaction.d.ts.map +1 -0
- package/dist/harness/compaction/compaction.js +631 -0
- package/dist/harness/compaction/compaction.js.map +1 -0
- package/dist/harness/compaction/utils.d.ts +38 -0
- package/dist/harness/compaction/utils.d.ts.map +1 -0
- package/dist/harness/compaction/utils.js +153 -0
- package/dist/harness/compaction/utils.js.map +1 -0
- package/dist/harness/env/nodejs.d.ts +50 -0
- package/dist/harness/env/nodejs.d.ts.map +1 -0
- package/dist/harness/env/nodejs.js +487 -0
- package/dist/harness/env/nodejs.js.map +1 -0
- package/dist/harness/execution-env.d.ts +4 -0
- package/dist/harness/execution-env.d.ts.map +1 -0
- package/dist/harness/execution-env.js +3 -0
- package/dist/harness/execution-env.js.map +1 -0
- package/dist/harness/factory.d.ts +6 -0
- package/dist/harness/factory.d.ts.map +1 -0
- package/dist/harness/factory.js +9 -0
- package/dist/harness/factory.js.map +1 -0
- package/dist/harness/messages.d.ts +51 -0
- package/dist/harness/messages.d.ts.map +1 -0
- package/dist/harness/messages.js +102 -0
- package/dist/harness/messages.js.map +1 -0
- package/dist/harness/prompt-templates.d.ts +47 -0
- package/dist/harness/prompt-templates.d.ts.map +1 -0
- package/dist/harness/prompt-templates.js +201 -0
- package/dist/harness/prompt-templates.js.map +1 -0
- package/dist/harness/session/jsonl-repo.d.ts +26 -0
- package/dist/harness/session/jsonl-repo.d.ts.map +1 -0
- package/dist/harness/session/jsonl-repo.js +97 -0
- package/dist/harness/session/jsonl-repo.js.map +1 -0
- package/dist/harness/session/jsonl-storage.d.ts +33 -0
- package/dist/harness/session/jsonl-storage.d.ts.map +1 -0
- package/dist/harness/session/jsonl-storage.js +159 -0
- package/dist/harness/session/jsonl-storage.js.map +1 -0
- package/dist/harness/session/memory-repo.d.ts +18 -0
- package/dist/harness/session/memory-repo.d.ts.map +1 -0
- package/dist/harness/session/memory-repo.js +42 -0
- package/dist/harness/session/memory-repo.js.map +1 -0
- package/dist/harness/session/memory-storage.d.ts +26 -0
- package/dist/harness/session/memory-storage.d.ts.map +1 -0
- package/dist/harness/session/memory-storage.js +89 -0
- package/dist/harness/session/memory-storage.js.map +1 -0
- package/dist/harness/session/repo/jsonl.d.ts +20 -0
- package/dist/harness/session/repo/jsonl.d.ts.map +1 -0
- package/dist/harness/session/repo/jsonl.js +92 -0
- package/dist/harness/session/repo/jsonl.js.map +1 -0
- package/dist/harness/session/repo/memory.d.ts +18 -0
- package/dist/harness/session/repo/memory.d.ts.map +1 -0
- package/dist/harness/session/repo/memory.js +42 -0
- package/dist/harness/session/repo/memory.js.map +1 -0
- package/dist/harness/session/repo/shared.d.ts +10 -0
- package/dist/harness/session/repo/shared.d.ts.map +1 -0
- package/dist/harness/session/repo/shared.js +31 -0
- package/dist/harness/session/repo/shared.js.map +1 -0
- package/dist/harness/session/repo-utils.d.ts +10 -0
- package/dist/harness/session/repo-utils.d.ts.map +1 -0
- package/dist/harness/session/repo-utils.js +31 -0
- package/dist/harness/session/repo-utils.js.map +1 -0
- package/dist/harness/session/session.d.ts +32 -0
- package/dist/harness/session/session.d.ts.map +1 -0
- package/dist/harness/session/session.js +196 -0
- package/dist/harness/session/session.js.map +1 -0
- package/dist/harness/session/storage/jsonl.d.ts +30 -0
- package/dist/harness/session/storage/jsonl.d.ts.map +1 -0
- package/dist/harness/session/storage/jsonl.js +170 -0
- package/dist/harness/session/storage/jsonl.js.map +1 -0
- package/dist/harness/session/storage/memory.d.ts +26 -0
- package/dist/harness/session/storage/memory.d.ts.map +1 -0
- package/dist/harness/session/storage/memory.js +90 -0
- package/dist/harness/session/storage/memory.js.map +1 -0
- package/dist/harness/session/uuid.d.ts +2 -0
- package/dist/harness/session/uuid.d.ts.map +1 -0
- package/dist/harness/session/uuid.js +50 -0
- package/dist/harness/session/uuid.js.map +1 -0
- package/dist/harness/skills.d.ts +43 -0
- package/dist/harness/skills.d.ts.map +1 -0
- package/dist/harness/skills.js +255 -0
- package/dist/harness/skills.js.map +1 -0
- package/dist/harness/system-prompt.d.ts +3 -0
- package/dist/harness/system-prompt.d.ts.map +1 -0
- package/dist/harness/system-prompt.js +30 -0
- package/dist/harness/system-prompt.js.map +1 -0
- package/dist/harness/types.d.ts +578 -0
- package/dist/harness/types.d.ts.map +1 -0
- package/dist/harness/types.js +56 -0
- package/dist/harness/types.js.map +1 -0
- package/dist/harness/utils/shell-output.d.ts +14 -0
- package/dist/harness/utils/shell-output.d.ts.map +1 -0
- package/dist/harness/utils/shell-output.js +125 -0
- package/dist/harness/utils/shell-output.js.map +1 -0
- package/dist/harness/utils/truncate.d.ts +70 -0
- package/dist/harness/utils/truncate.d.ts.map +1 -0
- package/dist/harness/utils/truncate.js +288 -0
- package/dist/harness/utils/truncate.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -1
- package/dist/node.d.ts +3 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +3 -0
- package/dist/node.js.map +1 -0
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +5 -2
- package/dist/proxy.js.map +1 -1
- package/dist/types.d.ts +50 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +19 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compaction.js","sourceRoot":"","sources":["../../../src/harness/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,8BAA8B,EAC9B,mBAAmB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAwB,eAAe,EAAE,GAAG,EAAE,EAAE,EAAsC,MAAM,aAAa,CAAC;AACjH,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAYpB;;GAEG;AACH,SAAS,qBAAqB,CAC7B,QAAwB,EACxB,OAA2B,EAC3B,mBAA2B,EACV;IACjB,MAAM,OAAO,GAAG,aAAa,EAAE,CAAC;IAEhC,+DAA+D;IAC/D,IAAI,mBAAmB,IAAI,CAAC,EAAE,CAAC;QAC9B,MAAM,cAAc,GAAG,OAAO,CAAC,mBAAmB,CAAoB,CAAC;QACvE,IAAI,CAAC,cAAc,CAAC,QAAQ,IAAI,cAAc,CAAC,OAAO,EAAE,CAAC;YACxD,qDAAqD;YACrD,MAAM,OAAO,GAAG,cAAc,CAAC,OAA4B,CAAC;YAC5D,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;gBACtC,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,SAAS;oBAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YACxD,CAAC;YACD,IAAI,KAAK,CAAC,OAAO,CAAC,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AI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CACZ,CAAC;AAAA,CACF","sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AssistantMessage, ImageContent, Model, TextContent, Usage } from \"@eminent337/aery-ai\";\nimport { completeSimple } from \"@eminent337/aery-ai\";\nimport type { AgentMessage, ThinkingLevel } from \"../../types.js\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.js\";\nimport { buildSessionContext } from \"../session/session.js\";\nimport { type CompactionEntry, CompactionError, err, ok, type Result, type SessionTreeEntry } from \"../types.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.js\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\n/**\n * Extract file operations from messages and previous compaction entries.\n */\nfunction extractFileOperations(\n\tmessages: AgentMessage[],\n\tentries: SessionTreeEntry[],\n\tprevCompactionIndex: number,\n): FileOperations {\n\tconst fileOps = createFileOps();\n\n\t// Collect from previous compaction's details (if pi-generated)\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = entries[prevCompactionIndex] as CompactionEntry;\n\t\tif (!prevCompaction.fromHook && prevCompaction.details) {\n\t\t\t// fromHook field kept for session file compatibility\n\t\t\tconst details = prevCompaction.details as CompactionDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\tfor (const f of details.modifiedFiles) fileOps.edited.add(f);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract from tool calls in messages\n\tfor (const msg of messages) {\n\t\textractFileOpsFromMessage(msg, fileOps);\n\t}\n\n\treturn fileOps;\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/**\n * Extract AgentMessage from an entry if it produces one.\n * Returns undefined for entries that don't contribute to LLM context.\n */\nfunction getMessageFromEntry(entry: SessionTreeEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message as AgentMessage;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content as string | (TextContent | ImageContent)[],\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction getMessageFromEntryForCompaction(entry: SessionTreeEntry): AgentMessage | undefined {\n\tif (entry.type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\treturn getMessageFromEntry(entry);\n}\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n}\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n};\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionTreeEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message as AgentMessage);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tif (!settings.enabled) return false;\n\treturn contextTokens > contextWindow - settings.reserveTokens;\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tconst content = (message as { content: string | Array<{ type: string; text?: string }> }).content;\n\t\t\tif (typeof content === \"string\") {\n\t\t\t\tchars = content.length;\n\t\t\t} else if (Array.isArray(content)) {\n\t\t\t\tfor (const block of content) {\n\t\t\t\t\tif (block.type === \"text\" && block.text) {\n\t\t\t\t\t\tchars += block.text.length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tif (typeof message.content === \"string\") {\n\t\t\t\tchars = message.content.length;\n\t\t\t} else {\n\t\t\t\tfor (const block of message.content) {\n\t\t\t\t\tif (block.type === \"text\" && block.text) {\n\t\t\t\t\t\tchars += block.text.length;\n\t\t\t\t\t}\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\tchars += 4800; // Estimate images as 4000 chars, or 1200 tokens\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionTreeEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// branch_summary and custom_message are user-role messages, valid cut points\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionTreeEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\t// branch_summary and custom_message are user-role messages, can start a turn\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionTreeEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\n\t\t// Estimate this message's size\n\t\tconst messageTokens = estimateTokens(entry.message as AgentMessage);\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at session header or compaction boundaries\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\t// Stop if we hit any message\n\t\t\tbreak;\n\t\t}\n\t\t// Include this non-message entry (bash, settings change, etc.)\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n): Promise<Result<string, CompactionError>> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions =\n\t\tmodel.reasoning && thinkingLevel && thinkingLevel !== \"off\"\n\t\t\t? { maxTokens, signal, apiKey, headers, reasoning: thinkingLevel }\n\t\t\t: { maxTokens, signal, apiKey, headers };\n\n\tconst responseResult: Result<AssistantMessage, CompactionError> = await completeSimple(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t).then(\n\t\t(response) => ok<AssistantMessage, CompactionError>(response),\n\t\t(error: unknown) =>\n\t\t\terr<AssistantMessage, CompactionError>(new CompactionError(\"unknown\", \"Summarization request failed\", error)),\n\t);\n\tif (!responseResult.ok) return err(responseResult.error);\n\n\tconst response = responseResult.value;\n\tif (response.stopReason === \"aborted\") {\n\t\treturn err(new CompactionError(\"aborted\", response.errorMessage || \"Summarization aborted\"));\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn err(\n\t\t\tnew CompactionError(\n\t\t\t\t\"summarization_failed\",\n\t\t\t\t`Summarization failed: ${response.errorMessage || \"Unknown error\"}`,\n\t\t\t),\n\t\t);\n\t}\n\n\tconst textContent = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\treturn ok(textContent);\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionTreeEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\nexport { serializeConversation } from \"./utils.js\";\n\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n): Promise<Result<CompactionResult, CompactionError>> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\tif (!firstKeptEntryId) {\n\t\treturn err(new CompactionError(\"invalid_session\", \"First kept entry has no UUID - session may need migration\"));\n\t}\n\n\tlet summary: string;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? generateSummary(\n\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve(ok<string, CompactionError>(\"No prior history.\")),\n\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\tturnPrefixMessages,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t),\n\t\t]);\n\t\tif (!historyResult.ok) return err(historyResult.error);\n\t\tif (!turnPrefixResult.ok) return err(turnPrefixResult.error);\n\t\tsummary = `${historyResult.value}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult.value}`;\n\t} else {\n\t\tconst summaryResult = await generateSummary(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t);\n\t\tif (!summaryResult.ok) return err(summaryResult.error);\n\t\tsummary = summaryResult.value;\n\t}\n\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn ok({\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles } as CompactionDetails,\n\t});\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n): Promise<Result<string, CompactionError>> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst responseResult: Result<AssistantMessage, CompactionError> = await completeSimple(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tmodel.reasoning && thinkingLevel && thinkingLevel !== \"off\"\n\t\t\t? { maxTokens, signal, apiKey, headers, reasoning: thinkingLevel }\n\t\t\t: { maxTokens, signal, apiKey, headers },\n\t).then(\n\t\t(response) => ok<AssistantMessage, CompactionError>(response),\n\t\t(error: unknown) =>\n\t\t\terr<AssistantMessage, CompactionError>(\n\t\t\t\tnew CompactionError(\"unknown\", \"Turn prefix summarization request failed\", error),\n\t\t\t),\n\t);\n\tif (!responseResult.ok) return err(responseResult.error);\n\n\tconst response = responseResult.value;\n\tif (response.stopReason === \"aborted\") {\n\t\treturn err(new CompactionError(\"aborted\", response.errorMessage || \"Turn prefix summarization aborted\"));\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn err(\n\t\t\tnew CompactionError(\n\t\t\t\t\"summarization_failed\",\n\t\t\t\t`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`,\n\t\t\t),\n\t\t);\n\t}\n\n\treturn ok(\n\t\tresponse.content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\\n\"),\n\t);\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared utilities for compaction and branch summarization.
|
|
3
|
+
*/
|
|
4
|
+
import type { Message } from "@eminent337/aery-ai";
|
|
5
|
+
import type { AgentMessage } from "../../types.js";
|
|
6
|
+
export interface FileOperations {
|
|
7
|
+
read: Set<string>;
|
|
8
|
+
written: Set<string>;
|
|
9
|
+
edited: Set<string>;
|
|
10
|
+
}
|
|
11
|
+
export declare function createFileOps(): FileOperations;
|
|
12
|
+
/**
|
|
13
|
+
* Extract file operations from tool calls in an assistant message.
|
|
14
|
+
*/
|
|
15
|
+
export declare function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void;
|
|
16
|
+
/**
|
|
17
|
+
* Compute final file lists from file operations.
|
|
18
|
+
* Returns readFiles (files only read, not modified) and modifiedFiles.
|
|
19
|
+
*/
|
|
20
|
+
export declare function computeFileLists(fileOps: FileOperations): {
|
|
21
|
+
readFiles: string[];
|
|
22
|
+
modifiedFiles: string[];
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Format file operations as XML tags for summary.
|
|
26
|
+
*/
|
|
27
|
+
export declare function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string;
|
|
28
|
+
/**
|
|
29
|
+
* Serialize LLM messages to text for summarization.
|
|
30
|
+
* This prevents the model from treating it as a conversation to continue.
|
|
31
|
+
* Call convertToLlm() first to handle custom message types.
|
|
32
|
+
*
|
|
33
|
+
* Tool results are truncated to keep the summarization request within
|
|
34
|
+
* reasonable token budgets. Full content is not needed for summarization.
|
|
35
|
+
*/
|
|
36
|
+
export declare function serializeConversation(messages: Message[]): string;
|
|
37
|
+
export declare const SUMMARIZATION_SYSTEM_PROMPT = "You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.";
|
|
38
|
+
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/harness/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAMnD,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAClB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACpB;AAED,wBAAgB,aAAa,IAAI,cAAc,CAM9C;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CA2B9F;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG;IAAE,SAAS,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAA;CAAE,CAK1G;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,MAAM,CAUzF;AAmBD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAqDjE;AAMD,eAAO,MAAM,2BAA2B,oUAEmF,CAAC","sourcesContent":["/**\n * Shared utilities for compaction and branch summarization.\n */\n\nimport type { Message } from \"@eminent337/aery-ai\";\nimport type { AgentMessage } from \"../../types.js\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\n/**\n * Extract file operations from tool calls in an assistant message.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\n\t\tconst args = block.arguments as Record<string, unknown> | undefined;\n\t\tif (!args) continue;\n\n\t\tconst path = typeof args.path === \"string\" ? args.path : undefined;\n\t\tif (!path) continue;\n\n\t\tswitch (block.name) {\n\t\t\tcase \"read\":\n\t\t\t\tfileOps.read.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"write\":\n\t\t\t\tfileOps.written.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"edit\":\n\t\t\t\tfileOps.edited.add(path);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content =\n\t\t\t\ttypeof msg.content === \"string\"\n\t\t\t\t\t? msg.content\n\t\t\t\t\t: msg.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst textParts: string[] = [];\n\t\t\tconst thinkingParts: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\ttextParts.push(block.text);\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tthinkingParts.push(block.thinking);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${argsStr})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (thinkingParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant thinking]: ${thinkingParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (textParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant]: ${textParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = msg.content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n"]}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared utilities for compaction and branch summarization.
|
|
3
|
+
*/
|
|
4
|
+
export function createFileOps() {
|
|
5
|
+
return {
|
|
6
|
+
read: new Set(),
|
|
7
|
+
written: new Set(),
|
|
8
|
+
edited: new Set(),
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Extract file operations from tool calls in an assistant message.
|
|
13
|
+
*/
|
|
14
|
+
export function extractFileOpsFromMessage(message, fileOps) {
|
|
15
|
+
if (message.role !== "assistant")
|
|
16
|
+
return;
|
|
17
|
+
if (!("content" in message) || !Array.isArray(message.content))
|
|
18
|
+
return;
|
|
19
|
+
for (const block of message.content) {
|
|
20
|
+
if (typeof block !== "object" || block === null)
|
|
21
|
+
continue;
|
|
22
|
+
if (!("type" in block) || block.type !== "toolCall")
|
|
23
|
+
continue;
|
|
24
|
+
if (!("arguments" in block) || !("name" in block))
|
|
25
|
+
continue;
|
|
26
|
+
const args = block.arguments;
|
|
27
|
+
if (!args)
|
|
28
|
+
continue;
|
|
29
|
+
const path = typeof args.path === "string" ? args.path : undefined;
|
|
30
|
+
if (!path)
|
|
31
|
+
continue;
|
|
32
|
+
switch (block.name) {
|
|
33
|
+
case "read":
|
|
34
|
+
fileOps.read.add(path);
|
|
35
|
+
break;
|
|
36
|
+
case "write":
|
|
37
|
+
fileOps.written.add(path);
|
|
38
|
+
break;
|
|
39
|
+
case "edit":
|
|
40
|
+
fileOps.edited.add(path);
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Compute final file lists from file operations.
|
|
47
|
+
* Returns readFiles (files only read, not modified) and modifiedFiles.
|
|
48
|
+
*/
|
|
49
|
+
export function computeFileLists(fileOps) {
|
|
50
|
+
const modified = new Set([...fileOps.edited, ...fileOps.written]);
|
|
51
|
+
const readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();
|
|
52
|
+
const modifiedFiles = [...modified].sort();
|
|
53
|
+
return { readFiles: readOnly, modifiedFiles };
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Format file operations as XML tags for summary.
|
|
57
|
+
*/
|
|
58
|
+
export function formatFileOperations(readFiles, modifiedFiles) {
|
|
59
|
+
const sections = [];
|
|
60
|
+
if (readFiles.length > 0) {
|
|
61
|
+
sections.push(`<read-files>\n${readFiles.join("\n")}\n</read-files>`);
|
|
62
|
+
}
|
|
63
|
+
if (modifiedFiles.length > 0) {
|
|
64
|
+
sections.push(`<modified-files>\n${modifiedFiles.join("\n")}\n</modified-files>`);
|
|
65
|
+
}
|
|
66
|
+
if (sections.length === 0)
|
|
67
|
+
return "";
|
|
68
|
+
return `\n\n${sections.join("\n\n")}`;
|
|
69
|
+
}
|
|
70
|
+
// ============================================================================
|
|
71
|
+
// Message Serialization
|
|
72
|
+
// ============================================================================
|
|
73
|
+
/** Maximum characters for a tool result in serialized summaries. */
|
|
74
|
+
const TOOL_RESULT_MAX_CHARS = 2000;
|
|
75
|
+
/**
|
|
76
|
+
* Truncate text to a maximum character length for summarization.
|
|
77
|
+
* Keeps the beginning and appends a truncation marker.
|
|
78
|
+
*/
|
|
79
|
+
function truncateForSummary(text, maxChars) {
|
|
80
|
+
if (text.length <= maxChars)
|
|
81
|
+
return text;
|
|
82
|
+
const truncatedChars = text.length - maxChars;
|
|
83
|
+
return `${text.slice(0, maxChars)}\n\n[... ${truncatedChars} more characters truncated]`;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Serialize LLM messages to text for summarization.
|
|
87
|
+
* This prevents the model from treating it as a conversation to continue.
|
|
88
|
+
* Call convertToLlm() first to handle custom message types.
|
|
89
|
+
*
|
|
90
|
+
* Tool results are truncated to keep the summarization request within
|
|
91
|
+
* reasonable token budgets. Full content is not needed for summarization.
|
|
92
|
+
*/
|
|
93
|
+
export function serializeConversation(messages) {
|
|
94
|
+
const parts = [];
|
|
95
|
+
for (const msg of messages) {
|
|
96
|
+
if (msg.role === "user") {
|
|
97
|
+
const content = typeof msg.content === "string"
|
|
98
|
+
? msg.content
|
|
99
|
+
: msg.content
|
|
100
|
+
.filter((c) => c.type === "text")
|
|
101
|
+
.map((c) => c.text)
|
|
102
|
+
.join("");
|
|
103
|
+
if (content)
|
|
104
|
+
parts.push(`[User]: ${content}`);
|
|
105
|
+
}
|
|
106
|
+
else if (msg.role === "assistant") {
|
|
107
|
+
const textParts = [];
|
|
108
|
+
const thinkingParts = [];
|
|
109
|
+
const toolCalls = [];
|
|
110
|
+
for (const block of msg.content) {
|
|
111
|
+
if (block.type === "text") {
|
|
112
|
+
textParts.push(block.text);
|
|
113
|
+
}
|
|
114
|
+
else if (block.type === "thinking") {
|
|
115
|
+
thinkingParts.push(block.thinking);
|
|
116
|
+
}
|
|
117
|
+
else if (block.type === "toolCall") {
|
|
118
|
+
const args = block.arguments;
|
|
119
|
+
const argsStr = Object.entries(args)
|
|
120
|
+
.map(([k, v]) => `${k}=${JSON.stringify(v)}`)
|
|
121
|
+
.join(", ");
|
|
122
|
+
toolCalls.push(`${block.name}(${argsStr})`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (thinkingParts.length > 0) {
|
|
126
|
+
parts.push(`[Assistant thinking]: ${thinkingParts.join("\n")}`);
|
|
127
|
+
}
|
|
128
|
+
if (textParts.length > 0) {
|
|
129
|
+
parts.push(`[Assistant]: ${textParts.join("\n")}`);
|
|
130
|
+
}
|
|
131
|
+
if (toolCalls.length > 0) {
|
|
132
|
+
parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
else if (msg.role === "toolResult") {
|
|
136
|
+
const content = msg.content
|
|
137
|
+
.filter((c) => c.type === "text")
|
|
138
|
+
.map((c) => c.text)
|
|
139
|
+
.join("");
|
|
140
|
+
if (content) {
|
|
141
|
+
parts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return parts.join("\n\n");
|
|
146
|
+
}
|
|
147
|
+
// ============================================================================
|
|
148
|
+
// Summarization System Prompt
|
|
149
|
+
// ============================================================================
|
|
150
|
+
export const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.
|
|
151
|
+
|
|
152
|
+
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;
|
|
153
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/harness/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAeH,MAAM,UAAU,aAAa,GAAmB;IAC/C,OAAO;QACN,IAAI,EAAE,IAAI,GAAG,EAAE;QACf,OAAO,EAAE,IAAI,GAAG,EAAE;QAClB,MAAM,EAAE,IAAI,GAAG,EAAE;KACjB,CAAC;AAAA,CACF;AAED;;GAEG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB,EAAE,OAAuB,EAAQ;IAC/F,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO;IACzC,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO;IAEvE,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACrC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;YAAE,SAAS;QAC1D,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YAAE,SAAS;QAC9D,IAAI,CAAC,CAAC,WAAW,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC;YAAE,SAAS;QAE5D,MAAM,IAAI,GAAG,KAAK,CAAC,SAAgD,CAAC;QACpE,IAAI,CAAC,IAAI;YAAE,SAAS;QAEpB,MAAM,IAAI,GAAG,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;QACnE,IAAI,CAAC,IAAI;YAAE,SAAS;QAEpB,QAAQ,KAAK,CAAC,IAAI,EAA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AAC;YACD,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC1B,KAAK,CAAC,IAAI,CAAC,2BAA2B,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YAC/D,CAAC;QACF,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YACtC,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO;iBACzB,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;iBACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;iBAClB,IAAI,CAAC,EAAE,CAAC,CAAC;YACX,IAAI,OAAO,EAAE,CAAC;gBACb,KAAK,CAAC,IAAI,CAAC,kBAAkB,kBAAkB,CAAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC,CAAC;YACpF,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAAA,CAC1B;AAED,+EAA+E;AAC/E,8BAA8B;AAC9B,+EAA+E;AAE/E,MAAM,CAAC,MAAM,2BAA2B,GAAG;;2HAEgF,CAAC","sourcesContent":["/**\n * Shared utilities for compaction and branch summarization.\n */\n\nimport type { Message } from \"@eminent337/aery-ai\";\nimport type { AgentMessage } from \"../../types.js\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\n/**\n * Extract file operations from tool calls in an assistant message.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\n\t\tconst args = block.arguments as Record<string, unknown> | undefined;\n\t\tif (!args) continue;\n\n\t\tconst path = typeof args.path === \"string\" ? args.path : undefined;\n\t\tif (!path) continue;\n\n\t\tswitch (block.name) {\n\t\t\tcase \"read\":\n\t\t\t\tfileOps.read.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"write\":\n\t\t\t\tfileOps.written.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"edit\":\n\t\t\t\tfileOps.edited.add(path);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content =\n\t\t\t\ttypeof msg.content === \"string\"\n\t\t\t\t\t? msg.content\n\t\t\t\t\t: msg.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst textParts: string[] = [];\n\t\t\tconst thinkingParts: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\ttextParts.push(block.text);\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tthinkingParts.push(block.thinking);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${argsStr})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (thinkingParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant thinking]: ${thinkingParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (textParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant]: ${textParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = msg.content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n"]}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type ExecutionEnv, ExecutionError, FileError, type FileInfo, type Result } from "../types.js";
|
|
2
|
+
export declare class NodeExecutionEnv implements ExecutionEnv {
|
|
3
|
+
cwd: string;
|
|
4
|
+
private shellPath?;
|
|
5
|
+
private shellEnv?;
|
|
6
|
+
constructor(options: {
|
|
7
|
+
cwd: string;
|
|
8
|
+
shellPath?: string;
|
|
9
|
+
shellEnv?: NodeJS.ProcessEnv;
|
|
10
|
+
});
|
|
11
|
+
absolutePath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;
|
|
12
|
+
joinPath(parts: string[], abortSignal?: AbortSignal): Promise<Result<string, FileError>>;
|
|
13
|
+
exec(command: string, options?: {
|
|
14
|
+
cwd?: string;
|
|
15
|
+
env?: Record<string, string>;
|
|
16
|
+
timeout?: number;
|
|
17
|
+
abortSignal?: AbortSignal;
|
|
18
|
+
onStdout?: (chunk: string) => void;
|
|
19
|
+
onStderr?: (chunk: string) => void;
|
|
20
|
+
}): Promise<Result<{
|
|
21
|
+
stdout: string;
|
|
22
|
+
stderr: string;
|
|
23
|
+
exitCode: number;
|
|
24
|
+
}, ExecutionError>>;
|
|
25
|
+
readTextFile(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;
|
|
26
|
+
readBinaryFile(path: string, abortSignal?: AbortSignal): Promise<Result<Uint8Array, FileError>>;
|
|
27
|
+
writeFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;
|
|
28
|
+
appendFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;
|
|
29
|
+
fileInfo(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo, FileError>>;
|
|
30
|
+
listDir(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo[], FileError>>;
|
|
31
|
+
canonicalPath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;
|
|
32
|
+
exists(path: string, abortSignal?: AbortSignal): Promise<Result<boolean, FileError>>;
|
|
33
|
+
createDir(path: string, options?: {
|
|
34
|
+
recursive?: boolean;
|
|
35
|
+
abortSignal?: AbortSignal;
|
|
36
|
+
}): Promise<Result<void, FileError>>;
|
|
37
|
+
remove(path: string, options?: {
|
|
38
|
+
recursive?: boolean;
|
|
39
|
+
force?: boolean;
|
|
40
|
+
abortSignal?: AbortSignal;
|
|
41
|
+
}): Promise<Result<void, FileError>>;
|
|
42
|
+
createTempDir(prefix?: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;
|
|
43
|
+
createTempFile(options?: {
|
|
44
|
+
prefix?: string;
|
|
45
|
+
suffix?: string;
|
|
46
|
+
abortSignal?: AbortSignal;
|
|
47
|
+
}): Promise<Result<string, FileError>>;
|
|
48
|
+
cleanup(): Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=nodejs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"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,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,WAAW,CAAC,EAAE,WAAW,CAAA;KAAE,GAC1D,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAYlC;IAEK,MAAM,CACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAC;QAAC,WAAW,CAAC,EAAE,WAAW,CAAA;KAAE,GAC3E,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAYlC;IAEK,aAAa,CAAC,MAAM,GAAE,MAAe,EAAE,WAAW,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAW1G;IAEK,cAAc,CAAC,OAAO,CAAC,EAAE;QAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,WAAW,CAAC,EAAE,WAAW,CAAC;KAC1B,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAYrC;IAEK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAE7B;CACD","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport {\n\taccess,\n\tappendFile,\n\tlstat,\n\tmkdir,\n\tmkdtemp,\n\treaddir,\n\treadFile,\n\trealpath,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport {\n\ttype ExecutionEnv,\n\tExecutionError,\n\terr,\n\tFileError,\n\ttype FileInfo,\n\ttype FileKind,\n\tok,\n\ttype Result,\n} from \"../types.js\";\n\nfunction resolvePath(cwd: string, path: string): string {\n\treturn isAbsolute(path) ? path : resolve(cwd, path);\n}\n\nfunction fileKindFromStats(stats: {\n\tisFile(): boolean;\n\tisDirectory(): boolean;\n\tisSymbolicLink(): boolean;\n}): FileKind | undefined {\n\tif (stats.isFile()) return \"file\";\n\tif (stats.isDirectory()) return \"directory\";\n\tif (stats.isSymbolicLink()) return \"symlink\";\n\treturn undefined;\n}\n\nfunction fileInfoFromStats(\n\tpath: string,\n\tstats: { isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean; size: number; mtimeMs: number },\n): Result<FileInfo, FileError> {\n\tconst kind = fileKindFromStats(stats);\n\tif (!kind) return err(new FileError(\"invalid\", \"Unsupported file type\", path));\n\treturn ok({\n\t\tname: path.replace(/\\/+$/, \"\").split(\"/\").pop() ?? path,\n\t\tpath,\n\t\tkind,\n\t\tsize: stats.size,\n\t\tmtimeMs: stats.mtimeMs,\n\t});\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction toFileError(error: unknown, path?: string): FileError {\n\tif (error instanceof FileError) return error;\n\tif (isNodeError(error)) {\n\t\tconst message = error.message;\n\t\tswitch (error.code) {\n\t\t\tcase \"ABORT_ERR\":\n\t\t\t\treturn new FileError(\"aborted\", message, path, error);\n\t\t\tcase \"ENOENT\":\n\t\t\t\treturn new FileError(\"not_found\", message, path, error);\n\t\t\tcase \"EACCES\":\n\t\t\tcase \"EPERM\":\n\t\t\t\treturn new FileError(\"permission_denied\", message, path, error);\n\t\t\tcase \"ENOTDIR\":\n\t\t\t\treturn new FileError(\"not_directory\", message, path, error);\n\t\t\tcase \"EISDIR\":\n\t\t\t\treturn new FileError(\"is_directory\", message, path, error);\n\t\t\tcase \"EINVAL\":\n\t\t\t\treturn new FileError(\"invalid\", message, path, error);\n\t\t}\n\t}\n\treturn new FileError(\"unknown\", error instanceof Error ? error.message : String(error), path, error);\n}\n\nfunction abortResult<TValue>(signal: AbortSignal | undefined, path?: string): Result<TValue, FileError> | undefined {\n\treturn signal?.aborted ? err(new FileError(\"aborted\", \"aborted\", path)) : undefined;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n\ttry {\n\t\tawait access(path, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function runCommand(\n\tcommand: string,\n\targs: string[],\n\ttimeoutMs: number,\n): Promise<{ stdout: string; status: number | null }> {\n\treturn await new Promise((resolve) => {\n\t\tlet stdout = \"\";\n\t\tlet child: ReturnType<typeof spawn>;\n\t\ttry {\n\t\t\tchild = spawn(command, args, { stdio: [\"ignore\", \"pipe\", \"ignore\"] });\n\t\t} catch {\n\t\t\tresolve({ stdout: \"\", status: null });\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(() => {\n\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t}, timeoutMs);\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\tstdout += chunk;\n\t\t});\n\t\tchild.on(\"error\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve({ stdout: \"\", status: null });\n\t\t});\n\t\tchild.on(\"close\", (status) => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve({ stdout, status });\n\t\t});\n\t});\n}\n\nasync function findBashOnPath(): Promise<string | null> {\n\tconst result =\n\t\tprocess.platform === \"win32\"\n\t\t\t? await runCommand(\"where\", [\"bash.exe\"], 5000)\n\t\t\t: await runCommand(\"which\", [\"bash\"], 5000);\n\tif (result.status !== 0 || !result.stdout) return null;\n\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\treturn firstMatch && (await pathExists(firstMatch)) ? firstMatch : null;\n}\n\nasync function getShellConfig(\n\tcustomShellPath?: string,\n): Promise<Result<{ shell: string; args: string[] }, ExecutionError>> {\n\tif (customShellPath) {\n\t\tif (await pathExists(customShellPath)) {\n\t\t\treturn ok({ shell: customShellPath, args: [\"-c\"] });\n\t\t}\n\t\treturn err(new ExecutionError(\"shell_unavailable\", `Custom shell path not found: ${customShellPath}`));\n\t}\n\tif (process.platform === \"win32\") {\n\t\tconst candidates: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) candidates.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) candidates.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tfor (const candidate of candidates) {\n\t\t\tif (await pathExists(candidate)) {\n\t\t\t\treturn ok({ shell: candidate, args: [\"-c\"] });\n\t\t\t}\n\t\t}\n\t\tconst bashOnPath = await findBashOnPath();\n\t\tif (bashOnPath) {\n\t\t\treturn ok({ shell: bashOnPath, args: [\"-c\"] });\n\t\t}\n\t\treturn err(new ExecutionError(\"shell_unavailable\", \"No bash shell found\"));\n\t}\n\n\tif (await pathExists(\"/bin/bash\")) {\n\t\treturn ok({ shell: \"/bin/bash\", args: [\"-c\"] });\n\t}\n\tconst bashOnPath = await findBashOnPath();\n\tif (bashOnPath) {\n\t\treturn ok({ shell: bashOnPath, args: [\"-c\"] });\n\t}\n\treturn ok({ shell: \"sh\", args: [\"-c\"] });\n}\n\nfunction getShellEnv(baseEnv?: NodeJS.ProcessEnv, extraEnv?: Record<string, string>): NodeJS.ProcessEnv {\n\treturn {\n\t\t...process.env,\n\t\t...baseEnv,\n\t\t...extraEnv,\n\t};\n}\n\nfunction killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\ttry {\n\t\t\tspawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\t\tstdio: \"ignore\",\n\t\t\t\tdetached: true,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore errors.\n\t\t}\n\t\treturn;\n\t}\n\n\ttry {\n\t\tprocess.kill(-pid, \"SIGKILL\");\n\t} catch {\n\t\ttry {\n\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Process already dead.\n\t\t}\n\t}\n}\n\nexport class NodeExecutionEnv implements ExecutionEnv {\n\tcwd: string;\n\tprivate shellPath?: string;\n\tprivate shellEnv?: NodeJS.ProcessEnv;\n\n\tconstructor(options: { cwd: string; shellPath?: string; shellEnv?: NodeJS.ProcessEnv }) {\n\t\tthis.cwd = options.cwd;\n\t\tthis.shellPath = options.shellPath;\n\t\tthis.shellEnv = options.shellEnv;\n\t}\n\n\tasync absolutePath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<string>(abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\treturn ok(resolved);\n\t}\n\n\tasync joinPath(parts: string[], abortSignal?: AbortSignal): Promise<Result<string, FileError>> {\n\t\tconst joined = join(...parts);\n\t\tconst aborted = abortResult<string>(abortSignal, joined);\n\t\tif (aborted) return aborted;\n\t\treturn ok(joined);\n\t}\n\n\tasync exec(\n\t\tcommand: string,\n\t\toptions?: {\n\t\t\tcwd?: string;\n\t\t\tenv?: Record<string, string>;\n\t\t\ttimeout?: number;\n\t\t\tabortSignal?: AbortSignal;\n\t\t\tonStdout?: (chunk: string) => void;\n\t\t\tonStderr?: (chunk: string) => void;\n\t\t},\n\t): Promise<Result<{ stdout: string; stderr: string; exitCode: number }, ExecutionError>> {\n\t\tif (options?.abortSignal?.aborted) return err(new ExecutionError(\"aborted\", \"aborted\"));\n\n\t\tconst cwd = options?.cwd ? resolvePath(this.cwd, options.cwd) : this.cwd;\n\t\tconst shellConfig = await getShellConfig(this.shellPath);\n\t\tif (!shellConfig.ok) return shellConfig;\n\n\t\treturn await new Promise((resolvePromise) => {\n\t\t\tlet stdout = \"\";\n\t\t\tlet stderr = \"\";\n\t\t\tlet settled = false;\n\t\t\tlet timedOut = false;\n\t\t\tlet callbackError: ExecutionError | undefined;\n\t\t\tlet child: ReturnType<typeof spawn> | undefined;\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child?.pid) {\n\t\t\t\t\tkillProcessTree(child.pid);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst settle = (result: Result<{ stdout: string; stderr: string; exitCode: number }, ExecutionError>) => {\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\tif (options?.abortSignal) options.abortSignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolvePromise(result);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tchild = spawn(shellConfig.value.shell, [...shellConfig.value.args, command], {\n\t\t\t\t\tcwd,\n\t\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\t\tenv: getShellEnv(this.shellEnv, options?.env),\n\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tsettle(\n\t\t\t\t\terr(new ExecutionError(\"spawn_error\", error instanceof Error ? error.message : String(error), error)),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttimeoutId =\n\t\t\t\ttypeof options?.timeout === \"number\"\n\t\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\tif (child?.pid) {\n\t\t\t\t\t\t\t\tkillProcessTree(child.pid);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}, options.timeout * 1000)\n\t\t\t\t\t: undefined;\n\n\t\t\tif (options?.abortSignal) {\n\t\t\t\tif (options.abortSignal.aborted) {\n\t\t\t\t\tonAbort();\n\t\t\t\t} else {\n\t\t\t\t\toptions.abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\t\tchild.stderr?.setEncoding(\"utf8\");\n\t\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\t\tstdout += chunk;\n\t\t\t\ttry {\n\t\t\t\t\toptions?.onStdout?.(chunk);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcallbackError = new ExecutionError(\n\t\t\t\t\t\t\"unknown\",\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\terror,\n\t\t\t\t\t);\n\t\t\t\t\tonAbort();\n\t\t\t\t}\n\t\t\t});\n\t\t\tchild.stderr?.on(\"data\", (chunk: string) => {\n\t\t\t\tstderr += chunk;\n\t\t\t\ttry {\n\t\t\t\t\toptions?.onStderr?.(chunk);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcallbackError = new ExecutionError(\n\t\t\t\t\t\t\"unknown\",\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\terror,\n\t\t\t\t\t);\n\t\t\t\t\tonAbort();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\tsettle(err(new ExecutionError(\"spawn_error\", error.message, error)));\n\t\t\t});\n\n\t\t\tchild.on(\"close\", (code) => {\n\t\t\t\tif (callbackError) {\n\t\t\t\t\tsettle(err(callbackError));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (options?.abortSignal?.aborted) {\n\t\t\t\t\tsettle(err(new ExecutionError(\"aborted\", \"aborted\")));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tsettle(err(new ExecutionError(\"timeout\", `timeout:${options?.timeout}`)));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettle(ok({ stdout, stderr, exitCode: code ?? 0 }));\n\t\t\t});\n\t\t});\n\t}\n\n\tasync readTextFile(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<string>(abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await readFile(resolved, { encoding: \"utf8\", signal: abortSignal }));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync readBinaryFile(path: string, abortSignal?: AbortSignal): Promise<Result<Uint8Array, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<Uint8Array>(abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await readFile(resolved, { signal: abortSignal }));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync writeFile(\n\t\tpath: string,\n\t\tcontent: string | Uint8Array,\n\t\tabortSignal?: AbortSignal,\n\t): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<void>(abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolve(resolved, \"..\"), { recursive: true });\n\t\t\tconst afterMkdirAbort = abortResult<void>(abortSignal, resolved);\n\t\t\tif (afterMkdirAbort) return afterMkdirAbort;\n\t\t\tawait writeFile(resolved, content, { signal: abortSignal });\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync appendFile(\n\t\tpath: string,\n\t\tcontent: string | Uint8Array,\n\t\tabortSignal?: AbortSignal,\n\t): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<void>(abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolve(resolved, \"..\"), { recursive: true });\n\t\t\tconst afterMkdirAbort = abortResult<void>(abortSignal, resolved);\n\t\t\tif (afterMkdirAbort) return afterMkdirAbort;\n\t\t\tawait appendFile(resolved, content);\n\t\t\tconst afterAppendAbort = abortResult<void>(abortSignal, resolved);\n\t\t\tif (afterAppendAbort) return afterAppendAbort;\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync fileInfo(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<FileInfo>(abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn fileInfoFromStats(resolved, await lstat(resolved));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync listDir(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo[], FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<FileInfo[]>(abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tconst entries = await readdir(resolved, { withFileTypes: true });\n\t\t\tconst infos: FileInfo[] = [];\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst loopAbort = abortResult<FileInfo[]>(abortSignal, resolved);\n\t\t\t\tif (loopAbort) return loopAbort;\n\t\t\t\tconst entryPath = resolve(resolved, entry.name);\n\t\t\t\ttry {\n\t\t\t\t\tconst info = fileInfoFromStats(entryPath, await lstat(entryPath));\n\t\t\t\t\tif (info.ok) infos.push(info.value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn err(toFileError(error, entryPath));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ok(infos);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync canonicalPath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<string>(abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await realpath(resolved));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync exists(path: string, abortSignal?: AbortSignal): Promise<Result<boolean, FileError>> {\n\t\tconst result = await this.fileInfo(path, abortSignal);\n\t\tif (result.ok) return ok(true);\n\t\tif (result.error.code === \"not_found\") return ok(false);\n\t\treturn err(result.error);\n\t}\n\n\tasync createDir(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<void>(options?.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolved, { recursive: options?.recursive ?? true });\n\t\t\tconst afterMkdirAbort = abortResult<void>(options?.abortSignal, resolved);\n\t\t\tif (afterMkdirAbort) return afterMkdirAbort;\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync remove(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; force?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<void>(options?.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait rm(resolved, { recursive: options?.recursive ?? false, force: options?.force ?? false });\n\t\t\tconst afterRemoveAbort = abortResult<void>(options?.abortSignal, resolved);\n\t\t\tif (afterRemoveAbort) return afterRemoveAbort;\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync createTempDir(prefix: string = \"tmp-\", abortSignal?: AbortSignal): Promise<Result<string, FileError>> {\n\t\tconst aborted = abortResult<string>(abortSignal);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tconst path = await mkdtemp(join(tmpdir(), prefix));\n\t\t\tconst afterMkdtempAbort = abortResult<string>(abortSignal, path);\n\t\t\tif (afterMkdtempAbort) return afterMkdtempAbort;\n\t\t\treturn ok(path);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error));\n\t\t}\n\t}\n\n\tasync createTempFile(options?: {\n\t\tprefix?: string;\n\t\tsuffix?: string;\n\t\tabortSignal?: AbortSignal;\n\t}): Promise<Result<string, FileError>> {\n\t\tconst dir = await this.createTempDir(\"tmp-\", options?.abortSignal);\n\t\tif (!dir.ok) return dir;\n\t\tconst filePath = join(dir.value, `${options?.prefix ?? \"\"}${randomUUID()}${options?.suffix ?? \"\"}`);\n\t\tconst aborted = abortResult<string>(options?.abortSignal, filePath);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait writeFile(filePath, \"\", { signal: options?.abortSignal });\n\t\t\treturn ok(filePath);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, filePath));\n\t\t}\n\t}\n\n\tasync cleanup(): Promise<void> {\n\t\t// nothing to clean up for the local node implementation\n\t}\n}\n"]}
|