File size: 5,787 Bytes
e249c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { randomUUID } from "node:crypto";
import type { SessionEntry, PendingTranscriptRepairState } from "../../config/sessions/types.js";
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import { formatErrorMessage } from "../../infra/errors.js";
import { createSubsystemLogger } from "../../logging/subsystem.js";
import { runAgentHarnessBeforeMessageWriteHook } from "../harness/hook-helpers.js";
import { persistAgentSession } from "./attempt-execution.shared.js";
import { loadTranscriptAppendRuntime } from "./runtime-loaders.js";

const log = createSubsystemLogger("agents/assistant-transcript-repair");

type AssistantTranscriptRepairContext = {
  sessionKey: string;
  sessionEntry: SessionEntry | undefined;
  sessionStore?: Record<string, SessionEntry>;
  storePath: string;
  sessionAgentId: string;
  config: OpenClawConfig;
};

const EMPTY_USAGE = {
  input: 0,
  output: 0,
  cacheRead: 0,
  cacheWrite: 0,
  totalTokens: 0,
  cost: {
    input: 0,
    output: 0,
    cacheRead: 0,
    cacheWrite: 0,
    total: 0,
  },
} as const;

/** Records a final whose canonical transcript append failed. */
export async function persistAssistantTranscriptRepairRecord(params: {
  context: AssistantTranscriptRepairContext;
  replyText: string;
  provider?: string;
  model?: string;
  runOwnedSessionId: string;
}): Promise<void> {
  const { context, replyText, provider, model, runOwnedSessionId } = params;
  if (!replyText.trim() || !context.sessionStore || !context.sessionKey.trim()) {
    return;
  }
  const now = Date.now();
  const existing = context.sessionStore[context.sessionKey] ?? context.sessionEntry;
  if (!existing) {
    return;
  }
  const nextRepair: PendingTranscriptRepairState = {
    id: randomUUID(),
    text: replyText,
    ...(provider?.trim() ? { provider: provider.trim() } : {}),
    ...(model?.trim() ? { model: model.trim() } : {}),
    createdAt: now,
  };
  try {
    await persistAgentSession({
      sessionStore: context.sessionStore,
      sessionKey: context.sessionKey,
      storePath: context.storePath,
      initialEntry: existing,
      entry: {
        ...existing,
        pendingTranscriptRepair: [...(existing.pendingTranscriptRepair ?? []), nextRepair],
        updatedAt: now,
      },
      shouldPersist: (current) =>
        current?.sessionId === runOwnedSessionId && current.abortedLastRun !== true,
    });
  } catch (error) {
    log.warn(
      `Failed to persist assistant transcript repair record for ${context.sessionKey}: ${formatErrorMessage(error)}`,
    );
  }
}

/**
 * Restores missing assistant finals before another turn can observe or extend
 * the transcript. Append failures are an admission barrier: continuing would
 * give the model incomplete history and make the eventual append out of order.
 */
export async function repairPendingAssistantTranscriptTurns(params: {
  context: AssistantTranscriptRepairContext;
}): Promise<void> {
  const { context } = params;
  if (!context.sessionStore || !context.sessionKey) {
    return;
  }
  const entry = context.sessionStore[context.sessionKey] ?? context.sessionEntry;
  const backlog = entry?.pendingTranscriptRepair;
  if (!entry || !backlog?.length) {
    return;
  }

  const { appendExactAssistantMessageToSessionTranscript } = await loadTranscriptAppendRuntime();
  const remaining = [...backlog];
  while (remaining.length > 0) {
    const item = remaining[0]!;
    let result: Awaited<ReturnType<typeof appendExactAssistantMessageToSessionTranscript>>;
    try {
      result = await appendExactAssistantMessageToSessionTranscript({
        agentId: context.sessionAgentId,
        sessionKey: context.sessionKey,
        expectedSessionId: entry.sessionId,
        storePath: context.storePath,
        config: context.config,
        updateMode: "file-only",
        idempotencyKey: `transcript-repair:${item.id}`,
        beforeMessageWrite: runAgentHarnessBeforeMessageWriteHook,
        message: {
          role: "assistant",
          content: [{ type: "text", text: item.text }],
          api: "cli",
          provider: item.provider ?? "cli",
          model: item.model ?? "default",
          usage: EMPTY_USAGE,
          stopReason: "stop",
          timestamp: item.createdAt,
        },
      });
    } catch (error) {
      log.warn(
        `Assistant transcript repair failed for ${context.sessionKey}: ${formatErrorMessage(error)}`,
      );
      throw new Error("Previous assistant reply is still pending transcript recovery; retry.", {
        cause: error,
      });
    }

    if (!result.ok && result.code !== "blocked") {
      log.warn(`Assistant transcript repair failed for ${context.sessionKey}: ${result.reason}`);
      throw new Error("Previous assistant reply is still pending transcript recovery; retry.");
    }
    remaining.shift();
    if (result.ok) {
      log.info(`Re-appended missing assistant transcript turn for ${context.sessionKey}`);
    } else {
      log.warn(`Dropped blocked assistant transcript repair for ${context.sessionKey}`);
    }
  }

  const current = context.sessionStore[context.sessionKey];
  if (!current || current.sessionId !== entry.sessionId) {
    return;
  }
  try {
    await persistAgentSession({
      sessionStore: context.sessionStore,
      sessionKey: context.sessionKey,
      storePath: context.storePath,
      initialEntry: current,
      entry: { ...current, pendingTranscriptRepair: undefined, updatedAt: Date.now() },
      shouldPersist: (latest) => latest?.sessionId === entry.sessionId,
    });
  } catch (error) {
    // The exact append key makes a later retry safe after cleanup failure.
    log.warn(
      `Failed to clear assistant transcript repair record for ${context.sessionKey}: ${formatErrorMessage(error)}`,
    );
  }
}