mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 06:36:34 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e58f712bc2 | ||
|
|
a0a3690e79 |
@@ -19,6 +19,9 @@ import { isolatePaseoHome } from "../../../../test-utils/isolated-paseo-home.js"
|
||||
|
||||
isolatePaseoHome();
|
||||
|
||||
const ONE_PIXEL_PNG =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=";
|
||||
|
||||
const TURN_LIFECYCLE_EVENTS = new Set<AgentStreamEvent["type"]>([
|
||||
"turn_started",
|
||||
"turn_completed",
|
||||
@@ -1329,6 +1332,82 @@ describe("OMP agent client and session", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("shows a live OMP browser screenshot after its completed tool call", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
onTestFinished(() => omp.close());
|
||||
omp.emit({
|
||||
type: "tool_execution_start",
|
||||
toolCallId: "shot-1",
|
||||
toolName: "browser_screenshot",
|
||||
args: {},
|
||||
});
|
||||
omp.emit(
|
||||
OmpRuntimeEventSchema.parse({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "shot-1",
|
||||
toolName: "browser_screenshot",
|
||||
result: {
|
||||
content: [
|
||||
{ type: "text", text: "Captured browser screenshot (1x1)." },
|
||||
{
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: ONE_PIXEL_PNG,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect
|
||||
.poll(() => omp.timeline().slice(-2), { timeout: 500 })
|
||||
.toMatchObject([
|
||||
{
|
||||
type: "tool_call",
|
||||
status: "completed",
|
||||
detail: {
|
||||
output: {
|
||||
content: [
|
||||
{ type: "text", text: "Captured browser screenshot (1x1)." },
|
||||
{ type: "text", text: "[image]" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ type: "assistant_message", text: expect.stringMatching(/!\[.*\]\(.*\.png\)/) },
|
||||
]);
|
||||
});
|
||||
|
||||
test("publishes the queued OMP browser screenshot and reply before close returns", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
onTestFinished(() => omp.close());
|
||||
await omp.startTurn("capture the page");
|
||||
omp.emit({ type: "agent_start" });
|
||||
omp.emit(
|
||||
OmpRuntimeEventSchema.parse({
|
||||
type: "tool_execution_end",
|
||||
toolCallId: "shot-1",
|
||||
toolName: "browser_screenshot",
|
||||
result: {
|
||||
content: [{ type: "image", mimeType: "image/png", data: ONE_PIXEL_PNG }],
|
||||
},
|
||||
}),
|
||||
);
|
||||
omp.runtime().streamAssistantText("Here is the captured page.");
|
||||
omp.runtime().finishTurn();
|
||||
|
||||
const closing = omp.close();
|
||||
omp.runtime().acceptCustomMessage("Output after shutdown started");
|
||||
await closing;
|
||||
|
||||
expect(omp.timeline().slice(-3)).toMatchObject([
|
||||
{ type: "tool_call", status: "completed" },
|
||||
{ type: "assistant_message", text: expect.stringMatching(/!\[.*\]\(.*\.png\)/) },
|
||||
{ type: "assistant_message", text: "Here is the captured page." },
|
||||
]);
|
||||
});
|
||||
|
||||
test("preserves tool intent across live updates and completion", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start();
|
||||
|
||||
@@ -121,6 +121,11 @@ import { readOmpHistoryTodoState, streamOmpHistory } from "./history.js";
|
||||
import { mapOmpTodoReminderEvent, mapOmpTodoState, mapOmpTodoToolResult } from "./todo-mapper.js";
|
||||
import { mapOmpRuntimeEventToTimelineItem } from "./event-mapper.js";
|
||||
import { mapOmpAdvisorMessageToToolCall } from "./advisor-message.js";
|
||||
import {
|
||||
renderOmpToolResultImages,
|
||||
resolveOmpBlobDirectory,
|
||||
splitOmpToolResultImages,
|
||||
} from "./tool-result-images.js";
|
||||
import { handleOmpHostToolRuntimeEvent, OmpHostToolRouter } from "./host-tools.js";
|
||||
import { OmpSubagentIndex } from "./subagent-index.js";
|
||||
import { OmpQuestionUi } from "./question-ui.js";
|
||||
@@ -654,6 +659,7 @@ class OmpHistorySession implements AgentSession {
|
||||
private readonly sessionFile: string,
|
||||
provider: AgentProvider,
|
||||
private readonly bridgedTools: ReadonlyMap<string, OmpBridgedToolIdentity>,
|
||||
private readonly blobDirectory: string,
|
||||
) {
|
||||
this.provider = provider;
|
||||
}
|
||||
@@ -679,6 +685,7 @@ class OmpHistorySession implements AgentSession {
|
||||
sessionFile: this.sessionFile,
|
||||
provider: this.provider,
|
||||
bridgedTools: this.bridgedTools,
|
||||
blobDirectory: this.blobDirectory,
|
||||
});
|
||||
const todo = await readOmpHistoryTodoState(this.sessionFile);
|
||||
if (todo) yield { type: "timeline", provider: this.provider, item: todo };
|
||||
@@ -728,6 +735,7 @@ export class OmpAgentSession implements AgentSession {
|
||||
readonly capabilities: AgentCapabilityFlags = withOmpCapabilities();
|
||||
|
||||
private readonly subscribers = new Set<(event: AgentStreamEvent) => void>();
|
||||
private pendingOutput: Promise<void> | null = null;
|
||||
private readonly activeToolCalls = new Map<string, OmpTrackedToolCall>();
|
||||
private readonly pendingExtensionUiRequests = new Map<string, AgentPermissionRequest>();
|
||||
private readonly questionUi = new OmpQuestionUi();
|
||||
@@ -1092,6 +1100,7 @@ export class OmpAgentSession implements AgentSession {
|
||||
runtimeSession: this.runtimeSession,
|
||||
provider: this.provider,
|
||||
bridgedTools: this.hostTools?.bridge?.toolIdentities(),
|
||||
blobDirectory: resolveOmpBlobDirectory(this.runtimeSession.environment),
|
||||
});
|
||||
this.lastReply ??= replay.lastReply;
|
||||
const stats = await this.runtimeSession.getSessionStats().catch((error: unknown) => {
|
||||
@@ -1402,6 +1411,8 @@ export class OmpAgentSession implements AgentSession {
|
||||
try {
|
||||
await this.runtimeSession.close();
|
||||
} finally {
|
||||
// The manager can drain only events that the provider has published.
|
||||
await this.pendingOutput;
|
||||
await this.hostTools?.close();
|
||||
this.clearOmpSessionState();
|
||||
}
|
||||
@@ -1538,11 +1549,34 @@ export class OmpAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
private emit(event: AgentStreamEvent): void {
|
||||
if (this.pendingOutput) {
|
||||
this.emitAsync(async () => [event]);
|
||||
return;
|
||||
}
|
||||
this.publish(event);
|
||||
}
|
||||
|
||||
private publish(event: AgentStreamEvent): void {
|
||||
for (const subscriber of this.subscribers) {
|
||||
subscriber(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep later timeline events behind the image while it is written to disk.
|
||||
private emitAsync(render: () => Promise<AgentStreamEvent[]>): void {
|
||||
const pending = (this.pendingOutput ?? Promise.resolve())
|
||||
.then(render)
|
||||
.then((events) => {
|
||||
for (const event of events) this.publish(event);
|
||||
return undefined;
|
||||
})
|
||||
.catch((err: unknown) => this.logger.error({ err }, "OMP output rendering failed"));
|
||||
this.pendingOutput = pending;
|
||||
void pending.finally(() => {
|
||||
if (this.pendingOutput === pending) this.pendingOutput = null;
|
||||
});
|
||||
}
|
||||
|
||||
private currentTurnIdForEvent(): string | undefined {
|
||||
return this.activeTurnId ?? undefined;
|
||||
}
|
||||
@@ -1975,9 +2009,8 @@ export class OmpAgentSession implements AgentSession {
|
||||
}
|
||||
if (event.type === "subagent_event") {
|
||||
const payload = (event as Extract<OmpRuntimeEvent, { type: "subagent_event" }>).payload;
|
||||
for (const mapped of this.subagentIndex.handleEvent(this.runtimeSession, payload)) {
|
||||
this.emit(mapped);
|
||||
}
|
||||
const events = this.subagentIndex.handleEvent(this.runtimeSession, payload);
|
||||
this.emitAsync(() => events);
|
||||
return true;
|
||||
}
|
||||
if (event.type === "todo_reminder") {
|
||||
@@ -2206,7 +2239,9 @@ export class OmpAgentSession implements AgentSession {
|
||||
return;
|
||||
}
|
||||
|
||||
const partialResult = parseToolResult(event.partialResult);
|
||||
const { result: partialResult } = splitOmpToolResultImages(
|
||||
parseToolResult(event.partialResult),
|
||||
);
|
||||
this.emitToolCallEvent(event.toolCallId, toolCall, "running", partialResult, null);
|
||||
return;
|
||||
}
|
||||
@@ -2237,11 +2272,14 @@ export class OmpAgentSession implements AgentSession {
|
||||
|
||||
this.questionUi.finish(event.toolName);
|
||||
|
||||
const result = parseToolResult(event.result);
|
||||
const { images, result } = splitOmpToolResultImages(parseToolResult(event.result));
|
||||
const failed = isOmpToolFailure(toolCall, result, Boolean(event.isError));
|
||||
const error = failed ? toolFailureMessage(result) : null;
|
||||
const status = failed ? "failed" : "completed";
|
||||
this.emitToolCallEvent(event.toolCallId, toolCall, status, result, error);
|
||||
if (images.length > 0) {
|
||||
this.emitAsync(() => renderOmpToolResultImages(images, this.provider, { turnId }));
|
||||
}
|
||||
if (event.toolName === "task") {
|
||||
this.subagentCardTracker.delete(event.toolCallId);
|
||||
}
|
||||
@@ -2768,6 +2806,11 @@ export class OmpAgentClient implements AgentClient {
|
||||
sessionFile,
|
||||
this.provider,
|
||||
persistenceMetadata.bridgedTools,
|
||||
resolveOmpBlobDirectory({
|
||||
...process.env,
|
||||
...this.runtimeSettings?.env,
|
||||
...launchContext?.env,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { isolatePaseoHome } from "../../../../test-utils/isolated-paseo-home.js";
|
||||
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
|
||||
import { streamOmpCoreHistory, type OmpCapturedUserMessageEntry } from "./message-history.js";
|
||||
import type { OmpAgentMessage } from "./rpc-types.js";
|
||||
@@ -11,6 +13,8 @@ import { FakeOmp } from "./test-utils/fake-omp.js";
|
||||
import { OMP_HISTORY_MAPPER_HOOKS } from "./history-hooks.js";
|
||||
import { readActiveOmpEntryChain, readOmpHistoryTodoState, streamOmpHistory } from "./history.js";
|
||||
|
||||
isolatePaseoHome();
|
||||
|
||||
async function collectHistory(
|
||||
messages: OmpAgentMessage[],
|
||||
userEntries: OmpCapturedUserMessageEntry[] = [],
|
||||
@@ -153,6 +157,87 @@ describe("OMP history mapper", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("replays an OMP browser screenshot after its completed tool call", async () => {
|
||||
const events = await collectHistory([
|
||||
{
|
||||
role: "assistant",
|
||||
content: [{ type: "toolCall", id: "shot-1", name: "browser_screenshot", arguments: {} }],
|
||||
},
|
||||
{
|
||||
role: "toolResult",
|
||||
toolCallId: "shot-1",
|
||||
toolName: "browser_screenshot",
|
||||
content: [
|
||||
{ type: "text", text: "Captured browser screenshot (1x1)." },
|
||||
{
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=",
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(events.map((event) => event.item)).toMatchObject([
|
||||
{ type: "tool_call", status: "running" },
|
||||
{ type: "tool_call", status: "completed" },
|
||||
{ type: "assistant_message", text: expect.stringMatching(/!\[.*\]\(.*\.png\)/) },
|
||||
]);
|
||||
});
|
||||
|
||||
test("replays a browser screenshot stored in the OMP blob directory", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "omp-screenshot-history-"));
|
||||
const sessionFile = join(directory, "session.jsonl");
|
||||
const png = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
const hash = createHash("sha256").update(png).digest("hex");
|
||||
try {
|
||||
await writeFile(join(directory, hash), png);
|
||||
await writeFile(
|
||||
sessionFile,
|
||||
[
|
||||
{ type: "session", id: "session-1" },
|
||||
{
|
||||
type: "message",
|
||||
id: "capture",
|
||||
parentId: null,
|
||||
message: {
|
||||
role: "toolResult",
|
||||
toolCallId: "shot-1",
|
||||
toolName: "browser_screenshot",
|
||||
content: [
|
||||
{ type: "text", text: "Captured browser screenshot (1x1)." },
|
||||
{ type: "image", data: `blob:sha256:${hash}`, mimeType: "image/png" },
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
.map((row) => JSON.stringify(row))
|
||||
.join("\n") + "\n",
|
||||
);
|
||||
const events: AgentStreamEvent[] = [];
|
||||
for await (const event of streamOmpHistory({
|
||||
provider: "omp",
|
||||
sessionFile,
|
||||
blobDirectory: directory,
|
||||
})) {
|
||||
events.push(event);
|
||||
}
|
||||
expect(events.map((event) => event.item)).toMatchObject([
|
||||
{ type: "tool_call", status: "completed" },
|
||||
{ type: "assistant_message", text: expect.stringContaining(`${hash}.png`) },
|
||||
]);
|
||||
const item = events[1]?.item;
|
||||
if (item?.type !== "assistant_message") throw new Error("Missing screenshot");
|
||||
const imagePath = item.text.match(/\(([^()]+)\)/)?.[1];
|
||||
if (!imagePath) throw new Error("Missing screenshot URL");
|
||||
expect(await readFile(new URL(imagePath))).toEqual(png);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("replays a Paseo browser tool result whose details error is an object", async () => {
|
||||
const events = await collectHistory([
|
||||
{
|
||||
|
||||
@@ -85,6 +85,7 @@ export async function* streamOmpHistory(input: {
|
||||
provider: AgentProvider;
|
||||
bridgedTools?: ReadonlyMap<string, OmpBridgedToolIdentity>;
|
||||
visitedSessionFiles?: Set<string>;
|
||||
blobDirectory?: string;
|
||||
}): AsyncGenerator<AgentStreamEvent, OmpHistoryReplay> {
|
||||
const replay: OmpHistoryReplay = { lastReply: null };
|
||||
if (!input.sessionFile) {
|
||||
@@ -130,6 +131,7 @@ export async function* streamOmpHistory(input: {
|
||||
userEntries,
|
||||
OMP_HISTORY_MAPPER_HOOKS,
|
||||
input.bridgedTools,
|
||||
input.blobDirectory,
|
||||
);
|
||||
const turns = ompReplayedTurns();
|
||||
const turnCompleted = (metrics: AgentMetric[]): AgentStreamEvent[] =>
|
||||
@@ -143,7 +145,7 @@ export async function* streamOmpHistory(input: {
|
||||
? [{ type: "timeline", provider: input.provider, item: replayEntry.item }]
|
||||
: [
|
||||
...turnCompleted(turns.observe(replayEntry.message)),
|
||||
...mapper.mapMessages([replayEntry.message]),
|
||||
...(await mapper.mapMessages([replayEntry.message])),
|
||||
];
|
||||
for (const event of events) {
|
||||
yield timestamp && event.type === "timeline" ? { ...event, timestamp } : event;
|
||||
@@ -152,7 +154,12 @@ export async function* streamOmpHistory(input: {
|
||||
yield* turnCompleted(turns.end());
|
||||
replay.lastReply = turns.lastReply;
|
||||
for (const transcript of readSubagentTranscripts(messages, input.sessionFile)) {
|
||||
yield* replaySubagentTranscript(transcript, input.provider, visitedSessionFiles);
|
||||
yield* replaySubagentTranscript(
|
||||
transcript,
|
||||
input.provider,
|
||||
visitedSessionFiles,
|
||||
input.blobDirectory,
|
||||
);
|
||||
}
|
||||
return replay;
|
||||
}
|
||||
@@ -161,6 +168,7 @@ async function* replaySubagentTranscript(
|
||||
transcript: OmpSubagentTranscript,
|
||||
provider: AgentProvider,
|
||||
visitedSessionFiles: Set<string>,
|
||||
blobDirectory?: string,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
const childEntries = await readActiveOmpEntryChain(transcript.sessionFile).catch(
|
||||
(error: unknown) => {
|
||||
@@ -175,6 +183,7 @@ async function* replaySubagentTranscript(
|
||||
sessionFile: transcript.sessionFile,
|
||||
provider,
|
||||
visitedSessionFiles,
|
||||
blobDirectory,
|
||||
})) {
|
||||
if (event.type === "timeline") {
|
||||
yield {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
type OmpToolResult,
|
||||
type OmpTrackedToolCall,
|
||||
} from "./tool-call-detail.js";
|
||||
import { renderOmpToolResultImages, splitOmpToolResultImages } from "./tool-result-images.js";
|
||||
|
||||
export interface OmpCapturedUserMessageEntry {
|
||||
id: string;
|
||||
@@ -77,9 +78,10 @@ export class OmpHistoryMapper {
|
||||
private readonly userEntries: readonly OmpCapturedUserMessageEntry[] = [],
|
||||
private readonly hooks: OmpHistoryMapperHooks = {},
|
||||
private readonly bridgedTools: ReadonlyMap<string, OmpBridgedToolIdentity> = new Map(),
|
||||
private readonly blobDirectory?: string,
|
||||
) {}
|
||||
|
||||
mapMessages(messages: readonly OmpAgentMessage[]): AgentStreamEvent[] {
|
||||
async mapMessages(messages: readonly OmpAgentMessage[]): Promise<AgentStreamEvent[]> {
|
||||
const events: AgentStreamEvent[] = [];
|
||||
|
||||
for (const message of messages) {
|
||||
@@ -94,10 +96,7 @@ export class OmpHistoryMapper {
|
||||
events.push(...this.mapAssistantMessage(message));
|
||||
break;
|
||||
case "toolResult": {
|
||||
const event = this.mapToolResultMessage(message);
|
||||
if (event) {
|
||||
events.push(event);
|
||||
}
|
||||
events.push(...(await this.mapToolResultMessage(message)));
|
||||
break;
|
||||
}
|
||||
case "bashExecution":
|
||||
@@ -217,18 +216,18 @@ export class OmpHistoryMapper {
|
||||
return events;
|
||||
}
|
||||
|
||||
private mapToolResultMessage(
|
||||
private async mapToolResultMessage(
|
||||
message: Extract<OmpAgentMessage, { role: "toolResult" }>,
|
||||
): AgentStreamEvent | null {
|
||||
): Promise<AgentStreamEvent[]> {
|
||||
const tracked =
|
||||
this.pendingToolCalls.get(message.toolCallId) ?? parseToolArgs(message.toolName, null);
|
||||
this.pendingToolCalls.delete(message.toolCallId);
|
||||
const result = parseToolResult({ content: message.content, details: message.details });
|
||||
const { images, result } = splitOmpToolResultImages(
|
||||
parseToolResult({ content: message.content, details: message.details }),
|
||||
);
|
||||
const detail = this.mapToolDetail(message.toolCallId, tracked, result);
|
||||
if (!detail) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
if (!detail) return [];
|
||||
const event: AgentStreamEvent = {
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
item: withOmpToolIntent(
|
||||
@@ -242,6 +241,12 @@ export class OmpHistoryMapper {
|
||||
tracked,
|
||||
),
|
||||
};
|
||||
return [
|
||||
event,
|
||||
...(await renderOmpToolResultImages(images, this.provider, {
|
||||
blobDirectory: this.blobDirectory,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
private mapBashExecutionMessage(
|
||||
@@ -298,11 +303,7 @@ export async function* streamOmpCoreHistory(
|
||||
hooks: OmpHistoryMapperHooks = {},
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
const mapper = new OmpHistoryMapper(provider, userEntries, hooks);
|
||||
for (const event of mapper.mapMessages(messages)) {
|
||||
if (event) {
|
||||
yield event;
|
||||
}
|
||||
}
|
||||
yield* await mapper.mapMessages(messages);
|
||||
}
|
||||
|
||||
function toToolResultTimelineItem(input: {
|
||||
|
||||
@@ -71,11 +71,11 @@ describe("OMP provider subagent mapper", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("maps child message events onto the descriptor timeline", () => {
|
||||
test("maps child message events onto the descriptor timeline", async () => {
|
||||
const index = new OmpSubagentIndex();
|
||||
const parent = {};
|
||||
expect(
|
||||
index.handleEvent(parent, {
|
||||
await index.handleEvent(parent, {
|
||||
id: "child-1",
|
||||
event: {
|
||||
type: "message_end",
|
||||
|
||||
@@ -43,10 +43,10 @@ export class OmpSubagentIndex {
|
||||
return [this.upsert(id, state.status, state)];
|
||||
}
|
||||
|
||||
handleEvent(parent: object, payload: OmpSubagentEventPayload): AgentStreamEvent[] {
|
||||
async handleEvent(parent: object, payload: OmpSubagentEventPayload): Promise<AgentStreamEvent[]> {
|
||||
const state = this.stateFor(parent, payload.id, "OMP subagent");
|
||||
const messages = messagesFromSessionEvent(payload.event);
|
||||
return state.mapper.mapMessages(messages).flatMap((mapped) =>
|
||||
return (await state.mapper.mapMessages(messages)).flatMap((mapped) =>
|
||||
mapped.type === "timeline"
|
||||
? [
|
||||
{
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { open } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
|
||||
import {
|
||||
MAX_PROVIDER_IMAGE_BYTES,
|
||||
materializeProviderImage,
|
||||
renderProviderImageOutputAsAssistantMarkdown,
|
||||
} from "../provider-image-output.js";
|
||||
import { resolveOmpDiagnosticPaths } from "./provider-config.js";
|
||||
import { OmpImageContentSchema, type OmpImageContent } from "./rpc-types.js";
|
||||
import type { OmpToolResult } from "./tool-call-detail.js";
|
||||
|
||||
export function splitOmpToolResultImages(result: OmpToolResult): {
|
||||
result: OmpToolResult;
|
||||
images: OmpImageContent[];
|
||||
} {
|
||||
const images: OmpImageContent[] = [];
|
||||
if (
|
||||
!result ||
|
||||
typeof result === "string" ||
|
||||
!result.content?.some((block) => block.type === "image")
|
||||
) {
|
||||
return { result, images };
|
||||
}
|
||||
|
||||
const content = result.content.map((block) => {
|
||||
if (block.type !== "image") return block;
|
||||
const image = OmpImageContentSchema.safeParse(block);
|
||||
if (image.success) images.push(image.data);
|
||||
return { type: "text", text: "[image]" };
|
||||
});
|
||||
return { result: { ...result, content }, images };
|
||||
}
|
||||
|
||||
export async function renderOmpToolResultImages(
|
||||
images: OmpImageContent[],
|
||||
provider: string,
|
||||
options: { turnId?: string; blobDirectory?: string } = {},
|
||||
): Promise<AgentStreamEvent[]> {
|
||||
const events: AgentStreamEvent[] = [];
|
||||
for (const image of images) {
|
||||
const item = await renderProviderImageOutputAsAssistantMarkdown(image, {
|
||||
materialize: async ({ data, mimeType }) =>
|
||||
materializeProviderImage({
|
||||
data: data.startsWith("blob:")
|
||||
? await readOmpImageBlob(data, options.blobDirectory)
|
||||
: data,
|
||||
mimeType,
|
||||
}),
|
||||
});
|
||||
if (item) events.push({ type: "timeline", provider, turnId: options.turnId, item });
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
export function resolveOmpBlobDirectory(env?: NodeJS.ProcessEnv): string {
|
||||
return join(dirname(resolveOmpDiagnosticPaths(env).agentDb), "blobs");
|
||||
}
|
||||
|
||||
// OMP 18 replaces inline image bytes in the transcript with a content hash.
|
||||
async function readOmpImageBlob(reference: string, directory?: string): Promise<string> {
|
||||
const hash = /^blob:sha256:([a-f0-9]{64})$/.exec(reference)?.[1];
|
||||
if (!hash || !directory) throw new Error("Unresolved OMP image reference");
|
||||
const file = await open(
|
||||
join(directory, hash),
|
||||
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
|
||||
);
|
||||
try {
|
||||
const stat = await file.stat();
|
||||
if (!stat.isFile() || stat.size === 0 || stat.size > MAX_PROVIDER_IMAGE_BYTES) {
|
||||
throw new Error("Invalid OMP image blob");
|
||||
}
|
||||
const buffer = Buffer.allocUnsafe(stat.size);
|
||||
const { bytesRead } = await file.read({ buffer, position: 0 });
|
||||
if (bytesRead !== buffer.length || createHash("sha256").update(buffer).digest("hex") !== hash) {
|
||||
throw new Error("Invalid OMP image blob");
|
||||
}
|
||||
return buffer.toString("base64");
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user