File size: 9,405 Bytes
eb3f11e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import crypto from "node:crypto";
import { imageMimeFromFormat } from "@openclaw/media-core/mime";
import { readImageMetadataFromHeader } from "../../media/image-ops.js";
import type { ComputerActResult } from "../../plugins/computer-use-contract.js";
import { DEFAULT_IMAGE_MAX_DIMENSION_PX } from "../image-sanitization.js";
import type { AgentMessage, AgentToolResult } from "../runtime/index.js";
import { sanitizeContentBlocksImages } from "../tool-images.js";
import type {
  ComputerContextEpoch,
  ComputerObservationState,
  ComputerTarget,
  ComputerToolAction,
  ScreenshotCapture,
} from "./computer-tool-shared.js";
import {
  COMPUTER_REF_WIDTH,
  MODEL_OBSERVATION_MAX_ELEMENTS,
  computerTargetDetails,
} from "./computer-tool-shared.js";

type ModelObservationProjection = NonNullable<ComputerActResult["observation"]> & {
  truncatedElements?: number;
};

function projectComputerActResultMetadata(result: ComputerActResult) {
  let observation: ModelObservationProjection | undefined = result.observation
    ? { ...result.observation, ...(result.observation.base64 ? { base64: "[image]" } : {}) }
    : undefined;
  if (observation?.elements && observation.elements.length > MODEL_OBSERVATION_MAX_ELEMENTS) {
    observation = {
      ...observation,
      elements: observation.elements.slice(0, MODEL_OBSERVATION_MAX_ELEMENTS),
      truncatedElements: observation.elements.length - MODEL_OBSERVATION_MAX_ELEMENTS,
    };
  }
  const details = result.details ? { ...result.details } : undefined;
  if (
    details &&
    Array.isArray(details.elements) &&
    details.elements.length > MODEL_OBSERVATION_MAX_ELEMENTS
  ) {
    const originalLength = details.elements.length;
    details.elements = details.elements.slice(0, MODEL_OBSERVATION_MAX_ELEMENTS);
    details.truncatedElements = originalLength - MODEL_OBSERVATION_MAX_ELEMENTS;
  }
  return {
    ...result,
    ...(observation ? { observation } : {}),
    ...(details ? { details } : {}),
  };
}

export function computerActResultText(
  action: ComputerToolAction,
  result: ComputerActResult,
): string {
  return JSON.stringify({ action, ...projectComputerActResultMetadata(result) });
}

function computerFrameImageIdentity(
  content: AgentToolResult<unknown>["content"],
): string | undefined {
  const [image, duplicate] = content.filter((block) => block.type === "image");
  if (!image || duplicate) {
    return undefined;
  }
  return crypto
    .createHash("sha256")
    .update(JSON.stringify([image.mimeType, image.data]))
    .digest("hex");
}

function invalidateComputerFrame(contextEpoch: ComputerContextEpoch): boolean {
  if (contextEpoch.frameToolCallId === undefined && contextEpoch.frameImageIdentity === undefined) {
    return false;
  }
  contextEpoch.value += 1;
  delete contextEpoch.frameToolCallId;
  delete contextEpoch.frameImageIdentity;
  return true;
}

/**
 * Invalidate screenshot coordinates when the final model context no longer
 * contains the image produced by the tracked computer tool result.
 */
export function invalidateComputerFrameIfMissing(params: {
  contextEpoch: ComputerContextEpoch;
  messages: AgentMessage[];
  imagesBlocked?: boolean;
}): boolean {
  const frameToolCallId = params.contextEpoch.frameToolCallId;
  if (frameToolCallId === undefined || params.imagesBlocked) {
    return invalidateComputerFrame(params.contextEpoch);
  }

  let frameImageIdentity: string | undefined;
  for (let index = params.messages.length - 1; index >= 0; index -= 1) {
    const message = params.messages[index];
    if (
      message?.role !== "toolResult" ||
      message.toolName !== "computer" ||
      message.toolCallId !== frameToolCallId
    ) {
      continue;
    }
    frameImageIdentity = computerFrameImageIdentity(message.content);
    break;
  }

  if (
    frameImageIdentity !== undefined &&
    frameImageIdentity === params.contextEpoch.frameImageIdentity
  ) {
    return false;
  }
  return invalidateComputerFrame(params.contextEpoch);
}

/**
 * The reference frame width both the screenshot and the coordinates use.
 * Capped at the model's image sanitization limit so a persisted screenshot that
 * is replay-sanitized in a later turn is not resized underneath the coordinate
 * frame the model is still issuing `refWidth` against.
 */
export function resolveReferenceWidth(limits: { maxDimensionPx?: number }): number {
  const sanitizationLimit = limits.maxDimensionPx ?? DEFAULT_IMAGE_MAX_DIMENSION_PX;
  return Math.max(1, Math.min(COMPUTER_REF_WIDTH, sanitizationLimit));
}

async function projectComputerImage(params: {
  image?: { base64: string; mimeType: string };
  action: ComputerToolAction;
  referenceWidth: number;
  modelHasVision?: boolean;
}) {
  // Keep the delivered pixels within the replay cap so later turns cannot
  // resize the image underneath the coordinates bound to it.
  const content = await sanitizeContentBlocksImages(
    params.image && params.modelHasVision !== false
      ? [{ type: "image", data: params.image.base64, mimeType: params.image.mimeType }]
      : [],
    `computer:${params.action}`,
    { maxDimensionPx: params.referenceWidth },
  );
  const image = content.find((block) => block.type === "image");
  const dimensions = image ? readImageMetadataFromHeader(Buffer.from(image.data, "base64")) : null;
  return { content, image, dimensions };
}

export async function projectScreenshotResult(params: {
  capture: ScreenshotCapture;
  noteLines: string[];
  target: ComputerTarget;
  action: ComputerToolAction;
  referenceWidth: number;
  modelHasVision?: boolean;
}): Promise<{
  result: AgentToolResult<unknown>;
  frameId: string;
  imageIdentity?: string;
}> {
  const { capture, target } = params;
  const frameId = crypto.randomUUID();
  const { content, dimensions } = await projectComputerImage({ ...params, image: capture });
  const dims = dimensions ? `${dimensions.width}x${dimensions.height}` : "unknown size";
  const text = [
    ...params.noteLines,
    `screenshot ${dims} (screen ${target.screenIndex}, frameId ${frameId})`,
  ].join("\n");
  if (params.modelHasVision === false) {
    content.push({
      type: "text",
      text: "[model has no vision; screenshot omitted — use a vision-capable model for computer use]",
    });
  }
  const result = {
    content: [{ type: "text" as const, text }, ...content],
    details: {
      ...computerTargetDetails(target),
      action: params.action,
      width: dimensions?.width,
      height: dimensions?.height,
      screenIndex: target.screenIndex,
      frameId,
      refWidth: params.referenceWidth,
      media: { outbound: false },
    },
  };
  return { result, frameId, imageIdentity: computerFrameImageIdentity(result.content) };
}

export async function projectComputerActResult(params: {
  result: ComputerActResult;
  precedingAction?: { action: ComputerToolAction; result: ComputerActResult };
  target: ComputerTarget;
  action: ComputerToolAction;
  referenceWidth: number;
  modelHasVision?: boolean;
}): Promise<{
  result: AgentToolResult<unknown>;
  imageCoordinates?: ComputerObservationState["imageCoordinates"];
}> {
  const observation = params.result.observation;
  // Observation images have no context-presence tracking, so they must never be deduplicated.
  const { content, image, dimensions } = await projectComputerImage({
    ...params,
    image: observation?.base64
      ? {
          base64: observation.base64,
          mimeType: imageMimeFromFormat(observation.format ?? "png") ?? "image/png",
        }
      : undefined,
  });
  // Pixels belong only in image content. Metadata describes the delivered bitmap;
  // accessibility bounds retain the provider's coordinate space.
  const result = projectComputerActResultMetadata(params.result);
  if (result.observation && dimensions) {
    Object.assign(result.observation, dimensions, {
      format: image?.mimeType === "image/jpeg" ? "jpeg" : "png",
    });
  }
  let imageCoordinates: ComputerObservationState["imageCoordinates"];
  if (params.result.details?.coordinateSpace === "image-pixels") {
    imageCoordinates =
      dimensions && observation?.width && observation.height
        ? {
            kind: "available",
            scaleX: observation.width / dimensions.width,
            scaleY: observation.height / dimensions.height,
          }
        : { kind: "unavailable" };
  }
  return {
    result: {
      content: [
        ...(params.precedingAction
          ? [
              {
                type: "text" as const,
                text: computerActResultText(
                  params.precedingAction.action,
                  params.precedingAction.result,
                ),
              },
            ]
          : []),
        { type: "text", text: JSON.stringify({ action: params.action, ...result }) },
        ...content,
      ],
      details: {
        ...computerTargetDetails(params.target),
        action: params.precedingAction?.action ?? params.action,
        screenIndex: params.target.screenIndex,
        // Keep mutation evidence separate from the read's coordinate space and other metadata.
        result: params.precedingAction
          ? projectComputerActResultMetadata(params.precedingAction.result)
          : result,
        ...(params.precedingAction ? { followUpObservation: result } : {}),
        media: { outbound: false },
      },
    },
    imageCoordinates,
  };
}