From ca702415e6575cbc202adf8d0033d03cb506099e Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 23 Dec 2025 21:39:44 -0500 Subject: [PATCH] Refactor metadata updates to track completion state and changes --- extensions/cli/src/commands/serve.ts | 12 +-- extensions/cli/src/util/exit.ts | 142 ++++++++++++++++++--------- 2 files changed, 99 insertions(+), 55 deletions(-) diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index f77e86f41..f0a41469b 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -387,10 +387,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { server.close(async () => { telemetryService.stopActiveTime(); - // Update metadata one final time before exiting + // Update metadata one final time before exiting (with completion flag) try { const history = services.chatHistory?.getHistory(); - await updateAgentMetadata(history); + await updateAgentMetadata({ history, isComplete: true }); } catch (err) { logger.debug("Failed to update metadata (non-critical)", err as any); } @@ -596,10 +596,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { server.close(async () => { telemetryService.stopActiveTime(); - // Update metadata one final time before exiting + // Update metadata one final time before exiting (with completion flag) try { const history = services.chatHistory?.getHistory(); - await updateAgentMetadata(history); + await updateAgentMetadata({ history, isComplete: true }); } catch (err) { logger.debug("Failed to update metadata (non-critical)", err as any); } @@ -628,10 +628,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { server.close(async () => { telemetryService.stopActiveTime(); - // Update metadata one final time before exiting + // Update metadata one final time before exiting (with completion flag) try { const history = services.chatHistory?.getHistory(); - await updateAgentMetadata(history); + await updateAgentMetadata({ history, isComplete: true }); } catch (err) { logger.debug("Failed to update metadata (non-critical)", err as any); } diff --git a/extensions/cli/src/util/exit.ts b/extensions/cli/src/util/exit.ts index 2d2c052d9..a378cd8de 100644 --- a/extensions/cli/src/util/exit.ts +++ b/extensions/cli/src/util/exit.ts @@ -14,16 +14,101 @@ import { postAgentMetadata, } from "./metadata.js"; +/** + * Options for updating agent metadata + */ +export interface UpdateAgentMetadataOptions { + /** Chat history to extract summary from */ + history?: ChatHistoryItem[]; + /** Set to true when the agent is exiting/completing */ + isComplete?: boolean; +} + +/** + * Collect diff stats and add to metadata + * @returns Whether there were any changes + */ +async function collectDiffStats( + metadata: Record, +): Promise { + try { + const { diff, repoFound } = await getGitDiffSnapshot(); + if (repoFound && diff) { + const { additions, deletions } = calculateDiffStats(diff); + if (additions > 0 || deletions > 0) { + metadata.additions = additions; + metadata.deletions = deletions; + return true; + } + } + } catch (err) { + logger.debug("Failed to calculate diff stats (non-critical)", err as any); + } + return false; +} + +/** + * Extract summary from conversation history and add to metadata + */ +function collectSummary( + metadata: Record, + history: ChatHistoryItem[] | undefined, +): void { + if (!history || history.length === 0) { + return; + } + try { + const summary = extractSummary(history); + if (summary) { + metadata.summary = summary; + } + } catch (err) { + logger.debug( + "Failed to extract conversation summary (non-critical)", + err as any, + ); + } +} + +/** + * Extract session usage and add to metadata + */ +function collectSessionUsage(metadata: Record): void { + try { + const usage = getSessionUsage(); + if (usage.totalCost > 0) { + metadata.usage = { + totalCost: parseFloat(usage.totalCost.toFixed(6)), + promptTokens: usage.promptTokens, + completionTokens: usage.completionTokens, + ...(usage.promptTokensDetails?.cachedTokens && { + cachedTokens: usage.promptTokensDetails.cachedTokens, + }), + ...(usage.promptTokensDetails?.cacheWriteTokens && { + cacheWriteTokens: usage.promptTokensDetails.cacheWriteTokens, + }), + }; + } + } catch (err) { + logger.debug("Failed to get session usage (non-critical)", err as any); + } +} + /** * Update agent session metadata in control plane * Collects diff stats and conversation summary, posts to control plane * This is called both during execution (after each turn) and before exit * - * @param history - Chat history to extract summary from (optional, will fetch if not provided) + * @param options - Options including history and completion state */ export async function updateAgentMetadata( - history?: ChatHistoryItem[], + options?: ChatHistoryItem[] | UpdateAgentMetadataOptions, ): Promise { + // Support both old signature (history array) and new signature (options object) + const { history, isComplete } = Array.isArray(options) + ? { history: options, isComplete: false } + : { history: options?.history, isComplete: options?.isComplete ?? false }; + try { const agentId = getAgentIdFromArgs(); if (!agentId) { @@ -32,57 +117,16 @@ export async function updateAgentMetadata( } const metadata: Record = {}; + const hasChanges = await collectDiffStats(metadata); - // Calculate diff stats - try { - const { diff, repoFound } = await getGitDiffSnapshot(); - if (repoFound && diff) { - const { additions, deletions } = calculateDiffStats(diff); - if (additions > 0 || deletions > 0) { - metadata.additions = additions; - metadata.deletions = deletions; - } - } - } catch (err) { - logger.debug("Failed to calculate diff stats (non-critical)", err as any); + if (isComplete) { + metadata.isComplete = true; + metadata.hasChanges = hasChanges; } - // Extract summary from conversation - if (history && history.length > 0) { - try { - const summary = extractSummary(history); - if (summary) { - metadata.summary = summary; - } - } catch (err) { - logger.debug( - "Failed to extract conversation summary (non-critical)", - err as any, - ); - } - } + collectSummary(metadata, history); + collectSessionUsage(metadata); - // Extract session usage (cost and token counts) - try { - const usage = getSessionUsage(); - if (usage.totalCost > 0) { - metadata.usage = { - totalCost: parseFloat(usage.totalCost.toFixed(6)), - promptTokens: usage.promptTokens, - completionTokens: usage.completionTokens, - ...(usage.promptTokensDetails?.cachedTokens && { - cachedTokens: usage.promptTokensDetails.cachedTokens, - }), - ...(usage.promptTokensDetails?.cacheWriteTokens && { - cacheWriteTokens: usage.promptTokensDetails.cacheWriteTokens, - }), - }; - } - } catch (err) { - logger.debug("Failed to get session usage (non-critical)", err as any); - } - - // Post metadata if we have any if (Object.keys(metadata).length > 0) { await postAgentMetadata(agentId, metadata); }