File size: 23,994 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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 | import crypto from "node:crypto";
import { imageMimeFromFormat } from "@openclaw/media-core/mime";
import { isRecord } from "@openclaw/normalization-core/record-coerce";
import { formatErrorMessage } from "../../infra/errors.js";
import type {
ComputerActParams,
ComputerActResult,
ComputerUseCapabilityDescriptor,
ComputerUseV2ActionName,
ScreenSnapshotParams,
} from "../../plugins/computer-use-contract.js";
import {
COMPUTER_CONTRACT_MISMATCH,
COMPUTER_STALE_OBSERVATION,
parseComputerActResult,
parseScreenSnapshotResult,
} from "../../plugins/computer-use-contract.js";
import {
NOT_COMPUTER_CAPABLE_HINT,
resolveComputerBinding,
type ComputerBinding,
} from "./computer-tool-bindings.js";
import type { GatewayComputerStatus } from "./computer-tool-gateway.js";
import { computerActionNeedsFrame, validateCapabilityBoundInput } from "./computer-tool-request.js";
import type {
ComputerContextEpoch,
ComputerFrame,
ComputerObservationState,
ComputerTarget,
ComputerToolAction,
ComputerToolTransport,
ResolvedComputerTarget,
ScreenshotCapture,
} from "./computer-tool-shared.js";
import {
COMPUTER_ACT_COMMAND,
computerHostKey,
SCREENSHOT_QUALITY,
SCREEN_SNAPSHOT_COMMAND,
} from "./computer-tool-shared.js";
import type { GatewayCallOptions } from "./gateway.js";
type ComputerState =
| { kind: "unbound" }
| { kind: "target"; target: ComputerTarget }
| ({ kind: "frame" } & ComputerFrame);
const DANGEROUS_DENY_HINT = "blocked by gateway.nodes.commands.deny";
const PLATFORM_ALLOWLIST_HINT = "is not in the allowlist for platform";
const BUTTON_NOT_HELD_HINT = "left button is not held by computer control";
const DEFINITIVE_NODE_COMMAND_REASONS = new Set([
"command required",
"command not allowlisted",
"command not declared by node",
"node did not declare commands",
]);
function parseComputerActPayload(value: unknown): ComputerActResult {
if (typeof value !== "string") {
return parseComputerActResult(value);
}
try {
return parseComputerActResult(JSON.parse(value));
} catch (error) {
if (error instanceof Error && error.message.startsWith(COMPUTER_CONTRACT_MISMATCH)) {
throw error;
}
throw new Error(`${COMPUTER_CONTRACT_MISMATCH}: computer.act returned invalid JSON`, {
cause: error,
});
}
}
function computerActIdempotencyKey(params: {
scope?: string;
toolCallId: string;
purpose?: "follow-up-observation";
}): string {
const stableScope = params.scope?.trim();
const stableCallId = params.toolCallId.trim();
if (!stableScope || !stableCallId) {
// A call id is only unique inside its model response. Without a stable run
// scope and provider/fallback id, avoid collapsing unrelated actions.
return crypto.randomUUID();
}
const parts = [stableScope, stableCallId, COMPUTER_ACT_COMMAND];
if (params.purpose) {
parts.push(params.purpose);
}
const digest = crypto.createHash("sha256").update(JSON.stringify(parts)).digest("hex");
// The automatic read shares a tool-call id with input, but must never replay its result.
if (params.purpose) {
return `computer.observation:v1:${digest}`;
}
// `v1` versions this key's composition (scope + call id + command), not the
// `computer.act` wire contract. Changing what goes into the digest needs a
// new prefix so in-flight keys from an older node cannot collide.
return `computer.act:v1:${digest}`;
}
function gatewayRequestDetails(err: unknown): Record<string, unknown> | undefined {
if (!(err instanceof Error) || err.name !== "GatewayClientRequestError") {
return undefined;
}
const details = (err as Error & { details?: unknown }).details;
return isRecord(details) ? details : undefined;
}
function withComputerEnablementHint(err: unknown): Error {
const message = formatErrorMessage(err);
const reason = gatewayRequestDetails(err)?.reason;
if (message.includes(DANGEROUS_DENY_HINT)) {
return new Error(
`${message} — remove ${COMPUTER_ACT_COMMAND} from gateway.nodes.commands.deny, then retry.`,
{ cause: err },
);
}
if (
reason === "command not allowlisted" ||
reason === "command not declared by node" ||
reason === "node did not declare commands" ||
message.includes(PLATFORM_ALLOWLIST_HINT)
) {
return new Error(`${message} — ${NOT_COMPUTER_CAPABLE_HINT}, then retry.`, { cause: err });
}
return err instanceof Error ? err : new Error(message);
}
function isDefinitiveComputerActRejection(err: unknown): boolean {
const details = gatewayRequestDetails(err);
return (
details?.nodeCommandDispatched === false ||
(typeof details?.reason === "string" && DEFINITIVE_NODE_COMMAND_REASONS.has(details.reason))
);
}
function isButtonAlreadyReleasedError(err: unknown): boolean {
return (
err instanceof Error &&
err.name === "GatewayClientRequestError" &&
err.message.includes(BUTTON_NOT_HELD_HINT)
);
}
export class ComputerToolSession {
private selectedCapabilities: ComputerUseCapabilityDescriptor | undefined;
private selectedCapabilityTargetKey: string | undefined;
private observationState: ComputerObservationState | undefined;
private computerState: ComputerState = { kind: "unbound" };
private heldButtonTarget: ComputerTarget | undefined;
private readonly executionTargets = new Map<string, ComputerBinding>();
private readonly retiredGatewayBindings = new Set<ComputerBinding>();
private disposePromise: Promise<void> | undefined;
constructor(
private readonly options: {
executionId: string;
idempotencyScope?: string;
contextEpoch?: ComputerContextEpoch;
transport?: ComputerToolTransport;
gatewayStatus?: GatewayComputerStatus;
availableActions: (
actions: readonly ComputerUseV2ActionName[],
) => readonly ComputerUseV2ActionName[];
defaultActions: readonly ComputerUseV2ActionName[];
onCapabilitiesChanged: (capabilities?: ComputerUseCapabilityDescriptor) => void;
registerRunCleanup?: (cleanup: (reason: string) => Promise<void>) => void;
getOperationQueue: () => Promise<unknown>;
},
) {
options.registerRunCleanup?.((reason) => this.dispose(reason));
}
private assertOpen(): void {
if (this.disposePromise) {
throw new Error("computer: execution is closed");
}
}
private bindCapabilities(binding: ComputerBinding, refresh = false): void {
const next = binding.capabilities;
const targetKey = computerHostKey(binding.host);
const changed =
this.selectedCapabilityTargetKey !== targetKey ||
this.selectedCapabilities?.provider.generation !== next?.provider.generation;
this.selectedCapabilityTargetKey = targetKey;
this.selectedCapabilities = next;
if (changed || refresh) {
this.options.onCapabilitiesChanged(next);
}
if (changed) {
this.observationState = undefined;
}
}
private setComputerState(next: ComputerState): void {
this.computerState = next;
if (!this.options.contextEpoch) {
return;
}
if (next.kind !== "frame") {
delete this.options.contextEpoch.frameToolCallId;
delete this.options.contextEpoch.frameImageIdentity;
}
}
setTarget(target: ComputerTarget): void {
this.setComputerState({ kind: "target", target });
}
private prepareScreenshotTarget(target: ComputerTarget): void {
const frame = this.computerState;
const contextEpoch = this.options.contextEpoch;
// Retain the visible frame only until replacement pixels are verified; failures clear it.
if (
contextEpoch?.frameImageIdentity &&
frame.kind === "frame" &&
computerHostKey(frame.target) === computerHostKey(target) &&
frame.target.screenIndex === target.screenIndex &&
frame.contextEpoch === contextEpoch.value
) {
return;
}
this.setTarget(target);
}
refreshUnchangedFrame(params: {
target: ComputerTarget;
capture: ScreenshotCapture;
imageIdentity?: string;
modelHasVision?: boolean;
}): ComputerFrame | undefined {
const frame = this.computerState;
const contextEpoch = this.options.contextEpoch;
// Without context tracking, the earlier screenshot may already have been pruned.
if (
params.modelHasVision === false ||
!contextEpoch?.frameImageIdentity ||
contextEpoch.frameImageIdentity !== params.imageIdentity ||
frame.kind !== "frame" ||
computerHostKey(frame.target) !== computerHostKey(params.target) ||
frame.target.screenIndex !== params.target.screenIndex ||
frame.contextEpoch !== contextEpoch.value
) {
return undefined;
}
// Keep the model's original image/frame binding while refreshing the node's capture token.
frame.displayFrameId = params.capture.displayFrameId;
return frame;
}
bindDeliveredFrame(params: {
resolved: ResolvedComputerTarget;
capture: ScreenshotCapture;
frameId: string;
toolCallId: string;
imageIdentity?: string;
modelHasVision?: boolean;
}): void {
if (params.modelHasVision === false || !params.imageIdentity) {
this.setTarget(params.resolved.target);
return;
}
this.computerState = {
kind: "frame",
target: params.resolved.target,
id: params.frameId,
displayFrameId: params.capture.displayFrameId,
contextEpoch: this.options.contextEpoch?.value ?? 0,
};
if (this.options.contextEpoch) {
this.options.contextEpoch.frameToolCallId = params.toolCallId;
this.options.contextEpoch.frameImageIdentity = params.imageIdentity;
}
}
recordObservation(
resolved: ResolvedComputerTarget,
result: ComputerActResult,
imageCoordinates?: ComputerObservationState["imageCoordinates"],
): void {
const observationId = result.observation?.observationId;
if (observationId && resolved.capabilities) {
this.observationState = {
targetKey: computerHostKey(resolved.target),
providerGeneration: resolved.capabilities.provider.generation,
observationId,
imageCoordinates,
};
}
}
async resolveTarget(params: {
action: ComputerToolAction;
input: Record<string, unknown>;
gatewayOpts: GatewayCallOptions;
signal?: AbortSignal;
}): Promise<ResolvedComputerTarget> {
this.assertOpen();
const explicitHost = params.input.target;
if (explicitHost !== undefined && explicitHost !== "gateway" && explicitHost !== "node") {
throw new Error("computer target must be gateway or node");
}
const explicitNode = typeof params.input.node === "string" ? params.input.node : undefined;
if (explicitHost === "gateway" && explicitNode !== undefined) {
throw new Error("computer target=gateway does not accept a node selector");
}
if (
this.options.transport &&
(explicitHost !== undefined ||
params.gatewayOpts.gatewayUrl ||
params.gatewayOpts.gatewayToken)
) {
throw new Error("Computer control is bound to this session's desktop");
}
const explicitScreenIndex = (() => {
if (params.input.screenIndex === undefined) {
return undefined;
}
if (
typeof params.input.screenIndex !== "number" ||
!Number.isInteger(params.input.screenIndex) ||
params.input.screenIndex < 0
) {
throw new Error("screenIndex must be a non-negative integer");
}
return params.input.screenIndex;
})();
const needsFrame = computerActionNeedsFrame(params.action, params.input);
const priorTarget =
this.computerState.kind === "unbound" ? undefined : this.computerState.target;
const implicitTarget = this.heldButtonTarget ?? priorTarget;
const reuseTarget =
explicitNode === undefined &&
implicitTarget &&
(explicitHost === undefined || explicitHost === implicitTarget.host);
const explicitGateway =
params.gatewayOpts.gatewayUrl !== undefined || params.gatewayOpts.gatewayToken !== undefined;
const priorBinding = priorTarget
? this.executionTargets.get(computerHostKey(priorTarget))
: undefined;
const selectionGatewayOpts =
explicitNode !== undefined && !explicitGateway && priorBinding?.host.host === "node"
? {
...priorBinding.gatewayOpts,
timeoutMs: params.gatewayOpts.timeoutMs ?? priorBinding.gatewayOpts.timeoutMs,
}
: params.gatewayOpts;
const resolvedBinding = reuseTarget
? this.executionTargets.get(computerHostKey(implicitTarget))!
: await resolveComputerBinding({
executionId: this.options.executionId,
sessionTransport: this.options.transport,
gatewayStatus: this.options.gatewayStatus,
target: explicitHost,
node: explicitNode,
gatewayOpts: selectionGatewayOpts,
signal: params.signal,
});
this.assertOpen();
const targetKey = computerHostKey(resolvedBinding.host);
const existingBinding = this.executionTargets.get(targetKey);
const refreshNode =
explicitNode !== undefined && !this.options.transport && resolvedBinding.host.host === "node";
const nextGatewayOpts = refreshNode ? resolvedBinding.gatewayOpts : params.gatewayOpts;
if (
existingBinding &&
(explicitGateway || refreshNode) &&
(nextGatewayOpts.gatewayUrl !== existingBinding.gatewayOpts.gatewayUrl ||
nextGatewayOpts.gatewayToken !== existingBinding.gatewayOpts.gatewayToken)
) {
throw new Error(
"Computer target is bound to its Gateway connection; start a new execution to change it",
);
}
const binding = refreshNode ? resolvedBinding : (existingBinding ?? resolvedBinding);
const capabilities = binding.capabilities;
this.bindCapabilities(binding, refreshNode);
this.executionTargets.set(targetKey, binding);
const advertisedActions = this.options.availableActions(
capabilities?.actions ?? this.options.defaultActions,
);
if (!advertisedActions.includes(params.action)) {
throw new Error(
`${COMPUTER_CONTRACT_MISMATCH}: computer ${targetKey} does not advertise action ${params.action}`,
);
}
validateCapabilityBoundInput({
action: params.action,
input: params.input,
targetKey,
capabilities,
observationState: this.observationState,
});
if (this.heldButtonTarget && targetKey !== computerHostKey(this.heldButtonTarget)) {
const heldHost =
this.heldButtonTarget.host === "gateway"
? "Gateway"
: `node ${this.heldButtonTarget.nodeId}`;
throw new Error(
`computer: left button may still be held on ${heldHost}; ` +
"release it before targeting another computer",
);
}
if (
this.heldButtonTarget &&
explicitScreenIndex !== undefined &&
explicitScreenIndex !== this.heldButtonTarget.screenIndex
) {
throw new Error(
`computer: left button may still be held on screen ${this.heldButtonTarget.screenIndex}; ` +
"release it before targeting another screen",
);
}
const targetForHost =
priorTarget && computerHostKey(priorTarget) === targetKey ? priorTarget : undefined;
const frame =
this.computerState.kind === "frame" &&
computerHostKey(this.computerState.target) === targetKey &&
this.computerState.contextEpoch === (this.options.contextEpoch?.value ?? 0)
? this.computerState
: undefined;
if (needsFrame && !frame) {
throw new Error(
"computer: no screenshot of this computer has been taken yet, so there is no display frame to " +
"target. Take a `screenshot` first (of this computer) before issuing coordinate actions.",
);
}
if (
needsFrame &&
explicitScreenIndex !== undefined &&
explicitScreenIndex !== frame?.target.screenIndex
) {
throw new Error("computer: screenIndex does not match the most recent screenshot frame");
}
if (needsFrame && params.input.frameId !== frame?.id) {
throw new Error(
"computer: frameId does not match the most recent screenshot result; take a new screenshot",
);
}
const screenIndex =
explicitScreenIndex ??
frame?.target.screenIndex ??
this.heldButtonTarget?.screenIndex ??
targetForHost?.screenIndex ??
0;
return { target: { ...binding.host, screenIndex }, frame, capabilities };
}
async captureScreenshot(
resolved: ResolvedComputerTarget,
refWidth: number,
signal?: AbortSignal,
): Promise<ScreenshotCapture> {
this.assertOpen();
this.prepareScreenshotTarget(resolved.target);
const commandParams: ScreenSnapshotParams = {
executionId: this.options.executionId,
screenIndex: resolved.target.screenIndex,
maxWidth: refWidth,
quality: SCREENSHOT_QUALITY,
format: "jpeg",
};
try {
const capture = (binding: ComputerBinding) =>
binding.invoke({
command: SCREEN_SNAPSHOT_COMMAND,
commandParams,
signal,
});
const targetKey = computerHostKey(resolved.target);
const binding = this.executionTargets.get(targetKey)!;
let payload: unknown;
try {
payload = await capture(binding);
} catch (error) {
if (
binding.host.host !== "gateway" ||
!(error instanceof Error) ||
!/^(?:Error: )?COMPUTER_STALE_OBSERVATION:/.test(error.message)
) {
throw error;
}
// Only a fresh screen read can reopen the same Gateway after native retirement.
this.setTarget(resolved.target);
this.observationState = undefined;
this.assertOpen();
signal?.throwIfAborted();
const refreshed = await resolveComputerBinding({
executionId: this.options.executionId,
target: "gateway",
gatewayOpts: binding.gatewayOpts,
signal,
});
this.retiredGatewayBindings.add(binding);
this.executionTargets.set(targetKey, refreshed);
this.assertOpen();
signal?.throwIfAborted();
this.bindCapabilities(refreshed);
if (
binding.capabilities?.provider.generation !== refreshed.capabilities?.provider.generation
) {
this.heldButtonTarget = undefined;
}
payload = await capture(refreshed);
}
const parsed = parseScreenSnapshotResult(payload);
if (!parsed.displayFrameId) {
throw new Error(
"screen.snapshot response missing displayFrameId; update the computer provider before computer use",
);
}
return {
base64: parsed.base64,
displayFrameId: parsed.displayFrameId,
mimeType: imageMimeFromFormat(parsed.format) ?? "image/jpeg",
width: parsed.width,
height: parsed.height,
};
} catch (error) {
this.setTarget(resolved.target);
throw error;
}
}
async invokeComputerAct(params: {
resolved: ResolvedComputerTarget;
wireParams: ComputerActParams;
toolCallId: string;
purpose?: "follow-up-observation";
signal?: AbortSignal;
}): Promise<ComputerActResult> {
this.assertOpen();
const durationMs =
"durationMs" in params.wireParams && typeof params.wireParams.durationMs === "number"
? params.wireParams.durationMs
: undefined;
const invokeTimeoutMs = durationMs ? durationMs + 10_000 : undefined;
params.signal?.throwIfAborted();
const commandParams: Record<string, unknown> = { ...params.wireParams };
const imageCoordinates =
commandParams.windowRef &&
commandParams.observationId === this.observationState?.observationId
? this.observationState?.imageCoordinates
: undefined;
if (imageCoordinates) {
// Map only the image bound to this validated observation. Browser CSS requests
// have no windowRef; native coordinate spaces and element refs remain unchanged.
for (const [x, y] of [
["x", "y"],
["fromX", "fromY"],
["x1", "y1"],
["x2", "y2"],
] as const) {
if (typeof commandParams[x] === "number" && typeof commandParams[y] === "number") {
if (imageCoordinates.kind === "unavailable") {
throw new Error(
`${COMPUTER_STALE_OBSERVATION}: take a fresh image observation and retry`,
);
}
commandParams[x] *= imageCoordinates.scaleX;
commandParams[y] *= imageCoordinates.scaleY;
}
}
}
this.prepareScreenshotTarget(params.resolved.target);
if (params.purpose === "follow-up-observation") {
// Input may have changed the window. A failed refresh must not leave its old refs usable.
this.observationState = undefined;
}
if (params.wireParams.action === "left_mouse_down") {
this.heldButtonTarget = params.resolved.target;
}
let actResult: ComputerActResult;
try {
actResult = parseComputerActPayload(
await this.executionTargets.get(computerHostKey(params.resolved.target))!.invoke({
command: COMPUTER_ACT_COMMAND,
commandParams,
timeoutMs: invokeTimeoutMs,
idempotencyKey: computerActIdempotencyKey({
scope: this.options.idempotencyScope,
toolCallId: params.toolCallId,
purpose: params.purpose,
}),
signal: params.signal,
}),
);
} catch (err) {
if (params.wireParams.action === "left_mouse_down" && isDefinitiveComputerActRejection(err)) {
this.heldButtonTarget = undefined;
}
if (params.wireParams.action === "left_mouse_up" && isButtonAlreadyReleasedError(err)) {
this.heldButtonTarget = undefined;
actResult = { ok: true };
} else {
this.setTarget(params.resolved.target);
throw withComputerEnablementHint(err);
}
}
if (params.wireParams.action === "left_mouse_up") {
this.heldButtonTarget = undefined;
}
return actResult;
}
async dispose(reason: string): Promise<void> {
if (this.disposePromise) {
return await this.disposePromise;
}
this.disposePromise = this.options
.getOperationQueue()
.catch(() => {})
.then(async () => {
const targets = [
...this.executionTargets.entries(),
...[...this.retiredGatewayBindings].map((binding): [string, ComputerBinding] => [
computerHostKey(binding.host),
binding,
]),
];
this.executionTargets.clear();
this.retiredGatewayBindings.clear();
const results = await Promise.allSettled(
targets.map(async ([targetKey, binding]) => {
await binding.invoke({
command: COMPUTER_ACT_COMMAND,
commandParams: {
action: "__close_execution",
executionId: this.options.executionId,
reason,
},
idempotencyKey: `computer.close:${this.options.executionId}:${targetKey}`,
});
}),
);
// Ordinary paired nodes can disconnect during best-effort cleanup.
// A bound session owner must observe cleanup failure before acknowledging its turn.
if (
this.options.transport ||
targets.some(([, binding]) => binding.host.host === "gateway")
) {
const failures = results.flatMap((result, index) =>
result.status === "rejected" &&
(this.options.transport || targets[index]?.[1].host.host === "gateway")
? [result.reason]
: [],
);
if (failures.length > 0) {
throw new AggregateError(failures, "computer: session desktop cleanup failed");
}
}
});
return await this.disposePromise;
}
}
|