File size: 5,131 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import * as path from 'node:path';
import type { GitService } from '../services/gitService.js';
import type { GeminiClient } from '../core/client.js';
import { getErrorMessage } from './errors.js';
import { z } from 'zod';
import type { Content } from '@google/genai';
import type { ToolCallRequestInfo } from '../scheduler/types.js';

export interface ToolCallData<HistoryType = unknown, ArgsType = unknown> {
  history?: HistoryType;
  clientHistory?: readonly Content[];
  commitHash?: string;
  toolCall: {
    name: string;
    args: ArgsType;
  };
  messageId?: string;
}

const ContentSchema = z
  .object({
    role: z.string().optional(),
    parts: z.array(z.record(z.unknown())),
  })
  .passthrough();

export function getToolCallDataSchema(historyItemSchema?: z.ZodTypeAny) {
  const schema = historyItemSchema ?? z.any();

  return z.object({
    history: z.array(schema).optional(),
    clientHistory: z.array(ContentSchema).optional(),
    commitHash: z.string().optional(),
    toolCall: z.object({
      name: z.string(),
      args: z.record(z.unknown()),
    }),
    messageId: z.string().optional(),
  });
}

export function generateCheckpointFileName(
  toolCall: ToolCallRequestInfo,
): string | null {
  const toolArgs = toolCall.args;
  const rawFilePath = toolArgs['file_path'];

  if (typeof rawFilePath !== 'string' || !rawFilePath) {
    return null;
  }
  const toolFilePath = rawFilePath;

  const timestamp = new Date()
    .toISOString()
    .replace(/:/g, '-')
    .replace(/\./g, '_');
  const toolName = toolCall.name;
  const fileName = path.basename(toolFilePath);

  return `${timestamp}-${fileName}-${toolName}`;
}

export function formatCheckpointDisplayList(filenames: string[]): string {
  return getTruncatedCheckpointNames(filenames).join('\n');
}

export function getTruncatedCheckpointNames(filenames: string[]): string[] {
  return filenames.map((file) => {
    const components = file.split('.');
    if (components.length <= 1) {
      return file;
    }
    components.pop();
    return components.join('.');
  });
}

export async function processRestorableToolCalls<HistoryType>(
  toolCalls: ToolCallRequestInfo[],
  gitService: GitService,
  geminiClient: GeminiClient,
  history?: HistoryType,
): Promise<{
  checkpointsToWrite: Map<string, string>;
  toolCallToCheckpointMap: Map<string, string>;
  errors: string[];
}> {
  const checkpointsToWrite = new Map<string, string>();
  const toolCallToCheckpointMap = new Map<string, string>();
  const errors: string[] = [];

  for (const toolCall of toolCalls) {
    try {
      let commitHash: string | undefined;
      try {
        commitHash = await gitService.createFileSnapshot(
          `Snapshot for ${toolCall.name}`,
        );
      } catch (error) {
        errors.push(
          `Failed to create new snapshot for ${
            toolCall.name
          }: ${getErrorMessage(error)}. Attempting to use current commit.`,
        );
        commitHash = await gitService.getCurrentCommitHash();
      }

      if (!commitHash) {
        errors.push(
          `Failed to create snapshot for ${toolCall.name}. Checkpointing may not be working properly. Ensure Git is installed and the project directory is accessible.`,
        );
        continue;
      }

      const checkpointFileName = generateCheckpointFileName(toolCall);
      if (!checkpointFileName) {
        errors.push(
          `Skipping restorable tool call due to missing file_path: ${toolCall.name}`,
        );
        continue;
      }

      const clientHistory = geminiClient.getHistory();
      const checkpointData: ToolCallData<HistoryType> = {
        history,
        clientHistory,
        toolCall: {
          name: toolCall.name,
          args: toolCall.args,
        },
        commitHash,
        messageId: toolCall.prompt_id,
      };

      const fileName = `${checkpointFileName}.json`;
      checkpointsToWrite.set(fileName, JSON.stringify(checkpointData, null, 2));
      toolCallToCheckpointMap.set(
        toolCall.callId,
        fileName.replace('.json', ''),
      );
    } catch (error) {
      errors.push(
        `Failed to create checkpoint for ${toolCall.name}: ${getErrorMessage(
          error,
        )}`,
      );
    }
  }

  return { checkpointsToWrite, toolCallToCheckpointMap, errors };
}

export interface CheckpointInfo {
  messageId: string;
  checkpoint: string;
}

export function getCheckpointInfoList(
  checkpointFiles: Map<string, string>,
): CheckpointInfo[] {
  const checkpointInfoList: CheckpointInfo[] = [];

  for (const [file, content] of checkpointFiles) {
    try {
      const parsed: unknown = JSON.parse(content);
      const result = z
        .object({ messageId: z.string() })
        .passthrough()
        .safeParse(parsed);
      if (result.success) {
        checkpointInfoList.push({
          messageId: result.data.messageId,
          checkpoint: file.replace('.json', ''),
        });
      }
    } catch {
      // Ignore invalid JSON files
    }
  }
  return checkpointInfoList;
}