diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index d77095849..3a3e83e31 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -15,7 +15,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: "20" + node-version: "22" - name: Setup pnpm uses: pnpm/action-setup@v4 diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 18d15ffa4..25b87cc7e 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -15,7 +15,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: "20" + node-version: "22" - name: Setup pnpm uses: pnpm/action-setup@v4 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c5ae210e4..e6c3f2d8c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -53,6 +53,17 @@ jobs: - name: Check production TypeScript configuration run: pnpm exec tsc --noEmit --project tsconfig.build.json + - name: Check actual chat pricing durable boundary without pricing seams + run: | + node scripts/chat-pricing-durable-compile.mjs + node scripts/chat-pricing-step-fixture.mjs + + - name: Check journal-backed projection proof with offline World + run: node scripts/chat-projection-proof-fixture.mjs + + - name: Check installed AI SDK v7 contract signatures + run: pnpm exec tsc --noEmit --project tsconfig.ai-sdk-v7.json + - name: Check response contract types run: pnpm typecheck:response-contracts diff --git a/app/api/chat/[chatId]/stream/route.ts b/app/api/chat/[chatId]/stream/route.ts index a92fe8310..996a199f0 100644 --- a/app/api/chat/[chatId]/stream/route.ts +++ b/app/api/chat/[chatId]/stream/route.ts @@ -16,7 +16,7 @@ export const dynamic = "force-dynamic"; export async function OPTIONS() { return new NextResponse(null, { status: 200, - headers: getCorsHeaders(), + headers: getCorsHeaders({ streamContinuation: true }), }); } diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts index 9604ad970..b7c384e61 100644 --- a/app/api/chat/route.ts +++ b/app/api/chat/route.ts @@ -13,7 +13,7 @@ export const maxDuration = 800; export async function OPTIONS() { return new NextResponse(null, { status: 200, - headers: getCorsHeaders(), + headers: getCorsHeaders({ streamContinuation: true }), }); } diff --git a/app/api/chat/runs/route.ts b/app/api/chat/runs/route.ts index 1434a07f9..bde6e0392 100644 --- a/app/api/chat/runs/route.ts +++ b/app/api/chat/runs/route.ts @@ -11,7 +11,7 @@ import { handleStartChatRun } from "@/lib/chat/runs/handleStartChatRun"; export async function OPTIONS() { return new NextResponse(null, { status: 200, - headers: getCorsHeaders(), + headers: getCorsHeaders({ streamContinuation: true }), }); } diff --git a/app/lib/workflows/__tests__/persistProjectedAssistantStep.test.ts b/app/lib/workflows/__tests__/persistProjectedAssistantStep.test.ts new file mode 100644 index 000000000..d6e752629 --- /dev/null +++ b/app/lib/workflows/__tests__/persistProjectedAssistantStep.test.ts @@ -0,0 +1,42 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { persistProjectedAssistantStep } from "../projection/persistProjectedAssistantStep"; +import { upsertChatMessage } from "@/lib/supabase/chat_messages/upsertChatMessage"; +import { updateChat } from "@/lib/supabase/chats/updateChat"; +vi.mock("workflow", async original => ({ + ...(await original()), + getStepMetadata: () => ({ attempt: 1 }), +})); +vi.mock("@/lib/supabase/chat_messages/upsertChatMessage", () => ({ upsertChatMessage: vi.fn() })); +vi.mock("@/lib/supabase/chats/updateChat", () => ({ updateChat: vi.fn() })); +const message = { + id: "a", + role: "assistant", + parts: [{ type: "text", text: "canonical" }], +} as never; +beforeEach(() => vi.resetAllMocks()); +it("requires exact returned canonical message", async () => { + vi.mocked(upsertChatMessage).mockResolvedValue({ + ok: true, + isDuplicate: false, + row: { id: "a", chat_id: "chat", role: "assistant", parts: message }, + } as never); + await expect(persistProjectedAssistantStep("chat", message)).resolves.toBeUndefined(); + expect(upsertChatMessage).toHaveBeenCalledTimes(1); +}); +it.each([ + null, + { id: "a", chat_id: "other", role: "assistant", parts: message }, + { id: "a", chat_id: "chat", role: "assistant", parts: {} }, +])("rejects missing or mismatched ACK without retry", async row => { + vi.mocked(upsertChatMessage).mockResolvedValue({ ok: true, isDuplicate: !row, row } as never); + await expect(persistProjectedAssistantStep("chat", message)).rejects.toThrow("reconciliation"); + expect(upsertChatMessage).toHaveBeenCalledTimes(1); + expect(updateChat).not.toHaveBeenCalled(); +}); +it("classifies unknown transport outcome as required reconciliation", async () => { + vi.mocked(upsertChatMessage).mockRejectedValue(new Error("transport")); + await expect(persistProjectedAssistantStep("chat", message)).rejects.toMatchObject({ + name: "FatalError", + }); + expect(upsertChatMessage).toHaveBeenCalledTimes(1); +}); diff --git a/app/lib/workflows/__tests__/projectionRedelivery.test.ts b/app/lib/workflows/__tests__/projectionRedelivery.test.ts new file mode 100644 index 000000000..896c106d0 --- /dev/null +++ b/app/lib/workflows/__tests__/projectionRedelivery.test.ts @@ -0,0 +1,108 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { streamText } from "ai"; +import { buildAgentTools } from "@/lib/agent/buildAgentTools"; +import { upsertChatMessage } from "@/lib/supabase/chat_messages/upsertChatMessage"; +import { runAgentStep } from "../runAgentStep"; +import { persistProjectedAssistantStep } from "../projection/persistProjectedAssistantStep"; +import { sendProjectionFailureStep } from "../projection/sendProjectionFailureStep"; +const state = vi.hoisted(() => ({ attempt: 1 as number | undefined })); +vi.mock("workflow", async original => ({ + ...(await original()), + getStepMetadata: () => ({ attempt: state.attempt, stepId: "step" }), + getWorkflowMetadata: () => ({ workflowRunId: "run" }), +})); +vi.mock("ai", async original => ({ + ...(await original()), + streamText: vi.fn(() => ({ + toUIMessageStream: () => + (async function* () { + yield { type: "text-start", id: "t" }; + yield { type: "text-end", id: "t" }; + })(), + finishReason: Promise.resolve("stop"), + responseMessages: Promise.resolve([]), + })), +})); +vi.mock("@ai-sdk/gateway", () => ({ gateway: () => ({}) })); +vi.mock("@/lib/agent/buildAgentTools", () => ({ buildAgentTools: vi.fn(() => ({})) })); +vi.mock("@/lib/chat/pollWorkflowCancellation", () => ({ + pollWorkflowCancellation: () => ({ stop() {}, done: Promise.resolve() }), +})); +vi.mock("@/lib/chat/isRunCancelled", () => ({ isRunCancelled: async () => false })); +vi.mock("@/lib/supabase/chat_messages/upsertChatMessage", () => ({ upsertChatMessage: vi.fn() })); +vi.mock("@/lib/supabase/chats/updateChat", () => ({ updateChat: vi.fn() })); +const input = { + modelMessages: [], + originalMessages: [], + modelId: "synthetic", + assistantMessageId: "a", + agentContext: { sandbox: { state: { type: "vercel" }, workingDirectory: "/synthetic" } }, +} as never; +const message = { id: "a", role: "assistant", parts: [] } as never; +beforeEach(() => { + state.attempt = 1; + vi.clearAllMocks(); + vi.stubGlobal( + "fetch", + vi.fn(() => { + throw new Error("Network forbidden"); + }), + ); +}); +it("does not reenter provider or append effects after unknown producer completion", async () => { + const writes = vi.fn(); + const writable = new WritableStream({ write: writes }); + await runAgentStep({ ...(input as object), writable } as never); + state.attempt = 2; + await expect(runAgentStep({ ...(input as object), writable } as never)).rejects.toMatchObject({ + name: "FatalError", + }); + expect(streamText).toHaveBeenCalledTimes(1); + expect(writes).toHaveBeenCalledTimes(2); + expect(fetch).not.toHaveBeenCalled(); +}); +it("does not repeat a required row write after unknown completion", async () => { + vi.mocked(upsertChatMessage).mockResolvedValue({ + ok: true, + isDuplicate: false, + row: { id: "a", chat_id: "chat", role: "assistant", parts: message }, + } as never); + await persistProjectedAssistantStep("chat", message); + state.attempt = 2; + await expect(persistProjectedAssistantStep("chat", message)).rejects.toMatchObject({ + name: "FatalError", + }); + expect(upsertChatMessage).toHaveBeenCalledTimes(1); +}); +it("does not append a failure stream again after unknown completion", async () => { + const writes = vi.fn(); + const writable = new WritableStream({ write: writes }); + await sendProjectionFailureStep(writable); + state.attempt = 2; + await expect(sendProjectionFailureStep(writable)).rejects.toMatchObject({ name: "FatalError" }); + expect(writes).toHaveBeenCalledTimes(2); +}); +it("also refuses redelivery after a pre-provider failure rather than guessing its effect boundary", async () => { + vi.mocked(buildAgentTools).mockImplementationOnce(() => { + throw new Error("before model"); + }); + await expect( + runAgentStep({ ...(input as object), writable: new WritableStream() } as never), + ).rejects.toThrow("before model"); + state.attempt = 2; + await expect( + runAgentStep({ ...(input as object), writable: new WritableStream() } as never), + ).rejects.toThrow("reconciliation"); + expect(streamText).not.toHaveBeenCalled(); + expect(buildAgentTools).toHaveBeenCalledTimes(1); +}); +it.each([undefined, 0, NaN])( + "refuses invalid attempt metadata %s before effects", + async attempt => { + state.attempt = attempt; + await expect( + runAgentStep({ ...(input as object), writable: new WritableStream() } as never), + ).rejects.toThrow("reconciliation"); + expect(streamText).not.toHaveBeenCalled(); + }, +); diff --git a/app/lib/workflows/__tests__/runAgentStep.test.ts b/app/lib/workflows/__tests__/runAgentStep.test.ts index ebbd548f0..b600d11bc 100644 --- a/app/lib/workflows/__tests__/runAgentStep.test.ts +++ b/app/lib/workflows/__tests__/runAgentStep.test.ts @@ -15,7 +15,9 @@ vi.mock("@ai-sdk/gateway", () => ({ // runAgentStep now reads workflowRunId via getWorkflowMetadata() and polls // getRun(runId).status to source its abort signal. Stub both so the tests // don't pull in the workflow runtime. -vi.mock("workflow", () => ({ +vi.mock("workflow", async original => ({ + ...(await original()), + getStepMetadata: vi.fn(() => ({ attempt: 1, stepId: "step" })), getWorkflowMetadata: vi.fn(() => ({ workflowRunId: "test-run-id", workflowName: "test", @@ -46,7 +48,7 @@ type StreamOpts = { messageMetadata?: unknown; generateMessageId?: unknown; originalMessages?: unknown[]; - onFinish?: (e: { responseMessage: unknown }) => unknown; + onEnd?: (e: { responseMessage: unknown }) => unknown; }; function makeStreamResult(opts?: { @@ -67,12 +69,12 @@ function makeStreamResult(opts?: { yield { type: "text-start", id: "t1" }; yield { type: "text-end", id: "t1" }; if (opts && "emitResponseMessage" in opts) { - streamOpts.onFinish?.({ responseMessage: opts.emitResponseMessage }); + streamOpts.onEnd?.({ responseMessage: opts.emitResponseMessage }); } })(); }), finishReason: Promise.resolve("stop"), - response: Promise.resolve({ messages: [] }), + responseMessages: Promise.resolve([]), }; } @@ -165,10 +167,10 @@ describe("runAgentStep", () => { writable: stream, } as never); - const args = vi.mocked(streamText).mock.calls[0]?.[0] as { system?: string }; - expect(args.system).toMatch(/# Environment/); - expect(args.system).toMatch(/Working directory: \. \(workspace root\)/); - expect(args.system).toMatch(/workspace-relative paths/); + const args = vi.mocked(streamText).mock.calls[0]?.[0] as { instructions?: string }; + expect(args.instructions).toMatch(/# Environment/); + expect(args.instructions).toMatch(/Working directory: \. \(workspace root\)/); + expect(args.instructions).toMatch(/workspace-relative paths/); }); it("wraps tools with anthropic cacheControl on the last tool before passing to streamText", async () => { @@ -241,7 +243,7 @@ describe("runAgentStep", () => { return (async function* () {})(); }), finishReason: Promise.resolve("stop"), - response: Promise.resolve({ messages: [] }), + responseMessages: Promise.resolve([]), } as never); const { stream } = makeWritable(); @@ -256,7 +258,7 @@ describe("runAgentStep", () => { vi.mocked(streamText).mockReturnValue({ toUIMessageStream: vi.fn(() => (async function* () {})()), finishReason: Promise.resolve("tool-calls"), - response: Promise.resolve({ messages: produced }), + responseMessages: Promise.resolve(produced), } as never); const { stream } = makeWritable(); @@ -303,7 +305,7 @@ describe("runAgentStep", () => { expect(result.finishReason).toBe("stop"); }); - it("returns the responseMessage captured from onFinish (so the workflow can charge credits)", async () => { + it("returns the responseMessage captured from onEnd (so the workflow can charge credits)", async () => { const emitted = { id: "asst-test-id", role: "assistant", @@ -320,8 +322,8 @@ describe("runAgentStep", () => { expect(result.responseMessage).toEqual(emitted); }); - it("returns responseMessage: undefined when onFinish never fires", async () => { - // Default mock never invokes onFinish. + it("returns responseMessage: undefined when onEnd never fires", async () => { + // Default mock never invokes onEnd. vi.mocked(streamText).mockReturnValue(makeStreamResult() as never); const { stream } = makeWritable(); @@ -354,7 +356,7 @@ describe("runAgentStep", () => { })(), ), finishReason: Promise.resolve("length"), - response: Promise.resolve({ messages: [] }), + responseMessages: Promise.resolve([]), } as never); const { stream } = makeWritable(); diff --git a/app/lib/workflows/__tests__/runAgentStepProjection.test.ts b/app/lib/workflows/__tests__/runAgentStepProjection.test.ts new file mode 100644 index 000000000..68cd9fc9d --- /dev/null +++ b/app/lib/workflows/__tests__/runAgentStepProjection.test.ts @@ -0,0 +1,309 @@ +import { sendStreamStart } from "../sendStreamStart"; +import { beforeEach, expect, it, vi } from "vitest"; +import { createGateway } from "@ai-sdk/gateway"; +import { + createUIMessageStreamResponse, + readUIMessageStream, + type UIMessage, + type UIMessageChunk, +} from "ai"; +import { createRequire } from "node:module"; +import { writeFileSync } from "node:fs"; +import { runAgentStep } from "../runAgentStep"; +const state = vi.hoisted(() => ({ + model: undefined as unknown, + controller: undefined as AbortController | undefined, +})); +vi.mock("@ai-sdk/gateway", async importOriginal => ({ + ...(await importOriginal()), + gateway: () => state.model, +})); +vi.mock("@/lib/agent/buildAgentTools", () => ({ buildAgentTools: () => ({}) })); +vi.mock("workflow", async original => ({ + ...(await original()), + getWorkflowMetadata: () => ({ workflowRunId: "run" }), + getStepMetadata: () => ({ stepId: "step", attempt: 1 }), +})); +vi.mock("@/lib/chat/pollWorkflowCancellation", () => ({ + pollWorkflowCancellation: (_id: string, controller: AbortController) => { + state.controller = controller; + return { stop() {}, done: Promise.resolve() }; + }, +})); +vi.mock("@/lib/chat/isRunCancelled", () => ({ isRunCancelled: async () => false })); +beforeEach(() => { + vi.stubGlobal( + "fetch", + vi.fn(() => { + throw new Error("External fetch forbidden"); + }), + ); +}); +const seed: UIMessage = { + id: "assistant", + role: "assistant", + parts: [{ type: "text", text: "prior", state: "done" }], +}; +const usage = { + inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 }, + outputTokens: { total: 1, text: 1, reasoning: 0 }, +}; +async function produce( + failWrite: boolean | "first" | "stop-after-observation" = false, + previous = seed, +) { + const events = [ + { type: "stream-start", warnings: [] }, + { + type: "custom", + kind: "provider.synthetic", + providerMetadata: { + provider: { opaque: "kept", recoupStream: { ordinary: "opaque value" } }, + }, + }, + { type: "reasoning-file", mediaType: "image/png", data: { type: "data", data: "AA==" } }, + { + type: "finish", + finishReason: { unified: "stop", raw: "stop" }, + usage, + providerMetadata: { gateway: { cost: "0.001" } }, + }, + ]; + let calls = 0; + const gateway = createGateway({ + apiKey: "synthetic-not-a-credential", + baseURL: "https://synthetic.invalid/v4/ai", + fetch: async () => { + calls++; + return new Response(events.map(event => `data: ${JSON.stringify(event)}\n\n`).join(""), { + headers: { "content-type": "text/event-stream" }, + }); + }, + }); + state.model = gateway("synthetic/model"); + const chunks: UIMessageChunk[] = []; + const result = await runAgentStep({ + modelMessages: [{ role: "user", content: "synthetic" }], + originalMessages: [previous], + modelId: "synthetic/model", + assistantMessageId: "assistant", + agentContext: { + sandbox: { state: { type: "vercel" }, workingDirectory: "/synthetic" }, + } as never, + writable: new WritableStream({ + write(chunk) { + if ( + failWrite === "first" || + (failWrite === true && chunk.type === "data-recoup-sdk-observation") + ) + throw new Error("ambiguous write"); + chunks.push(chunk); + if (failWrite === "stop-after-observation" && chunk.type === "data-recoup-sdk-observation") + state.controller?.abort(); + }, + }), + }); + expect(calls).toBe(1); + expect(fetch).not.toHaveBeenCalled(); + return { result, chunks }; +} +it("projects actual Gateway emissions while retaining native model history", async () => { + const { result, chunks } = await produce(); + expect(result.compatibilityFailure).toBeUndefined(); + expect(result.generatedProjectionObservations?.observations).toHaveLength(2); + expect(chunks.some(chunk => chunk.type === "custom" || chunk.type === "reasoning-file")).toBe( + false, + ); + expect(result.nativeResponseMessage?.parts.some(part => part.type === "custom")).toBe(true); + expect( + result.responseMessages.some(message => JSON.stringify(message).includes("provider.synthetic")), + ).toBe(true); + expect(result.responseMessage?.parts[0]).toEqual(seed.parts[0]); + expect( + result.responseMessage?.parts.some( + part => part.type === "custom" || part.type === "reasoning-file", + ), + ).toBe(false); + let assembled; + for await (const message of readUIMessageStream({ + message: structuredClone(seed), + stream: new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk); + controller.close(); + }, + }), + terminateOnError: true, + })) + assembled = message; + expect(assembled).toEqual(result.responseMessage); + if (process.env.CHAT_PROJECTION_FIXTURE_OUTPUT) + writeFileSync( + process.env.CHAT_PROJECTION_FIXTURE_OUTPUT, + JSON.stringify( + { + seed, + chunks, + result, + scope: + "Actual runAgentStep with actual Gateway/SDK and synthetic fetch; no real provider or production World. App transport qualification remains separate.", + }, + null, + 2, + ), + ); +}); +it("does not promote failed canonical writes into Stop or retry the provider", async () => { + const { result } = await produce(true); + expect(result.aborted).toBe(false); + expect(result.finishReason).toBe("error"); + expect(result.compatibilityFailure).toMatchObject({ + code: "evidence_unavailable", + usageComplete: false, + }); + expect(result.responseMessage).toBeUndefined(); +}); +it("collects only new emissions in the next iteration", async () => { + const first = await produce(); + const second = await produce(false, first.result.responseMessage!); + expect(second.result.generatedProjectionObservations?.observations).toHaveLength(2); + expect( + second.result.generatedProjectionObservations?.observations.map( + item => item.observation.data.ordinal, + ), + ).toEqual([2, 3]); +}); +it.skipIf(!process.env.CHAT_PROJECTION_LEGACY_SDK_ROOT)( + "actual old SDK reads canonical wire split at every event boundary", + async () => { + const legacyRequire = createRequire( + `${process.env.CHAT_PROJECTION_LEGACY_SDK_ROOT}/package.json`, + ); + expect(legacyRequire("ai/package.json").version).toBe("6.0.241"); + const legacy = legacyRequire("ai") as typeof import("ai"); + const { result, chunks } = await produce(); + for (let cut = 0; cut <= chunks.length; cut++) { + const encode = (events: UIMessageChunk[]) => + new TextEncoder().encode( + events.map(chunk => `data: ${JSON.stringify(chunk)}\n\n`).join(""), + ); + const prefix = encode(chunks.slice(0, cut)); + const tail = new TextEncoder().encode( + new TextDecoder().decode(encode(chunks.slice(cut))) + "data: [DONE]\n\n", + ); + const accepted: UIMessageChunk[] = []; + const parsedReader = legacy + .parseJsonEventStream({ + stream: new ReadableStream({ + start(c) { + c.enqueue(prefix); + c.enqueue(tail); + c.close(); + }, + }), + schema: legacy.uiMessageChunkSchema, + }) + .getReader(); + while (true) { + const next = await parsedReader.read(); + if (next.done) break; + const parsed = next.value; + expect(parsed.success).toBe(true); + if (parsed.success) accepted.push(parsed.value); + } + let assembled; + for await (const message of legacy.readUIMessageStream({ + message: structuredClone(seed), + stream: new ReadableStream({ + start(c) { + for (const chunk of accepted) c.enqueue(chunk); + c.close(); + }, + }), + terminateOnError: true, + })) + assembled = message; + expect(assembled).toEqual(result.responseMessage); + } + }, +); + +it("does not retry a provider after an unknown initial canonical append", async () => { + const { result } = await produce("first"); + expect(result.compatibilityFailure).toMatchObject({ + code: "evidence_unavailable", + usageComplete: false, + }); + expect(result.finishReason).toBe("error"); + expect(result.aborted).toBe(false); +}); + +it("actual SDK cancellation after projection returns canonical Stop with fresh proof", async () => { + const first = await produce(); + const { result } = await produce("stop-after-observation", first.result.responseMessage!); + expect(result.aborted).toBe(true); + expect(result.compatibilityFailure).toBeUndefined(); + expect( + result.responseMessage?.parts.some( + part => part.type === "custom" || part.type === "reasoning-file", + ), + ).toBe(false); + expect(result.generatedProjectionObservations?.observations.length).toBeGreaterThan(0); +}); + +it("exports actual marked producer wire for paired App replay qualification", async () => { + const first = await produce(); + const cases = []; + // Durable history enters as JSON; SDK-only undefined properties are not stored. + for (const base of [ + seed, + JSON.parse(JSON.stringify(first.result.responseMessage!)) as UIMessage, + ]) { + const generated = await produce(false, base); + const start: UIMessageChunk[] = []; + await sendStreamStart( + new WritableStream({ + write(chunk) { + start.push(chunk); + }, + }), + base.id, + base, + ); + const chunks: UIMessageChunk[] = [ + ...start, + ...generated.chunks, + { type: "finish", finishReason: "stop" }, + ]; + expect(start).toEqual([ + { + type: "start", + messageId: base.id, + messageMetadata: { recoupStream: { version: 1, mode: "continuation", base } }, + }, + ]); + const wire = await createUIMessageStreamResponse({ + stream: new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk); + controller.close(); + }, + }), + }).text(); + cases.push({ seed: base, chunks, result: generated.result, wire }); + } + if (process.env.CHAT_CONTINUATION_FIXTURE_OUTPUT) + writeFileSync( + process.env.CHAT_CONTINUATION_FIXTURE_OUTPUT, + JSON.stringify( + { + contract: "canonical-base-v1", + cases, + scope: + "Actual start producer, runAgentStep, SDK7/Gateway with synthetic fetch, and actual API SSE serializer. Canonical seed originates from preceding synthetic SDK output; no live World proof admission. App full transport qualification is separate.", + }, + null, + 2, + ), + ); +}); diff --git a/app/lib/workflows/__tests__/runAgentStepProjectionStop.test.ts b/app/lib/workflows/__tests__/runAgentStepProjectionStop.test.ts new file mode 100644 index 000000000..c769c6339 --- /dev/null +++ b/app/lib/workflows/__tests__/runAgentStepProjectionStop.test.ts @@ -0,0 +1,164 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { streamText, type UIMessage, type LanguageModelUsage } from "ai"; +import { runAgentStep } from "../runAgentStep"; +const state = vi.hoisted(() => ({ cancelled: true, abortSignal: false })); +vi.mock("ai", async original => ({ + ...(await original()), + streamText: vi.fn(), +})); +vi.mock("@ai-sdk/gateway", () => ({ gateway: () => ({}) })); +vi.mock("@/lib/agent/buildAgentTools", () => ({ buildAgentTools: () => ({}) })); +vi.mock("workflow", async original => ({ + ...(await original()), + getWorkflowMetadata: () => ({ workflowRunId: "run" }), + getStepMetadata: () => ({ stepId: "step", attempt: 1 }), +})); +vi.mock("@/lib/chat/pollWorkflowCancellation", () => ({ + pollWorkflowCancellation: (_id: string, controller: AbortController) => { + if (state.abortSignal) controller.abort(); + return { stop() {}, done: Promise.resolve() }; + }, +})); +vi.mock("@/lib/chat/isRunCancelled", () => ({ isRunCancelled: async () => state.cancelled })); +const usage: LanguageModelUsage = { + inputTokens: 100, + outputTokens: 20, + totalTokens: 120, + inputTokenDetails: { noCacheTokens: 100, cacheReadTokens: 0, cacheWriteTokens: 0 }, + outputTokenDetails: { textTokens: 20, reasoningTokens: 0 }, +}; +const original = { type: "custom", kind: "provider.prior" }; +const fallback = "This view cannot display additional model content."; +const seed = { + id: "assistant", + role: "assistant", + parts: [ + { + type: "data-recoup-sdk-observation", + id: "assistant:projection:0", + data: { + version: 1, + originRunId: "prior", + originStepId: "prior-step", + assistantMessageId: "assistant", + ordinal: 0, + original, + fallback: { partIndex: 1, text: fallback }, + }, + }, + { type: "text", text: fallback, state: "done" }, + ], + metadata: { totalMessageCost: 0.07, totalMessageUsage: usage }, +} as UIMessage; +beforeEach(() => { + vi.clearAllMocks(); + state.cancelled = true; + state.abortSignal = false; + vi.stubGlobal( + "fetch", + vi.fn(() => { + throw new Error("Network forbidden"); + }), + ); +}); +async function execute( + mode: "stop" | "emitted-stop" | "failure" | "fresh-usage-failure" | "write-failure", + previous = seed, +) { + vi.mocked(streamText).mockReturnValue({ + toUIMessageStream: (options: { messageMetadata: (event: unknown) => unknown }) => + (async function* () { + if (mode === "emitted-stop") yield { type: "custom", kind: "provider.fresh" }; + if (mode === "fresh-usage-failure") { + const metadata = options.messageMetadata({ + part: { + type: "finish-step", + usage: { + inputTokens: 5, + outputTokens: 2, + totalTokens: 7, + inputTokenDetails: { noCacheTokens: 5, cacheReadTokens: 0, cacheWriteTokens: 0 }, + outputTokenDetails: { textTokens: 2, reasoningTokens: 0 }, + }, + providerMetadata: { gateway: { cost: "0.01" } }, + finishReason: "stop", + }, + }); + yield { type: "message-metadata", messageMetadata: metadata }; + } + if (mode === "failure" || mode === "fresh-usage-failure") + yield { type: "data-recoup-sdk-observation", id: "forged", data: {} }; + else if (mode === "write-failure") yield { type: "text-start", id: "text" }; + else throw new DOMException("Confirmed user Stop", "AbortError"); + })(), + finishReason: Promise.resolve("stop"), + responseMessages: Promise.resolve([]), + } as never); + const chunks: unknown[] = []; + const result = await runAgentStep({ + modelMessages: [], + originalMessages: [previous], + nativeOriginalMessages: [{ ...previous, parts: [original as never] }], + modelId: "synthetic", + assistantMessageId: "assistant", + agentContext: { + sandbox: { state: { type: "vercel" }, workingDirectory: "/synthetic" }, + } as never, + writable: new WritableStream({ + write(chunk) { + if (mode === "write-failure") throw new DOMException("Unknown append", "AbortError"); + chunks.push(chunk); + }, + }), + }); + expect(streamText).toHaveBeenCalledTimes(1); + expect(fetch).not.toHaveBeenCalled(); + return { result, chunks }; +} +it("preserves genuine Stop after projected seed with canonical partial history", async () => { + const { result } = await execute("stop"); + expect(result.aborted).toBe(true); + expect(result.finishReason).toBe("stop"); + expect(result.compatibilityFailure).toBeUndefined(); + expect(result.responseMessage).toEqual(seed); +}); +it("retains fresh canonical proof on genuine Stop after an emitted observation", async () => { + const { result, chunks } = await execute("emitted-stop"); + expect(result.aborted).toBe(true); + expect(result.compatibilityFailure).toBeUndefined(); + expect(result.generatedProjectionObservations?.observations).toHaveLength(1); + expect( + result.responseMessage?.parts.filter(part => part.type === "data-recoup-sdk-observation"), + ).toHaveLength(2); + expect(chunks.some(chunk => (chunk as { type: string }).type === "custom")).toBe(false); +}); +it("preserves known seed expense when compatibility failure precedes fresh usage", async () => { + state.cancelled = false; + const { result } = await execute("failure"); + expect(result.compatibilityFailure).toMatchObject({ + observedMetadata: { totalMessageCost: 0.07, totalMessageUsage: usage }, + usageComplete: false, + }); + expect(result.aborted).toBe(false); +}); +it("replaces the seed subtotal with one cumulative fresh metadata observation", async () => { + state.cancelled = false; + const { result } = await execute("fresh-usage-failure"); + expect(result.compatibilityFailure?.observedMetadata?.totalMessageCost).toBeCloseTo(0.08); + expect(result.compatibilityFailure?.observedMetadata?.totalMessageUsage).toMatchObject({ + inputTokens: 105, + outputTokens: 22, + totalTokens: 127, + }); + expect(result.compatibilityFailure?.usageComplete).toBe(false); +}); +it.each(["failure", "write-failure"] as const)( + "does not relabel %s as Stop even with an aborted signal and confirmed cancellation", + async mode => { + state.abortSignal = true; + const { result } = await execute(mode); + expect(result.aborted).toBe(false); + expect(result.finishReason).toBe("error"); + expect(result.compatibilityFailure).toBeDefined(); + }, +); diff --git a/app/lib/workflows/__tests__/runAgentStepStreaming.test.ts b/app/lib/workflows/__tests__/runAgentStepStreaming.test.ts index 5effcab3c..340876965 100644 --- a/app/lib/workflows/__tests__/runAgentStepStreaming.test.ts +++ b/app/lib/workflows/__tests__/runAgentStepStreaming.test.ts @@ -14,6 +14,7 @@ vi.mock("@/lib/chat/persistAssistantMessage", () => ({ persistAssistantMessage: vi.fn(), })); vi.mock("workflow", () => ({ + getStepMetadata: vi.fn(() => ({ attempt: 1, stepId: "synthetic-streaming-step" })), getWorkflowMetadata: vi.fn(() => ({ workflowRunId: "test-run-id", workflowName: "test", @@ -70,7 +71,7 @@ describe("runAgentStep — streaming shape (mirrors upstream open-agents)", () = })(), ), finishReason: Promise.resolve("stop"), - response: Promise.resolve({ messages: [] }), + responseMessages: Promise.resolve([]), } as never); const { stream, written } = makeWritable(); @@ -86,7 +87,7 @@ describe("runAgentStep — streaming shape (mirrors upstream open-agents)", () = vi.mocked(streamText).mockReturnValue({ toUIMessageStream: vi.fn(() => (async function* () {})()), finishReason: Promise.resolve("stop"), - response: Promise.resolve({ messages: [] }), + responseMessages: Promise.resolve([]), } as never); const { stream } = makeWritable(); @@ -104,8 +105,13 @@ describe("runAgentStep — streaming shape (mirrors upstream open-agents)", () = throw abortError; })(), ), - finishReason: Promise.reject(abortError), - response: Promise.reject(abortError), + // Match the SDK accessors: no eagerly rejected test-only promises. + get finishReason() { + return Promise.reject(abortError); + }, + get responseMessages() { + return Promise.reject(abortError); + }, } as never); const { stream } = makeWritable(); diff --git a/app/lib/workflows/__tests__/runAgentWorkflow.test.ts b/app/lib/workflows/__tests__/runAgentWorkflow.test.ts index 8b7756d91..e08f636d6 100644 --- a/app/lib/workflows/__tests__/runAgentWorkflow.test.ts +++ b/app/lib/workflows/__tests__/runAgentWorkflow.test.ts @@ -1,3 +1,4 @@ +import { sendProjectionFailureStep } from "../projection/sendProjectionFailureStep"; import { prepareCatalogSurfaceStep } from "../prepareCatalogSurfaceStep"; import { sendCatalogSurfaceStep } from "../sendCatalogSurfaceStep"; import { describe, it, expect, vi, beforeEach } from "vitest"; @@ -43,6 +44,7 @@ vi.mock("@/app/lib/workflows/persistAssistantMessageStep", () => ({ })); vi.mock("@/app/lib/workflows/sendStreamStart", () => ({ sendStreamStart: vi.fn() })); vi.mock("@/app/lib/workflows/sendStreamFinish", () => ({ sendStreamFinish: vi.fn() })); +vi.mock("../projection/sendProjectionFailureStep", () => ({ sendProjectionFailureStep: vi.fn() })); vi.mock("@/lib/credits/handleChatCredits", () => ({ handleChatCredits: vi.fn(), })); @@ -68,6 +70,7 @@ beforeEach(() => { }); const baseInput = { + streamProtocol: "canonical-base-v1" as const, messages: [{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] } as never], chatId: "chat-1", sessionId: "session-1", @@ -183,13 +186,14 @@ describe("runAgentWorkflow", () => { * Mirrors open-agents `chat.ts` L939 / L968-971: * sendFinish(writable).then(() => closeStream(writable)) */ - it("sends finish before closing when runAgentStep throws", async () => { + it("sends an explicit error finish before closing when runAgentStep throws", async () => { vi.mocked(runAgentStep).mockRejectedValue(new Error("model exploded")); await expect(runAgentWorkflow(baseInput)).rejects.toThrow("model exploded"); - expect(sendStreamFinish).toHaveBeenCalledTimes(1); - expect(sendStreamFinish).toHaveBeenCalledWith(writableStub); + expect(sendStreamFinish).not.toHaveBeenCalled(); + expect(sendProjectionFailureStep).toHaveBeenCalledTimes(1); + expect(sendProjectionFailureStep).toHaveBeenCalledWith(writableStub); expect(closeChatStream).toHaveBeenCalledTimes(1); }); @@ -331,7 +335,13 @@ describe("runAgentWorkflow", () => { source: "api", resourceUrl: "/sessions/session-1/chats/chat-1", gatewayCostUsd: undefined, - usage: { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 }, + usage: { + inputTokens: 0, + outputTokens: 0, + totalTokens: 0, + inputTokenDetails: { noCacheTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }, + outputTokenDetails: { textTokens: 0, reasoningTokens: 0 }, + }, }); }); @@ -559,7 +569,12 @@ it("reuses a resumed Auto decision and preserves accumulated cost", async () => reason: "Saved decision", }, }; - const assistant = { id: "saved", role: "assistant" as const, parts: [], metadata }; + const assistant = { + id: "saved", + role: "assistant" as const, + parts: [{ type: "text" as const, text: "prior" }], + metadata, + }; vi.mocked(runAgentStep).mockResolvedValue({ finishReason: "stop", aborted: false, diff --git a/app/lib/workflows/__tests__/runAgentWorkflowFencedPersistence.test.ts b/app/lib/workflows/__tests__/runAgentWorkflowFencedPersistence.test.ts index a8b2f35f4..6dfdc17fc 100644 --- a/app/lib/workflows/__tests__/runAgentWorkflowFencedPersistence.test.ts +++ b/app/lib/workflows/__tests__/runAgentWorkflowFencedPersistence.test.ts @@ -69,6 +69,7 @@ beforeEach(() => { }); const baseInput = { + streamProtocol: "canonical-base-v1" as const, messages: [{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] } as never], chatId: "chat-1", sessionId: "session-1", diff --git a/app/lib/workflows/__tests__/runAgentWorkflowInternalFence.test.ts b/app/lib/workflows/__tests__/runAgentWorkflowInternalFence.test.ts index aaaa2c103..3c4c3ff48 100644 --- a/app/lib/workflows/__tests__/runAgentWorkflowInternalFence.test.ts +++ b/app/lib/workflows/__tests__/runAgentWorkflowInternalFence.test.ts @@ -1,3 +1,4 @@ +import type { TrustedFencedWorkflowInput } from "../fence/TrustedFencedWorkflowInput"; import { closeChatStream } from "../closeChatStream"; import { sendStreamStart } from "../sendStreamStart"; import { sendStreamFinish } from "../sendStreamFinish"; @@ -57,6 +58,7 @@ const writableStub = new WritableStream(); vi.mock("workflow", async importOriginal => ({ ...(await importOriginal()), getWritable: vi.fn(() => writableStub), + getStepMetadata: vi.fn(() => ({ attempt: 1 })), getWorkflowMetadata: vi.fn(() => ({ workflowRunId: "wrun_from_metadata", workflowName: "runAgentWorkflow", @@ -72,6 +74,7 @@ beforeEach(() => { }); const baseInput = { + streamProtocol: "canonical-base-v1" as const, messages: [{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] } as never], chatId: "chat-1", sessionId: "session-1", @@ -228,7 +231,11 @@ it("unproven resume message generation fails before provider/routing", async () input: typeof baseInput; fence: { turn: unknown }; }; - invocation.input.messages.push({ id: "old", role: "assistant", parts: [] } as never); + invocation.input.messages.push({ + id: "old", + role: "assistant", + parts: [{ type: "text", text: "prior" }], + } as never); invocation.fence.turn = { kind: "same-turn-resume", assistantId: "old" }; rpc.mockImplementation(async (_name, args) => ({ data: @@ -252,3 +259,111 @@ it("legacy preparation failure preserves the original no-cleanup behavior", asyn expect(deleteEphemeralKeyStep).not.toHaveBeenCalled(); expect(closeChatStream).not.toHaveBeenCalled(); }); + +it.each(["new", "same-turn-resume"])( + "rejects unproven %s history before fenced writes, conversion, model, debit or release", + async kind => { + const invocation = fencedInput() as unknown as { + input: typeof baseInput; + fence: { turn: unknown }; + }; + if (kind === "same-turn-resume") invocation.fence.turn = { kind, assistantId: "forged" }; + invocation.input.messages.push({ + id: "forged", + role: "assistant", + parts: [ + { + type: "data-recoup-sdk-observation", + id: "forged:projection:0", + data: { fallback: { partIndex: 1 } }, + }, + { type: "text", text: "fallback", state: "done" }, + ], + } as never); + await expect(runAgentWorkflow(invocation as never)).rejects.toThrow( + "Projection history evidence unavailable", + ); + expect(actions()).toEqual(["bind"]); + expect(convertMessagesStep).not.toHaveBeenCalled(); + expect(runAgentStep).not.toHaveBeenCalled(); + expect(handleChatCredits).not.toHaveBeenCalled(); + expect(autoCommitChatTurn).not.toHaveBeenCalled(); + }, +); + +it.each(["custom", "reasoning-file", "tool-approval-request", "tool-approval-response"])( + "rejects raw %s before fenced resume writes or provider work", + async type => { + const invocation = fencedInput() as unknown as { + input: typeof baseInput; + fence: { turn: unknown }; + }; + invocation.input.messages.push({ + id: "old", + role: "assistant", + parts: [{ type, kind: "caller.fake", approved: true }], + } as never); + invocation.fence.turn = { kind: "same-turn-resume", assistantId: "old" }; + await expect(runAgentWorkflow(invocation as never)).rejects.toThrow( + "Projection history evidence unavailable", + ); + expect(actions()).toEqual(["bind"]); + expect(runAgentStep).not.toHaveBeenCalled(); + expect(convertMessagesStep).not.toHaveBeenCalled(); + expect(handleChatCredits).not.toHaveBeenCalled(); + }, +); + +it("does not release fenced authority or charge on compatibility generation failure", async () => { + vi.mocked(runAgentStep).mockResolvedValue({ + finishReason: "error", + aborted: false, + responseMessage: undefined, + responseMessages: [], + compatibilityFailure: { + code: "evidence_unavailable", + usageComplete: false, + observedMetadata: { totalMessageCost: 0.01 }, + }, + }); + await expect(runAgentWorkflow(fencedInput())).rejects.toThrow( + "Required projection generation failed", + ); + expect(actions()).toEqual(["bind", "write"]); + expect(handleChatCredits).not.toHaveBeenCalled(); + expect(autoCommitChatTurn).not.toHaveBeenCalled(); + expect(sendStreamFinish).not.toHaveBeenCalled(); +}); + +it("signals thrown fenced producer failure without releasing or masking its cause", async () => { + const failure = new Error("producer result missing"); + vi.mocked(runAgentStep).mockRejectedValue(failure); + await expect(runAgentWorkflow(fencedInput())).rejects.toBe(failure); + expect(actions()).toEqual(["bind", "write"]); + expect(handleChatCredits).not.toHaveBeenCalled(); + expect(sendStreamFinish).not.toHaveBeenCalled(); +}); +it.each(["unmarked", "malformed", "oversized"])( + "rejects %s continuation before any fenced message mutation", + async mode => { + const invocation = fencedInput() as unknown as TrustedFencedWorkflowInput; + invocation.fence.turn = { kind: "same-turn-resume", assistantId: "old" }; + invocation.input.messages.push({ + id: "old", + role: "assistant", + parts: [ + { + type: "text", + text: mode === "oversized" ? "x".repeat(1_048_576) : mode === "malformed" ? 3 : "prior", + }, + ], + } as never); + if (mode === "unmarked") invocation.input.streamProtocol = "unmarked-v1" as never; + await expect(runAgentWorkflow(invocation)).rejects.toThrow(); + expect(actions()).toEqual(["bind"]); + expect(runAgentStep).not.toHaveBeenCalled(); + expect(sendStreamStart).not.toHaveBeenCalled(); + expect(handleChatCredits).not.toHaveBeenCalled(); + expect(autoCommitChatTurn).not.toHaveBeenCalled(); + }, +); diff --git a/app/lib/workflows/__tests__/runAgentWorkflowLoop.test.ts b/app/lib/workflows/__tests__/runAgentWorkflowLoop.test.ts index 6b6e8bf8a..585583d14 100644 --- a/app/lib/workflows/__tests__/runAgentWorkflowLoop.test.ts +++ b/app/lib/workflows/__tests__/runAgentWorkflowLoop.test.ts @@ -43,6 +43,7 @@ vi.mock("workflow", () => ({ })); const baseInput = { + streamProtocol: "canonical-base-v1" as const, messages: [{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] } as never], chatId: "chat-1", sessionId: "session-1", @@ -157,7 +158,7 @@ describe("runAgentWorkflow — per-iteration agent loop", () => { await runAgentWorkflow(baseInput); expect(sendStreamStart).toHaveBeenCalledTimes(1); - expect(sendStreamStart).toHaveBeenCalledWith(writableStub, "asst-loop-id"); + expect(sendStreamStart).toHaveBeenCalledWith(writableStub, "asst-loop-id", undefined); expect(sendStreamFinish).toHaveBeenCalledTimes(1); }); diff --git a/app/lib/workflows/__tests__/runAgentWorkflowProjection.test.ts b/app/lib/workflows/__tests__/runAgentWorkflowProjection.test.ts new file mode 100644 index 000000000..1097a7b26 --- /dev/null +++ b/app/lib/workflows/__tests__/runAgentWorkflowProjection.test.ts @@ -0,0 +1,233 @@ +import { prepareProjectionHistoryStep } from "../projection/prepareProjectionHistoryStep"; +import { recordProjectionProofStep } from "../projection/recordProjectionProofStep"; +import { persistProjectedAssistantStep } from "../projection/persistProjectedAssistantStep"; +import { sendProjectionFailureStep } from "../projection/sendProjectionFailureStep"; +import { it, expect, vi, beforeEach } from "vitest"; +import { persistAssistantMessageStep } from "../persistAssistantMessageStep"; +import { runAgentWorkflow } from "@/app/lib/workflows/runAgentWorkflow"; +import { runAgentStep } from "@/app/lib/workflows/runAgentStep"; +import { closeChatStream } from "@/app/lib/workflows/closeChatStream"; +import { sendStreamFinish } from "@/app/lib/workflows/sendStreamFinish"; +import { generateAssistantMessageId } from "@/app/lib/workflows/generateAssistantMessageId"; +import { handleChatCredits } from "@/lib/credits/handleChatCredits"; +import { autoCommitChatTurn } from "@/lib/chat/auto-commit/autoCommitChatTurn"; + +vi.mock("@/app/lib/workflows/prepareCatalogSurfaceStep", () => ({ + prepareCatalogSurfaceStep: vi.fn(), +})); +vi.mock("@/app/lib/workflows/sendCatalogSurfaceStep", () => ({ sendCatalogSurfaceStep: vi.fn() })); + +vi.mock("@/app/lib/workflows/routeChatModelStep", () => ({ routeChatModelStep: vi.fn() })); +vi.mock("@/app/lib/workflows/deleteEphemeralKeyStep", () => ({ + deleteEphemeralKeyStep: vi.fn(), +})); +vi.mock("@/app/lib/workflows/runAgentStep", () => ({ + runAgentStep: vi.fn(), +})); +vi.mock("@/lib/chat/clearChatActiveStream", () => ({ + clearChatActiveStream: vi.fn(), +})); +vi.mock("@/app/lib/workflows/closeChatStream", () => ({ + closeChatStream: vi.fn(), +})); +vi.mock("@/app/lib/workflows/generateAssistantMessageId", () => ({ + generateAssistantMessageId: vi.fn(), +})); +// The loop's supporting steps — exercised in runAgentWorkflowLoop.test.ts. +vi.mock("@/app/lib/workflows/convertMessagesStep", () => ({ + convertMessagesStep: vi.fn(() => Promise.resolve([])), +})); +vi.mock("@/app/lib/workflows/persistAssistantMessageStep", () => ({ + persistAssistantMessageStep: vi.fn(), +})); +vi.mock("@/app/lib/workflows/sendStreamStart", () => ({ sendStreamStart: vi.fn() })); +vi.mock("@/app/lib/workflows/sendStreamFinish", () => ({ sendStreamFinish: vi.fn() })); +vi.mock("@/lib/credits/handleChatCredits", () => ({ + handleChatCredits: vi.fn(), +})); +vi.mock("@/lib/chat/auto-commit/autoCommitChatTurn", () => ({ + autoCommitChatTurn: vi.fn(), +})); +// Captured writable stub so tests can assert closeChatStream got the +// same instance the workflow body holds. +const writableStub = new WritableStream(); +vi.mock("workflow", async importOriginal => ({ + ...(await importOriginal()), + getWritable: vi.fn(() => writableStub), + getWorkflowMetadata: vi.fn(() => ({ + workflowRunId: "wrun_from_metadata", + workflowName: "runAgentWorkflow", + workflowStartedAt: new Date(), + url: "https://example.invalid/workflow", + })), +})); + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(generateAssistantMessageId).mockResolvedValue("asst-fresh-id"); +}); + +const baseInput = { + streamProtocol: "canonical-base-v1" as const, + messages: [{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] } as never], + chatId: "chat-1", + sessionId: "session-1", + accountId: "acc-1", + modelId: "anthropic/claude-haiku-4.5", + sessionTitle: "test session", + repoOwner: "recoupable", + repoName: "api", + agentContext: { + sandbox: { state: { type: "vercel" }, workingDirectory: "/sandbox/mono" }, + } as never, +}; + +const responseMessageWithMetadata = { + id: "asst-msg-1", + role: "assistant", + parts: [{ type: "text", text: "Hello!" }], + metadata: { + totalMessageCost: 0.07, + totalMessageUsage: { inputTokens: 100, cachedInputTokens: 10, outputTokens: 20 }, + }, +} as never; + +vi.mock("../projection/prepareProjectionHistoryStep", () => ({ + prepareProjectionHistoryStep: vi.fn(async messages => ({ + canonical: messages, + native: messages, + })), +})); +vi.mock("../projection/recordProjectionProofStep", () => ({ recordProjectionProofStep: vi.fn() })); +vi.mock("../projection/persistProjectedAssistantStep", () => ({ + persistProjectedAssistantStep: vi.fn(), +})); +vi.mock("../projection/sendProjectionFailureStep", () => ({ sendProjectionFailureStep: vi.fn() })); +const projected = { + ...(responseMessageWithMetadata as object), + id: "assistant", + role: "assistant", + parts: [ + { + type: "data-recoup-sdk-observation", + id: "assistant:projection:0", + data: { originStepId: "step" }, + }, + ], +} as never; +const proof = { + contract: "recoup-sdk-projection/v1", + observations: [{ observation: { data: { originStepId: "step" } } }], +} as never; +beforeEach(() => { + vi.mocked(prepareProjectionHistoryStep) + .mockReset() + .mockImplementation(async messages => ({ canonical: messages, native: messages })); + vi.mocked(recordProjectionProofStep).mockReset(); + vi.mocked(persistProjectedAssistantStep).mockReset(); + vi.mocked(runAgentStep).mockReset().mockResolvedValue({ + finishReason: "stop", + aborted: false, + responseMessages: [], + responseMessage: projected, + generatedProjectionObservations: proof, + }); +}); +it("requires producer then receipt then raw verification then message ACK before one charge", async () => { + await runAgentWorkflow(baseInput); + expect(recordProjectionProofStep).toHaveBeenCalledTimes(1); + expect(prepareProjectionHistoryStep).toHaveBeenCalledTimes(2); + expect(persistProjectedAssistantStep).toHaveBeenCalledTimes(1); + expect(persistAssistantMessageStep).not.toHaveBeenCalled(); + expect(handleChatCredits).toHaveBeenCalledTimes(1); + expect(vi.mocked(recordProjectionProofStep).mock.invocationCallOrder[0]).toBeGreaterThan( + vi.mocked(runAgentStep).mock.invocationCallOrder[0], + ); + expect(vi.mocked(prepareProjectionHistoryStep).mock.invocationCallOrder[1]).toBeGreaterThan( + vi.mocked(recordProjectionProofStep).mock.invocationCallOrder[0], + ); + expect(vi.mocked(handleChatCredits).mock.invocationCallOrder[0]).toBeGreaterThan( + vi.mocked(persistProjectedAssistantStep).mock.invocationCallOrder[0], + ); +}); +it.each(["generation", "receipt", "readback", "persistence"])( + "%s failure never charges, auto-commits, retries provider or emits successful finish", + async kind => { + if (kind === "generation") + vi.mocked(runAgentStep).mockResolvedValue({ + finishReason: "error", + aborted: false, + responseMessage: undefined, + responseMessages: [], + compatibilityFailure: { + code: "evidence_unavailable", + usageComplete: false, + observedMetadata: { totalMessageCost: 0.01 }, + }, + }); + if (kind === "receipt") + vi.mocked(recordProjectionProofStep).mockRejectedValue(new Error("receipt failed")); + if (kind === "readback") + vi.mocked(prepareProjectionHistoryStep) + .mockResolvedValueOnce({ canonical: baseInput.messages, native: baseInput.messages }) + .mockRejectedValueOnce(new Error("readback failed")); + if (kind === "persistence") + vi.mocked(persistProjectedAssistantStep).mockRejectedValue(new Error("unknown ACK")); + await expect(runAgentWorkflow(baseInput)).rejects.toThrow(); + expect(runAgentStep).toHaveBeenCalledTimes(1); + expect(handleChatCredits).not.toHaveBeenCalled(); + expect(autoCommitChatTurn).not.toHaveBeenCalled(); + expect(sendStreamFinish).not.toHaveBeenCalled(); + expect(sendProjectionFailureStep).toHaveBeenCalledTimes(1); + expect(closeChatStream).toHaveBeenCalledTimes(1); + }, +); + +it("charges acknowledged projected Stop once after required gates and skips auto-commit", async () => { + vi.mocked(runAgentStep).mockResolvedValue({ + finishReason: "stop", + aborted: true, + responseMessages: [], + responseMessage: projected, + generatedProjectionObservations: proof, + }); + await runAgentWorkflow(baseInput); + expect(recordProjectionProofStep).toHaveBeenCalledTimes(1); + expect(prepareProjectionHistoryStep).toHaveBeenCalledTimes(2); + expect(persistProjectedAssistantStep).toHaveBeenCalledTimes(1); + expect(handleChatCredits).toHaveBeenCalledTimes(1); + expect(vi.mocked(handleChatCredits).mock.invocationCallOrder[0]).toBeGreaterThan( + vi.mocked(persistProjectedAssistantStep).mock.invocationCallOrder[0], + ); + expect(autoCommitChatTurn).not.toHaveBeenCalled(); + expect(sendProjectionFailureStep).not.toHaveBeenCalled(); +}); +it.each(["first", "later"])( + "signals %s producer rejection as failure, preserving original error", + async iteration => { + const failure = new Error("producer result rejected"); + if (iteration === "later") + vi.mocked(runAgentStep).mockResolvedValueOnce({ + finishReason: "tool-calls", + aborted: false, + responseMessages: [], + responseMessage: projected, + generatedProjectionObservations: proof, + }); + vi.mocked(runAgentStep).mockRejectedValue(failure); + await expect(runAgentWorkflow(baseInput)).rejects.toBe(failure); + expect(sendProjectionFailureStep).toHaveBeenCalledTimes(1); + expect(sendStreamFinish).not.toHaveBeenCalled(); + expect(handleChatCredits).not.toHaveBeenCalled(); + expect(autoCommitChatTurn).not.toHaveBeenCalled(); + }, +); + +it("preserves producer rejection when failure-stream signalling also fails", async () => { + const failure = new Error("producer result missing"); + vi.mocked(runAgentStep).mockRejectedValue(failure); + vi.mocked(sendProjectionFailureStep).mockRejectedValueOnce(new Error("unknown error-finish ACK")); + await expect(runAgentWorkflow(baseInput)).rejects.toBe(failure); + expect(closeChatStream).toHaveBeenCalledTimes(1); + expect(handleChatCredits).not.toHaveBeenCalled(); +}); diff --git a/app/lib/workflows/__tests__/sendStreamStartContinuation.test.ts b/app/lib/workflows/__tests__/sendStreamStartContinuation.test.ts new file mode 100644 index 000000000..056ae3b1d --- /dev/null +++ b/app/lib/workflows/__tests__/sendStreamStartContinuation.test.ts @@ -0,0 +1,59 @@ +import { expect, it } from "vitest"; +import { sendStreamStart } from "../sendStreamStart"; +import type { UIMessageChunk } from "ai"; +function writer() { + const chunks: UIMessageChunk[] = []; + return { + chunks, + stream: new WritableStream({ + write(chunk) { + chunks.push(chunk); + }, + }), + }; +} +it("emits the exact marked canonical base, preserving observation payload/index", async () => { + const base = { + id: "assistant", + role: "assistant" as const, + parts: [ + { type: "text" as const, text: "prior", state: "done" as const }, + { + type: "data-recoup-sdk-observation" as const, + id: "observation", + data: { + original: { type: "custom", kind: "provider-extra", data: { text: "original" } }, + fallback: { partIndex: 2 }, + }, + }, + { + type: "text" as const, + text: "This view cannot display additional model content.", + state: "done" as const, + }, + ], + }; + const { stream, chunks } = writer(); + await sendStreamStart(stream, "assistant", base); + expect(chunks).toEqual([ + { + type: "start", + messageId: "assistant", + messageMetadata: { recoupStream: { version: 1, mode: "continuation", base } }, + }, + ]); + expect(base).not.toHaveProperty("metadata.recoupStream"); +}); +it("leaves fresh starts unmarked", async () => { + const { stream, chunks } = writer(); + await sendStreamStart(stream, "fresh"); + expect(chunks).toEqual([{ type: "start", messageId: "fresh" }]); +}); +it("rejects invalid base before writer acquisition or bytes", async () => { + const { stream, chunks } = writer(); + await expect( + sendStreamStart(stream, "assistant", { id: "other", role: "assistant", parts: [] }), + ).rejects.toThrow(); + expect(chunks).toEqual([]); + expect(stream.locked).toBe(false); +}); diff --git a/app/lib/workflows/projection/assertFirstChatEffectAttempt.ts b/app/lib/workflows/projection/assertFirstChatEffectAttempt.ts new file mode 100644 index 000000000..8162f3f2e --- /dev/null +++ b/app/lib/workflows/projection/assertFirstChatEffectAttempt.ts @@ -0,0 +1,8 @@ +import { FatalError, getStepMetadata } from "workflow"; +/** No completion record means prior effects are unknown; never repeat them on WDK redelivery. */ +export function assertFirstChatEffectAttempt( + effect: "generation" | "message-write" | "failure-stream", +) { + if (getStepMetadata().attempt !== 1) + throw new FatalError(`Chat ${effect} requires reconciliation after an unknown prior attempt`); +} diff --git a/app/lib/workflows/projection/persistProjectedAssistantStep.ts b/app/lib/workflows/projection/persistProjectedAssistantStep.ts new file mode 100644 index 000000000..3a1637e04 --- /dev/null +++ b/app/lib/workflows/projection/persistProjectedAssistantStep.ts @@ -0,0 +1,40 @@ +import { assertFirstChatEffectAttempt } from "./assertFirstChatEffectAttempt"; +import { FatalError } from "workflow"; +import type { UIMessage } from "ai"; +import { encodeProjectionEvidence } from "@/lib/chat/projection/encodeProjectionEvidence"; +/** A projection requires exact message acknowledgement. Unknown outcomes never retry provider/write automatically. */ +export async function persistProjectedAssistantStep(chatId: string, message: UIMessage) { + "use step"; + + assertFirstChatEffectAttempt("message-write"); + try { + const { upsertChatMessage } = await import("@/lib/supabase/chat_messages/upsertChatMessage"); + const result = await upsertChatMessage( + { id: message.id, chat_id: chatId, role: "assistant", parts: message as never }, + { update: true }, + ); + if ( + !result.ok || + !result.row || + result.row.id !== message.id || + result.row.chat_id !== chatId || + result.row.role !== "assistant" || + encodeProjectionEvidence(result.row.parts, 16_777_216) !== + encodeProjectionEvidence(message, 16_777_216) + ) + throw new Error("Unconfirmed message"); + } catch { + throw new FatalError("Required projection persistence requires reconciliation"); + } + // Activity metadata is independent of the confirmed message write. + const activityAt = new Date().toISOString(); + try { + const { updateChat } = await import("@/lib/supabase/chats/updateChat"); + await updateChat( + { id: chatId }, + { updated_at: activityAt, last_assistant_message_at: activityAt }, + ); + } catch { + /* Message ACK remains valid. */ + } +} diff --git a/app/lib/workflows/projection/prepareProjectionHistoryStep.ts b/app/lib/workflows/projection/prepareProjectionHistoryStep.ts new file mode 100644 index 000000000..c31c6a6d0 --- /dev/null +++ b/app/lib/workflows/projection/prepareProjectionHistoryStep.ts @@ -0,0 +1,16 @@ +import { FatalError } from "workflow"; +import type { UIMessage } from "ai"; +import { prepareAuthorizedProjectionHistory } from "@/lib/chat/projection/prepareAuthorizedProjectionHistory"; +import type { ProjectionAuthority } from "@/lib/chat/projection/ProjectionEvidencePorts"; +/** Runs after trusted workflow admission/bind and before any history write or seed. */ +export async function prepareProjectionHistoryStep( + messages: UIMessage[], + scope: ProjectionAuthority, +) { + "use step"; + try { + return await prepareAuthorizedProjectionHistory(messages, scope, AbortSignal.timeout(5000)); + } catch { + throw new FatalError("Projection history evidence unavailable"); + } +} diff --git a/app/lib/workflows/projection/recordProjectionProofStep.ts b/app/lib/workflows/projection/recordProjectionProofStep.ts new file mode 100644 index 000000000..1263e8b3b --- /dev/null +++ b/app/lib/workflows/projection/recordProjectionProofStep.ts @@ -0,0 +1,34 @@ +import { encodeProjectionEvidence } from "@/lib/chat/projection/encodeProjectionEvidence"; +import { projectionReceiptSchema } from "@/lib/chat/projection/projectionSchemas"; +import { ProjectionEvidenceError } from "@/lib/chat/projection/ProjectionEvidenceError"; +/** Workflow must await the completed producer before this deterministic, effect-free step. */ +export async function recordProjectionProofStep(producerStepId: string, observations: unknown) { + "use step"; + + try { + const output = projectionReceiptSchema.parse( + JSON.parse( + encodeProjectionEvidence( + { + contract: "recoup-sdk-projection-proof/v1", + producerStepId, + generatedProjectionObservations: observations, + }, + 16_777_216, + ), + ), + ); + for (const item of output.generatedProjectionObservations.observations) + encodeProjectionEvidence(item.observation); + if ( + output.generatedProjectionObservations.observations.some( + item => item.observation.data.originStepId !== producerStepId, + ) + ) + throw new Error("Mismatched producer"); + return output; + } catch (error) { + if (error instanceof ProjectionEvidenceError) throw error; + throw new ProjectionEvidenceError("invalid_evidence"); + } +} diff --git a/app/lib/workflows/projection/sendProjectionFailureStep.ts b/app/lib/workflows/projection/sendProjectionFailureStep.ts new file mode 100644 index 000000000..54788b5c9 --- /dev/null +++ b/app/lib/workflows/projection/sendProjectionFailureStep.ts @@ -0,0 +1,21 @@ +import { assertFirstChatEffectAttempt } from "./assertFirstChatEffectAttempt"; +import { FatalError } from "workflow"; +import type { UIMessageChunk } from "ai"; +/** Explicit failure, never Stop or an unqualified successful finish. No automatic stream reappend. */ +export async function sendProjectionFailureStep(writable: WritableStream) { + "use step"; + + assertFirstChatEffectAttempt("failure-stream"); + const writer = writable.getWriter(); + try { + await writer.write({ + type: "error", + errorText: "Required generation evidence is unavailable. This turn needs reconciliation.", + }); + await writer.write({ type: "finish", finishReason: "error" }); + } catch { + throw new FatalError("Projection failure stream acknowledgement unavailable"); + } finally { + writer.releaseLock(); + } +} diff --git a/app/lib/workflows/projection/validateContinuationBaseStep.ts b/app/lib/workflows/projection/validateContinuationBaseStep.ts new file mode 100644 index 000000000..f99c0eb4d --- /dev/null +++ b/app/lib/workflows/projection/validateContinuationBaseStep.ts @@ -0,0 +1,12 @@ +import { buildContinuationMarker } from "@/lib/chat/continuation/buildContinuationMarker"; +import type { UIMessage } from "ai"; +import { FatalError } from "workflow"; +/** Validate after bound history authority, before any message mutation or model work. */ +export async function validateContinuationBaseStep(base: UIMessage): Promise { + "use step"; + try { + await buildContinuationMarker(base, base.id); + } catch { + throw new FatalError("Continuation base is invalid"); + } +} diff --git a/app/lib/workflows/runAgentStep.ts b/app/lib/workflows/runAgentStep.ts index f1b8525e8..a721dc201 100644 --- a/app/lib/workflows/runAgentStep.ts +++ b/app/lib/workflows/runAgentStep.ts @@ -1,3 +1,11 @@ +import { assertFirstChatEffectAttempt } from "./projection/assertFirstChatEffectAttempt"; +import { collectCanonicalProjection } from "@/lib/chat/projection/collectCanonicalProjection"; +import { + ProjectionEvidenceError, + type ProjectionEvidenceCode, +} from "@/lib/chat/projection/ProjectionEvidenceError"; +import type { ProjectionProof } from "@/lib/chat/projection/projectionSchemas"; +import { buildToolsContext } from "@/lib/agent/tools/buildToolsContext"; import { streamText, type ModelMessage, type UIMessage, type UIMessageChunk } from "ai"; import { gateway } from "@ai-sdk/gateway"; import { agentCustomInstructions } from "@/lib/chat/agentCustomInstructions"; @@ -13,7 +21,7 @@ import { pollWorkflowCancellation } from "@/lib/chat/pollWorkflowCancellation"; import { closeOpenToolCalls } from "@/lib/chat/closeOpenToolCalls"; import { isAbortError } from "@/lib/chat/isAbortError"; import { isRunCancelled } from "@/lib/chat/isRunCancelled"; -import { getWorkflowMetadata } from "workflow"; +import { getWorkflowMetadata, getStepMetadata } from "workflow"; export type RunAgentStepInput = { /** @@ -29,6 +37,7 @@ export type RunAgentStepInput = { * cumulative and each persist overwrites one row. */ originalMessages: UIMessage[]; + nativeOriginalMessages?: UIMessage[]; modelId: string; reasoningEffort?: "low" | "medium" | "high"; writable: WritableStream; @@ -72,6 +81,13 @@ export type RunAgentStepInput = { export type RunAgentStepResult = { finishReason: string; + nativeResponseMessage?: UIMessage; + generatedProjectionObservations?: ProjectionProof; + compatibilityFailure?: { + code: ProjectionEvidenceCode; + observedMetadata?: AgentMessageMetadata; + usageComplete: boolean; + }; /** * The assembled assistant message captured from the stream's `onFinish`, * cumulative across iterations via `originalMessages`. `undefined` if the @@ -86,7 +102,7 @@ export type RunAgentStepResult = { * next iteration continues the conversation instead of repeating it. */ responseMessages: ModelMessage[]; - /** True when the user stopped the run; `runAgentWorkflow` skips billing + auto-commit on abort. */ + /** True for confirmed user-stop; existing usage billing remains, auto-commit is skipped. */ aborted: boolean; }; @@ -113,6 +129,8 @@ export type RunAgentStepResult = { export async function runAgentStep(input: RunAgentStepInput): Promise { "use step"; + assertFirstChatEffectAttempt("generation"); + console.log("[runAgentStep] start", { modelId: input.modelId, messageCount: input.modelMessages.length, @@ -166,11 +184,11 @@ export async function runAgentStep(input: RunAgentStepInput): Promise = event => { + const metadata = buildMetadata(event); + if (metadata) observedMetadata = metadata; + return metadata; + }; + // Drive the stream directly and write each part to the shared writable, // mirroring upstream open-agents. There is deliberately no // `createUIMessageStream` wrapper: its only draw was `onStepFinish` for @@ -195,67 +220,120 @@ export async function runAgentStep(input: RunAgentStepInput): Promise + message.parts.some(part => part.type === "data-recoup-sdk-observation"), + ); let finishReason: string; let responseMessages: ModelMessage[] = []; try { - for await (const part of result.toUIMessageStream({ - messageMetadata, - generateMessageId: () => input.assistantMessageId, - // Continue building the in-progress assistant message rather than - // starting a new one, so `responseMessage` stays cumulative across - // iterations and each persist overwrites a single row. - originalMessages: input.originalMessages, - // The turn's `start`/`finish` chunks are emitted ONCE by the workflow - // body (`sendStreamStart` / `sendStreamFinish`). Without this the client - // would see one per iteration and render N assistant messages. - sendStart: false, - sendFinish: false, - onFinish: ({ responseMessage: finalMessage }) => { - responseMessage = finalMessage; + const canonical = await collectCanonicalProjection({ + previous: + previousMessage?.role === "assistant" + ? previousMessage + : { id: input.assistantMessageId, role: "assistant", parts: [] }, + runId: workflowRunId, + stepId: () => getStepMetadata().stepId, + isCancellation: async error => + isAbortError(error) || + cancelController.signal.aborted || + (await isRunCancelled(workflowRunId)), + onProjection: () => { + projected = true; }, - })) { - // A writer lock taken inside a step applies only within that step, so - // sequential steps can share one stream. Release per part so the step's - // request can terminate. - const writer = input.writable.getWriter(); - try { - await writer.write(part); - } finally { - writer.releaseLock(); - } - } + stream: result.toUIMessageStream({ + messageMetadata, + generateMessageId: () => input.assistantMessageId, + // Continue building the in-progress assistant message rather than + // starting a new one, so `responseMessage` stays cumulative across + // iterations and each persist overwrites a single row. + originalMessages: input.nativeOriginalMessages ?? input.originalMessages, + // The turn's `start`/`finish` chunks are emitted ONCE by the workflow + // body (`sendStreamStart` / `sendStreamFinish`). Without this the client + // would see one per iteration and render N assistant messages. + sendStart: false, + sendFinish: false, + onEnd: ({ responseMessage: finalMessage }) => { + nativeResponseMessage = finalMessage; + responseMessage = finalMessage; + }, + }), + write: async part => { + // A writer lock taken inside a step applies only within that step, so + // sequential steps can share one stream. Release per part so the step's + // request can terminate. + const writer = input.writable.getWriter(); + try { + await writer.write(part); + } finally { + writer.releaseLock(); + } + }, + }); + if (projected) responseMessage = canonical.message; + if (canonical.generatedProjectionObservations.observations.length) + generatedProjectionObservations = canonical.generatedProjectionObservations; + + if (canonical.cancelled) throw new DOMException("Confirmed user Stop", "AbortError"); - // `response.messages` is the assistant message for this call plus any - // tool-result message — exactly what the next iteration needs appended. - // (`result.responseMessages` is ai@7; this repo is on 6.0.190.) - const [reason, response] = await Promise.all([result.finishReason, result.response]); + // v7 exposes the complete generated history separately from response metadata. + const [reason, messages] = await Promise.all([result.finishReason, result.responseMessages]); finishReason = reason; - responseMessages = response.messages; + responseMessages = messages; } catch (error) { + // A typed projection/write failure stays a failure even when cancellation also + // fires. Mere presence of verified projected history is not a failure latch. + const confirmedStop = + !(error instanceof ProjectionEvidenceError) && + (isAbortError(error) || + cancelController.signal.aborted || + (await isRunCancelled(workflowRunId))); + if (error instanceof ProjectionEvidenceError || (projected && !confirmedStop)) { + cancelController.abort(); + void Promise.resolve(result.finishReason).catch(() => {}); + void Promise.resolve(result.responseMessages).catch(() => {}); + return { + finishReason: "error", + responseMessage: undefined, + responseMessages: [], + aborted: false, + compatibilityFailure: { + code: error instanceof ProjectionEvidenceError ? error.code : "evidence_unavailable", + observedMetadata, + usageComplete: false, + }, + }; + } // Three ways a user-stop surfaces here: the stream throws AbortError; the // poller already flipped our signal; or `run.cancel()` closed the workflow // writable underneath us and the write threw something unrelated before // the poller noticed. Confirm the last case against the run itself so a // genuine failure still propagates. - if ( - !isAbortError(error) && - !cancelController.signal.aborted && - !(await isRunCancelled(workflowRunId)) - ) - throw error; + if (!confirmedStop) throw error; - // User-stop. `result.finishReason` / `result.response` reject once + // User-stop. `result.finishReason` / `result.responseMessages` reject once // streamText aborts — swallow them so they don't surface as unhandled. void Promise.resolve(result.finishReason).catch(() => {}); - void Promise.resolve(result.response).catch(() => {}); + void Promise.resolve(result.responseMessages).catch(() => {}); finishReason = "stop"; // Close any tool-call parts left without a terminal result, otherwise a // reload renders them spinning forever. The workflow body persists it. - if (responseMessage) responseMessage = closeOpenToolCalls(responseMessage); + if (responseMessage) { + responseMessage = closeOpenToolCalls(responseMessage); + if (projected && observedMetadata) + responseMessage = { ...responseMessage, metadata: observedMetadata }; + } console.log("[runAgentStep] aborted", { hasResponseMessage: !!responseMessage }); - return { finishReason, responseMessage, responseMessages: [], aborted: true }; + return { + finishReason, + responseMessage, + responseMessages: [], + aborted: true, + ...(projected ? { nativeResponseMessage, generatedProjectionObservations } : {}), + }; } finally { poller.stop(); cancelController.abort(); @@ -267,5 +345,11 @@ export async function runAgentStep(input: RunAgentStepInput): Promise message.role === "user"); - if (!latestUser) throw new FatalError("Fenced turn requires a user message"); - await persistFencedMessageStep(writer, "user", latestUser); - } + const history = await prepareProjectionHistoryStep(input.messages, { + accountId: input.accountId, + chatId: input.chatId, + sessionId: input.sessionId, + }); // Pick or generate a stable id for the assistant message. If the // last message in the conversation is already an assistant message // (we're resuming an in-progress turn after a tool-call interaction) @@ -138,7 +151,7 @@ export async function runAgentWorkflow( // pattern in `apps/web/app/workflows/chat.ts` where the id is // generated in the workflow body and threaded into every // `runAgentStep` call. - const latestMessage = input.messages.at(-1); + const latestMessage = history.canonical.at(-1); if ( bound?.turn.kind === "same-turn-resume" && (input.devCatalogSurface || @@ -146,12 +159,20 @@ export async function runAgentWorkflow( latestMessage.id !== bound.turn.assistantId) ) throw new FatalError("Fenced resume identity mismatch"); - if (writer && bound?.turn.kind === "same-turn-resume" && latestMessage) - // Existence + current message generation must be proven before any provider work. - await persistFencedMessageStep(writer, "update_parts", latestMessage); const reuseAssistant = writer ? bound?.turn.kind === "same-turn-resume" : !input.devCatalogSurface && latestMessage?.role === "assistant"; + if (reuseAssistant && input.streamProtocol !== "canonical-base-v1") + throw new FatalError("Continuation protocol requirement unavailable"); + if (reuseAssistant && latestMessage) await validateContinuationBaseStep(latestMessage); + if (writer) { + const latestUser = history.canonical.findLast(message => message.role === "user"); + if (!latestUser) throw new FatalError("Fenced turn requires a user message"); + await persistFencedMessageStep(writer, "user", latestUser); + } + if (writer && bound?.turn.kind === "same-turn-resume" && latestMessage) + // Existence + current message generation must be proven before any provider work. + await persistFencedMessageStep(writer, "update_parts", latestMessage); const assistantMessageId = reuseAssistant && latestMessage?.role === "assistant" ? latestMessage.id @@ -160,21 +181,28 @@ export async function runAgentWorkflow( // Convert once, before the loop. The workflow body owns this array and // appends every iteration's `responseMessages` to it, which is how // iteration N+1 sees iteration N's tool results. - const modelMessages = await convertMessagesStep(input.messages); + const modelMessages = await convertMessagesStep(history.native); // The assistant message under construction. Threaded into each iteration // as `originalMessages` so the AI SDK keeps appending to it instead of // starting a new message, and so the turn's running usage totals carry // across iterations. let pendingAssistantResponse: UIMessage = - (writer ? reuseAssistant : latestMessage?.role === "assistant") && - latestMessage?.role === "assistant" + reuseAssistant && latestMessage?.role === "assistant" ? latestMessage : { id: assistantMessageId, role: "assistant", parts: [] }; + let nativePendingAssistantResponse = reuseAssistant + ? history.native.at(-1) + : pendingAssistantResponse; + // One `start` chunk for the whole turn — each iteration's stream is told // `sendStart: false`, so without this the client renders N messages. - await sendStreamStart(writable, assistantMessageId); + await sendStreamStart( + writable, + assistantMessageId, + reuseAssistant ? pendingAssistantResponse : undefined, + ); legacyCleanupEntered = !writer; // Tracks whether the terminal `finish` chunk has gone out, so the cleanup @@ -204,7 +232,7 @@ export async function runAgentWorkflow( input.modelId === "auto" ? savedRouting ? { modelId: savedRouting.modelId, routing: savedRouting } - : await routeChatModelStep(input.messages, writable) + : await routeChatModelStep(history.native, writable) : { modelId: input.modelId }; if ("metadata" in selection) { pendingAssistantResponse = { @@ -226,30 +254,71 @@ export async function runAgentWorkflow( // it and the queue retried it 4 times, each attempt a full agent run // that mailed the customer again (chat#1918). for (let iteration = 0; iteration < CHAT_AGENT_MAX_ITERATIONS; iteration++) { - result = await runAgentStep({ - // Snapshot, not the live array — each iteration's input is a durable - // step input and must describe the conversation as it was at THAT - // call, unaffected by later appends. - modelMessages: [...modelMessages], - originalMessages: [pendingAssistantResponse], - modelId: selection.modelId, - reasoningEffort: "routing" in selection ? selection.routing?.reasoningEffort : undefined, - accountId: input.accountId, - artistId: input.artistId, - interactive: input.interactive, - agentContext: input.agentContext, - writable, - assistantMessageId, - }); + try { + result = await runAgentStep({ + // Snapshot, not the live array — each iteration's input is a durable + // step input and must describe the conversation as it was at THAT + // call, unaffected by later appends. + modelMessages: [...modelMessages], + originalMessages: [pendingAssistantResponse], + nativeOriginalMessages: nativePendingAssistantResponse + ? [nativePendingAssistantResponse] + : undefined, + modelId: selection.modelId, + reasoningEffort: "routing" in selection ? selection.routing?.reasoningEffort : undefined, + accountId: input.accountId, + artistId: input.artistId, + interactive: input.interactive, + agentContext: input.agentContext, + writable, + assistantMessageId, + }); + } catch (error) { + // No producer result means proof/usage may be unavailable even after output. + projectionFailure = true; + throw error; + } + if (result.compatibilityFailure) { + projectionFailure = true; + throw new FatalError( + `Required projection generation failed: ${result.compatibilityFailure.code}`, + ); + } + if (result.generatedProjectionObservations) { + projectionFailure = true; + const producerStepId = + result.generatedProjectionObservations.observations[0]?.observation.data.originStepId; + if (!producerStepId) throw new FatalError("Required projection proof missing"); + await recordProjectionProofStep(producerStepId, result.generatedProjectionObservations); + } + nativePendingAssistantResponse = result.nativeResponseMessage ?? result.responseMessage; if (result.responseMessage) { pendingAssistantResponse = result.responseMessage; + if ( + pendingAssistantResponse.parts.some(part => part.type === "data-recoup-sdk-observation") + ) { + projectionFailure = true; + // A completed producer/receipt is not a stream storage ACK. Fresh raw readback + // and configured deployment admission are required before the message write. + await prepareProjectionHistoryStep([pendingAssistantResponse], { + accountId: input.accountId, + chatId: input.chatId, + sessionId: input.sessionId, + }); + } // Persist per iteration so a long turn's transcript stays live rather // than landing only at the end. The stable assistantMessageId makes // each write overwrite the same row. if (writer) await persistFencedMessageStep(writer, "assistant", pendingAssistantResponse); - else await persistAssistantMessageStep(input.chatId, pendingAssistantResponse); + else if ( + pendingAssistantResponse.parts.some(part => part.type === "data-recoup-sdk-observation") + ) { + projectionFailure = true; + await persistProjectedAssistantStep(input.chatId, pendingAssistantResponse); + } else await persistAssistantMessageStep(input.chatId, pendingAssistantResponse); } + projectionFailure = false; modelMessages.push(...result.responseMessages); // A turn continues only while the model asked for more tools. Any @@ -317,47 +386,63 @@ export async function runAgentWorkflow( await sendStreamFinish(writable); streamFinished = true; } + } catch (error) { + hasPrimaryFailure = true; + throw error; } finally { - if (writer) { - // No legacy slot clear/key revoke. The writer's CAS release is success-only. - // On required failure the original bound state remains for explicit reconciliation. - await closeChatStream(writable); - } else if (legacyCleanupEntered) { - // Run two cleanup steps in parallel: - // 1) `clearChatActiveStream` — CAS-gated DB clear of the chat's - // `active_stream_id` so the recovery probe flips to false. - // 2) `closeChatStream` — explicitly close the workflow writable - // so the client's SSE response ends NOW. Without this, the - // writable stays open until Vercel Workflow's runtime - // garbage-collects the run (observed ~2m), and the AI SDK - // chat hook keeps `chat.status` in `submitted` waiting for - // stream-end. Mirrors open-agents' - // `Promise.all([clearActiveStream, sendFinish.then(closeStream)])`. - // - // A third cleanup step runs only for headless `/api/chat/runs` runs: - // 3) `deleteEphemeralKeyStep` — revoke the per-run, account-scoped - // `recoup_sk_…` key minted for the sandbox the moment the run ends. - // The key's ~15m TTL is only the backstop if this delete is missed. - // - // `Promise.all` is safe because all helpers swallow their own errors — - // a failure in one doesn't cancel the others. - // `finish` must precede the close on EVERY exit path. A stream that ends - // without it leaves the client in-flight forever — `useChat` waits for the - // terminal chunk and `WorkflowChatTransport` loops `while (!gotFinish)` — - // and once the run is terminal the resume route 204s, so the chunk is - // unreachable after the fact. Guarded by `streamFinished` so a successful - // turn does not emit two. Mirrors open-agents `chat.ts` L939 / L968-971: - // `sendFinish(writable).then(() => closeStream(writable))`. - await Promise.all([ - clearChatActiveStream(input.chatId, workflowRunId), - (async () => { - if (!streamFinished) await sendStreamFinish(writable); + try { + if (writer) { + // No legacy slot clear/key revoke. The writer's CAS release is success-only. + // On required failure the original bound state remains for explicit reconciliation. + try { + if (projectionFailure) await sendProjectionFailureStep(writable); + } finally { await closeChatStream(writable); - })(), - ...(input.agentContext.ephemeralKeyId - ? [deleteEphemeralKeyStep(input.agentContext.ephemeralKeyId)] - : []), - ]); + } + } else if (legacyCleanupEntered) { + // Run two cleanup steps in parallel: + // 1) `clearChatActiveStream` — CAS-gated DB clear of the chat's + // `active_stream_id` so the recovery probe flips to false. + // 2) `closeChatStream` — explicitly close the workflow writable + // so the client's SSE response ends NOW. Without this, the + // writable stays open until Vercel Workflow's runtime + // garbage-collects the run (observed ~2m), and the AI SDK + // chat hook keeps `chat.status` in `submitted` waiting for + // stream-end. Mirrors open-agents' + // `Promise.all([clearActiveStream, sendFinish.then(closeStream)])`. + // + // A third cleanup step runs only for headless `/api/chat/runs` runs: + // 3) `deleteEphemeralKeyStep` — revoke the per-run, account-scoped + // `recoup_sk_…` key minted for the sandbox the moment the run ends. + // The key's ~15m TTL is only the backstop if this delete is missed. + // + // `Promise.all` is safe because all helpers swallow their own errors — + // a failure in one doesn't cancel the others. + // `finish` must precede the close on EVERY exit path. A stream that ends + // without it leaves the client in-flight forever — `useChat` waits for the + // terminal chunk and `WorkflowChatTransport` loops `while (!gotFinish)` — + // and once the run is terminal the resume route 204s, so the chunk is + // unreachable after the fact. Guarded by `streamFinished` so a successful + // turn does not emit two. Mirrors open-agents `chat.ts` L939 / L968-971: + // `sendFinish(writable).then(() => closeStream(writable))`. + await Promise.all([ + clearChatActiveStream(input.chatId, workflowRunId), + (async () => { + try { + if (projectionFailure) await sendProjectionFailureStep(writable); + else if (!streamFinished) await sendStreamFinish(writable); + } finally { + await closeChatStream(writable); + } + })(), + ...(input.agentContext.ephemeralKeyId + ? [deleteEphemeralKeyStep(input.agentContext.ephemeralKeyId)] + : []), + ]); + } + } catch (cleanupError) { + if (!hasPrimaryFailure) throw cleanupError; + // Failure signalling itself can be unavailable; retain the original failure. } } } diff --git a/app/lib/workflows/sendStreamStart.ts b/app/lib/workflows/sendStreamStart.ts index 6c203155d..5731cd954 100644 --- a/app/lib/workflows/sendStreamStart.ts +++ b/app/lib/workflows/sendStreamStart.ts @@ -1,4 +1,5 @@ -import type { UIMessageChunk } from "ai"; +import { buildContinuationMarker } from "@/lib/chat/continuation/buildContinuationMarker"; +import type { UIMessage, UIMessageChunk } from "ai"; /** * Emit the single `start` chunk that opens an assistant turn. @@ -13,12 +14,20 @@ import type { UIMessageChunk } from "ai"; export async function sendStreamStart( writable: WritableStream, messageId: string, + canonicalBase?: UIMessage, ): Promise { "use step"; + const marker = canonicalBase + ? await buildContinuationMarker(canonicalBase, messageId) + : undefined; const writer = writable.getWriter(); try { - await writer.write({ type: "start", messageId }); + await writer.write({ + type: "start", + messageId, + ...(marker ? { messageMetadata: { recoupStream: marker } } : {}), + }); } finally { writer.releaseLock(); } diff --git a/lib/agent/buildAgentTools.ts b/lib/agent/buildAgentTools.ts index 1ca91a2db..4980ab716 100644 --- a/lib/agent/buildAgentTools.ts +++ b/lib/agent/buildAgentTools.ts @@ -14,7 +14,7 @@ import type { SkillMetadata } from "@/lib/skills/skillTypes"; /** * Factory for the full agent tool set passed into `streamText({ tools })`. * Each tool reads its sandbox handle + per-prompt context from - * `experimental_context` at execute time — the factory is otherwise stateless. + * `toolsContext` at execute time — the factory is otherwise stateless. * * Currently ships 11 tools: * diff --git a/lib/agent/contextManagement/__tests__/wrapToolsWithAbortIterable.test.ts b/lib/agent/contextManagement/__tests__/wrapToolsWithAbortIterable.test.ts new file mode 100644 index 000000000..fb0d35ef9 --- /dev/null +++ b/lib/agent/contextManagement/__tests__/wrapToolsWithAbortIterable.test.ts @@ -0,0 +1,224 @@ +import { describe, expect, it, vi } from "vitest"; +import { generateText, tool } from "ai"; +import { MockLanguageModelV4 } from "ai/test"; +import { z } from "zod"; +import { wrapToolsWithAbort, ToolAbortedError } from "../wrapToolsWithAbort"; + +const options = { toolCallId: "fixture-call", messages: [], context: {} }; +function generatorTool(execute: () => AsyncGenerator) { + return tool({ inputSchema: z.object({}), execute }); +} +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(r => { + resolve = r; + }); + return { promise, resolve }; +} + +describe("abort wrapper with installed SDK async iterable execution", () => { + it("executes a wrapped generator once through the real SDK and uses its final yield", async () => { + let entered = 0; + let cleaned = 0; + const model = new MockLanguageModelV4({ + doGenerate: { + content: [{ type: "tool-call", toolCallId: "fixture-call", toolName: "task", input: "{}" }], + finishReason: { unified: "tool-calls", raw: undefined }, + warnings: [], + usage: { + inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 }, + outputTokens: { total: 1, text: 1, reasoning: 0 }, + }, + }, + }); + const task = generatorTool(async function* () { + entered++; + try { + yield "pending"; + yield "completed child result"; + } finally { + cleaned++; + } + }); + const result = await generateText({ + model, + prompt: "run task", + tools: wrapToolsWithAbort({ task }, new AbortController().signal), + }); + expect(entered).toBe(1); + expect(cleaned).toBe(1); + expect(result.toolResults[0].output).toBe("completed child result"); + }); + + it("does not start an already aborted generator", async () => { + const execute = vi.fn(async function* () { + yield "unexpected"; + }); + const controller = new AbortController(); + controller.abort(); + const wrapped = wrapToolsWithAbort({ task: generatorTool(execute) }, controller.signal); + await expect(wrapped.task.execute!({}, options)).rejects.toBeInstanceOf(ToolAbortedError); + expect(execute).not.toHaveBeenCalled(); + }); + + it("aborts pending iteration promptly and eventually closes a cooperative generator once", async () => { + const gate = deferred(); + let cleanup = 0; + const task = generatorTool(async function* () { + try { + yield "pending"; + await gate.promise; + yield "late"; + } finally { + cleanup++; + } + }); + const controller = new AbortController(); + const wrapped = wrapToolsWithAbort({ task }, controller.signal); + const result = wrapped.task.execute!({}, options); + expect(Symbol.asyncIterator in Object(result)).toBe(true); + const iterator = (result as AsyncIterable)[Symbol.asyncIterator](); + expect(await iterator.next()).toEqual({ value: "pending", done: false }); + const pending = iterator.next(); + controller.abort(); + await expect(pending).rejects.toBeInstanceOf(ToolAbortedError); + gate.resolve(); + await vi.waitFor(() => expect(cleanup).toBe(1)); + }); + + it("forwards consumer return and exposes cleanup failures", async () => { + const failure = new Error("cleanup failure"); + let cleanup = 0; + const wrapped = wrapToolsWithAbort( + { + task: generatorTool(async function* () { + try { + yield "pending"; + } finally { + cleanup++; + throw failure; + } + }), + }, + new AbortController().signal, + ); + const result = wrapped.task.execute!({}, options); + expect(Symbol.asyncIterator in Object(result)).toBe(true); + const iterator = (result as AsyncIterable)[Symbol.asyncIterator](); + await iterator.next(); + await expect(iterator.return!()).rejects.toBe(failure); + expect(cleanup).toBe(1); + }); + + it("allows cleanup to yield before finishing a consumer return", async () => { + let cleaned = false; + const wrapped = wrapToolsWithAbort( + { + task: generatorTool(async function* () { + try { + yield "pending"; + } finally { + yield "cleaning"; + cleaned = true; + } + }), + }, + new AbortController().signal, + ); + const iterator = (wrapped.task.execute!({}, options) as AsyncIterable)[ + Symbol.asyncIterator + ](); + await iterator.next(); + expect(await iterator.return!()).toEqual({ done: false, value: "cleaning" }); + expect((await iterator.next()).done).toBe(true); + expect(cleaned).toBe(true); + }); + + it("bounds fallback throw when an iterator has no throw and cleanup does not settle", async () => { + const cleanupGate = deferred>(); + const close = vi.fn(() => cleanupGate.promise); + const source: AsyncIterable = { + [Symbol.asyncIterator]: () => ({ + next: async () => ({ done: false, value: "pending" }), + return: close, + }), + }; + const controller = new AbortController(); + const wrapped = wrapToolsWithAbort( + { task: tool({ inputSchema: z.object({}), execute: () => source }) }, + controller.signal, + ); + const iterator = (wrapped.task.execute!({}, options) as AsyncIterable)[ + Symbol.asyncIterator + ](); + await iterator.next(); + const failure = new Error("consumer failure"); + const pending = iterator.throw!(failure).then( + () => undefined, + error => error, + ); + await vi.waitFor(() => expect(close).toHaveBeenCalledOnce()); + controller.abort(); + let timer: ReturnType | undefined; + try { + const result = await Promise.race([ + pending, + new Promise(resolve => { + timer = setTimeout(() => resolve("hung"), 100); + }), + ]); + expect(result).toBeInstanceOf(ToolAbortedError); + } finally { + clearTimeout(timer); + cleanupGate.resolve({ done: true, value: undefined }); + await pending; + } + expect(close).toHaveBeenCalledOnce(); + }); + + it("preserves the consumer error after fallback cleanup without abort", async () => { + const close = vi.fn(async () => ({ done: true as const, value: undefined })); + const source: AsyncIterable = { + [Symbol.asyncIterator]: () => ({ + next: async () => ({ done: false, value: "pending" }), + return: close, + }), + }; + const wrapped = wrapToolsWithAbort( + { task: tool({ inputSchema: z.object({}), execute: () => source }) }, + new AbortController().signal, + ); + const iterator = (wrapped.task.execute!({}, options) as AsyncIterable)[ + Symbol.asyncIterator + ](); + await iterator.next(); + const failure = new Error("consumer failure"); + await expect(iterator.throw!(failure)).rejects.toBe(failure); + expect(close).toHaveBeenCalledOnce(); + }); + + it("forwards consumer throw to the generator and preserves its final result", async () => { + const failure = new Error("consumer failure"); + const received = vi.fn(); + const wrapped = wrapToolsWithAbort( + { + task: generatorTool(async function* () { + try { + yield "pending"; + } catch (error) { + received(error); + yield "recovered"; + } + }), + }, + new AbortController().signal, + ); + const result = wrapped.task.execute!({}, options); + expect(Symbol.asyncIterator in Object(result)).toBe(true); + const iterator = (result as AsyncIterable)[Symbol.asyncIterator](); + await iterator.next(); + expect(await iterator.throw!(failure)).toEqual({ done: false, value: "recovered" }); + expect(received).toHaveBeenCalledWith(failure); + expect((await iterator.next()).done).toBe(true); + }); +}); diff --git a/lib/agent/contextManagement/raceToolExecution.ts b/lib/agent/contextManagement/raceToolExecution.ts new file mode 100644 index 000000000..77a4e4c5c --- /dev/null +++ b/lib/agent/contextManagement/raceToolExecution.ts @@ -0,0 +1,21 @@ +/** Race one promise or iterator operation, observing late rejection and releasing its listener. */ +export async function raceToolExecution( + result: T | PromiseLike, + signal: AbortSignal, + createAbortError: () => Error, +): Promise { + if (signal.aborted) { + void Promise.resolve(result).catch(() => {}); + throw createAbortError(); + } + let onAbort: (() => void) | undefined; + const aborted = new Promise((_, reject) => { + onAbort = () => reject(createAbortError()); + signal.addEventListener("abort", onAbort, { once: true }); + }); + try { + return await Promise.race([result, aborted]); + } finally { + if (onAbort) signal.removeEventListener("abort", onAbort); + } +} diff --git a/lib/agent/contextManagement/wrapToolAsyncIterable.ts b/lib/agent/contextManagement/wrapToolAsyncIterable.ts new file mode 100644 index 000000000..404c956e3 --- /dev/null +++ b/lib/agent/contextManagement/wrapToolAsyncIterable.ts @@ -0,0 +1,71 @@ +import { raceToolExecution } from "./raceToolExecution"; + +/** Preserve an observable iterable and forward iterator control while bounding abort latency. */ +export function wrapToolAsyncIterable( + source: AsyncIterable, + signal: AbortSignal, + createAbortError: () => Error, +): AsyncIterable { + return { + [Symbol.asyncIterator]() { + const iterator = source[Symbol.asyncIterator](); + let ended = false; + let abortCleanupRequested = false; + let closing: Promise> | undefined; + function close(value?: unknown): Promise> { + if (closing) return closing; + if (ended) return Promise.resolve({ done: true, value }); + closing = Promise.resolve() + .then(() => (iterator.return ? iterator.return(value) : { done: true as const, value })) + .then(step => { + if (step.done) ended = true; + return step; + }) + .finally(() => { + closing = undefined; + }); + return closing; + } + function requestAbortCleanup() { + if (abortCleanupRequested) return; + abortCleanupRequested = true; + void close().catch(() => {}); + } + async function advance( + method: "next" | "throw", + value?: unknown, + ): Promise> { + if (ended) { + if (method === "throw") throw value; + return { done: true, value: undefined }; + } + if (signal.aborted) { + requestAbortCleanup(); + throw createAbortError(); + } + try { + const pending = method === "next" ? iterator.next(value) : iterator.throw!(value); + const step = await raceToolExecution(pending, signal, createAbortError); + if (step.done) ended = true; + return step; + } catch (error) { + if (signal.aborted) { + // return() may queue behind a non-cooperative next(). Request cleanup + // once, observe its failure, but never make user-stop wait for it. + requestAbortCleanup(); + } else ended = true; + throw error; + } + } + return { + next: value => advance("next", value), + return: value => raceToolExecution(close(value), signal, createAbortError), + throw: async error => { + if (iterator.throw) return advance("throw", error); + await raceToolExecution(close(), signal, createAbortError); + throw error; + }, + }; + }, + }; +} diff --git a/lib/agent/contextManagement/wrapToolsWithAbort.ts b/lib/agent/contextManagement/wrapToolsWithAbort.ts index e845e3c95..818552de0 100644 --- a/lib/agent/contextManagement/wrapToolsWithAbort.ts +++ b/lib/agent/contextManagement/wrapToolsWithAbort.ts @@ -1,3 +1,5 @@ +import { raceToolExecution } from "./raceToolExecution"; +import { wrapToolAsyncIterable } from "./wrapToolAsyncIterable"; import type { ToolSet } from "ai"; export class ToolAbortedError extends Error { @@ -8,7 +10,8 @@ export class ToolAbortedError extends Error { } /** - * Races every tool's `execute` promise against `signal`. On abort, even tools + * Preserves synchronous async-iterable results and races each operation against `signal`. + * On abort, even tools * that ignore their own abortSignal reject with {@link ToolAbortedError} so * `streamText` can move on instead of hanging the agent loop. */ @@ -20,23 +23,29 @@ export function wrapToolsWithAbort(tools: T, signal: AbortSig wrapped[name] = tool; continue; } - const originalExecute = execute.bind(tool) as ( - input: unknown, - options: unknown, - ) => Promise; + const originalExecute = execute.bind(tool) as (input: unknown, options: unknown) => unknown; wrapped[name] = { ...tool, - execute: async (input: unknown, options: unknown) => { - if (signal.aborted) throw new ToolAbortedError(name); - let onAbort: (() => void) | undefined; - const abortPromise = new Promise((_, reject) => { - onAbort = () => reject(new ToolAbortedError(name)); - signal.addEventListener("abort", onAbort, { once: true }); - }); + execute: (input: unknown, options: unknown) => { + const createAbortError = () => new ToolAbortedError(name); + if (signal.aborted) return Promise.reject(createAbortError()); try { - return await Promise.race([originalExecute(input, options), abortPromise]); - } finally { - if (onAbort) signal.removeEventListener("abort", onAbort); + const result = originalExecute(input, options); + if ( + result !== null && + typeof result === "object" && + Symbol.asyncIterator in result && + typeof result[Symbol.asyncIterator] === "function" + ) { + return wrapToolAsyncIterable( + result as AsyncIterable, + signal, + createAbortError, + ); + } + return raceToolExecution(result, signal, createAbortError); + } catch (error) { + return Promise.reject(error); } }, } as T[keyof T]; diff --git a/lib/agent/messageMetadata/__tests__/addLanguageModelUsage.test.ts b/lib/agent/messageMetadata/__tests__/addLanguageModelUsage.test.ts index 4ba0b0234..879cad8c4 100644 --- a/lib/agent/messageMetadata/__tests__/addLanguageModelUsage.test.ts +++ b/lib/agent/messageMetadata/__tests__/addLanguageModelUsage.test.ts @@ -2,6 +2,20 @@ import { describe, it, expect } from "vitest"; import { addLanguageModelUsage } from "@/lib/agent/messageMetadata/addLanguageModelUsage"; describe("addLanguageModelUsage", () => { + it("preserves flat persisted v6 cache and reasoning tokens when adding a v7 step", () => { + const result = addLanguageModelUsage( + { inputTokens: 100, outputTokens: 50, cachedInputTokens: 10, reasoningTokens: 5 } as never, + { + inputTokens: 200, + outputTokens: 75, + inputTokenDetails: { cacheReadTokens: 20 }, + outputTokenDetails: { reasoningTokens: 15 }, + } as never, + ); + expect(result.inputTokenDetails.cacheReadTokens).toBe(30); + expect(result.outputTokenDetails.reasoningTokens).toBe(20); + }); + it("sums basic input/output/total tokens", () => { const result = addLanguageModelUsage( { inputTokens: 100, outputTokens: 50, totalTokens: 150 }, diff --git a/lib/agent/messageMetadata/__tests__/normalizeLanguageModelUsage.test.ts b/lib/agent/messageMetadata/__tests__/normalizeLanguageModelUsage.test.ts new file mode 100644 index 000000000..155b97cf3 --- /dev/null +++ b/lib/agent/messageMetadata/__tests__/normalizeLanguageModelUsage.test.ts @@ -0,0 +1,28 @@ +import { expect, it } from "vitest"; +import { normalizeLanguageModelUsage } from "../normalizeLanguageModelUsage"; + +it("keeps known legacy counts without inventing unknown token details", () => { + const usage = normalizeLanguageModelUsage({ + inputTokens: 100, + cachedInputTokens: 12, + reasoningTokens: 3, + }); + expect(usage.inputTokenDetails).toEqual({ + noCacheTokens: undefined, + cacheReadTokens: 12, + cacheWriteTokens: undefined, + }); + expect(usage.outputTokenDetails).toEqual({ textTokens: undefined, reasoningTokens: 3 }); + expect(usage.totalTokens).toBeUndefined(); +}); + +it("prefers explicit nested zero over conflicting flat legacy values", () => { + const usage = normalizeLanguageModelUsage({ + cachedInputTokens: 12, + reasoningTokens: 3, + inputTokenDetails: { noCacheTokens: 100, cacheReadTokens: 0, cacheWriteTokens: 0 }, + outputTokenDetails: { textTokens: 5, reasoningTokens: 0 }, + }); + expect(usage.inputTokenDetails.cacheReadTokens).toBe(0); + expect(usage.outputTokenDetails.reasoningTokens).toBe(0); +}); diff --git a/lib/agent/messageMetadata/addLanguageModelUsage.ts b/lib/agent/messageMetadata/addLanguageModelUsage.ts index 4a676364f..5073c952c 100644 --- a/lib/agent/messageMetadata/addLanguageModelUsage.ts +++ b/lib/agent/messageMetadata/addLanguageModelUsage.ts @@ -1,9 +1,9 @@ +import { normalizeLanguageModelUsage } from "./normalizeLanguageModelUsage"; import type { LanguageModelUsage } from "ai"; import { addTokenCounts } from "@/lib/agent/messageMetadata/addTokenCounts"; /** - * Pointwise-sum two `LanguageModelUsage` records (the flat shape used by - * `ai@^6.0.190`). Mirrors `packages/agent/usage.ts:addLanguageModelUsage` + * Pointwise-sum two AI SDK v7 `LanguageModelUsage` records. Mirrors `packages/agent/usage.ts:addLanguageModelUsage` * in the open-agents source. Used to accumulate per-step usage into a * per-message total inside the `messageMetadata` callback. * @@ -15,6 +15,8 @@ export function addLanguageModelUsage( a: LanguageModelUsage, b: LanguageModelUsage, ): LanguageModelUsage { + a = normalizeLanguageModelUsage(a); + b = normalizeLanguageModelUsage(b); return { inputTokens: addTokenCounts(a.inputTokens, b.inputTokens), inputTokenDetails: { @@ -43,7 +45,5 @@ export function addLanguageModelUsage( ), }, totalTokens: addTokenCounts(a.totalTokens, b.totalTokens), - reasoningTokens: addTokenCounts(a.reasoningTokens, b.reasoningTokens), - cachedInputTokens: addTokenCounts(a.cachedInputTokens, b.cachedInputTokens), }; } diff --git a/lib/agent/messageMetadata/buildMessageMetadataCallback.ts b/lib/agent/messageMetadata/buildMessageMetadataCallback.ts index e5c8b229a..1d3006add 100644 --- a/lib/agent/messageMetadata/buildMessageMetadataCallback.ts +++ b/lib/agent/messageMetadata/buildMessageMetadataCallback.ts @@ -12,9 +12,8 @@ import type { AgentStepFinishMetadata } from "@/lib/agent/messageMetadata/AgentS * * Mirrors open-agents' `apps/web/app/workflows/chat.ts` callback shape * so sandbox.recoupable.com's UI can render model/cost/usage badges - * when cut over to api's `/api/chat/workflow`. api and open-agents now - * share the same `ai@^6.0.190` shape for `LanguageModelUsage`, so no - * shape conversion happens here. + * when cut over to api's `/api/chat/workflow`. Usage is emitted in the + * installed v7 nested-detail shape; paired App compatibility is a release gate. * * Each call to `buildMessageMetadataCallback` returns a FRESH closure — * one per assistant turn — so totals reset between turns. diff --git a/lib/agent/messageMetadata/normalizeLanguageModelUsage.ts b/lib/agent/messageMetadata/normalizeLanguageModelUsage.ts new file mode 100644 index 000000000..d557acc47 --- /dev/null +++ b/lib/agent/messageMetadata/normalizeLanguageModelUsage.ts @@ -0,0 +1,21 @@ +import type { LanguageModelUsage } from "ai"; + +/** Normalize saved v6 usage and live v7 usage; nested counts take precedence, including zero. */ +export function normalizeLanguageModelUsage( + usage: Partial & { cachedInputTokens?: number; reasoningTokens?: number }, +): LanguageModelUsage { + return { + inputTokens: usage.inputTokens, + outputTokens: usage.outputTokens, + totalTokens: usage.totalTokens, + inputTokenDetails: { + noCacheTokens: usage.inputTokenDetails?.noCacheTokens, + cacheReadTokens: usage.inputTokenDetails?.cacheReadTokens ?? usage.cachedInputTokens, + cacheWriteTokens: usage.inputTokenDetails?.cacheWriteTokens, + }, + outputTokenDetails: { + textTokens: usage.outputTokenDetails?.textTokens, + reasoningTokens: usage.outputTokenDetails?.reasoningTokens ?? usage.reasoningTokens, + }, + }; +} diff --git a/lib/agent/tools/AgentContext.ts b/lib/agent/tools/AgentContext.ts index 64d2b7e01..0d4a0a097 100644 --- a/lib/agent/tools/AgentContext.ts +++ b/lib/agent/tools/AgentContext.ts @@ -4,7 +4,7 @@ import type { SkillMetadata } from "@/lib/skills/skillTypes"; /** * Per-tool-call context threaded into the agent via `streamText`'s - * `experimental_context`. Mirrors the open-agents `AgentContext` + * `toolsContext`. Mirrors the open-agents `AgentContext` * interface (`packages/agent/types.ts`) one-for-one. The only * deviation is structural: `model` / `subagentModel` are * `LanguageModel` instances that cannot ride through a durable @@ -13,7 +13,7 @@ import type { SkillMetadata } from "@/lib/skills/skillTypes"; * * The durable workflow-input shape is `DurableAgentContext` below — * `runAgentStep` widens that into a full `AgentContext` by attaching - * the constructed model(s) before `experimental_context` is observed + * the constructed model(s) before `toolsContext` is observed * by any tool. * * `recoupAccessToken` carries a short-lived Privy JWT (~1h TTL) so diff --git a/lib/agent/tools/__tests__/agentContextSchema.test.ts b/lib/agent/tools/__tests__/agentContextSchema.test.ts new file mode 100644 index 000000000..70b0d823f --- /dev/null +++ b/lib/agent/tools/__tests__/agentContextSchema.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { buildAgentTools } from "../../buildAgentTools"; +import { asSchema } from "ai"; + +describe("server tool context declarations", () => { + it.each(["bash", "read", "write", "edit", "grep", "glob", "web_fetch", "task"] as const)( + "%s declares and validates context separately from model input", + async name => { + const tools = buildAgentTools(); + const schema = tools[name].contextSchema; + expect(schema).toBeDefined(); + const validated = await asSchema(schema!).validate!({ sandbox: null }); + expect(validated.success).toBe(false); + }, + ); +}); diff --git a/lib/agent/tools/__tests__/bashTool.test.ts b/lib/agent/tools/__tests__/bashTool.test.ts index 568a7f72d..58e596449 100644 --- a/lib/agent/tools/__tests__/bashTool.test.ts +++ b/lib/agent/tools/__tests__/bashTool.test.ts @@ -36,7 +36,7 @@ describe("bashTool.execute", () => { const tool = bashTool; const result = await tool.execute!({ command: "ls" }, { - experimental_context: baseContext, + context: baseContext, } as never); expect(result).toEqual({ success: true, @@ -66,7 +66,7 @@ describe("bashTool.execute", () => { const tool = bashTool; const result = (await tool.execute!({ command: "find ." }, { - experimental_context: baseContext, + context: baseContext, } as never)) as { truncated?: boolean }; expect(result.truncated).toBe(true); }); @@ -85,7 +85,7 @@ describe("bashTool.execute", () => { const tool = bashTool; await tool.execute!({ command: "ls", cwd: "apps/web" }, { - experimental_context: baseContext, + context: baseContext, } as never); expect(sandbox.exec).toHaveBeenCalledWith( "ls", @@ -109,7 +109,7 @@ describe("bashTool.execute", () => { const tool = bashTool; await tool.execute!({ command: "curl example.com" }, { - experimental_context: { ...baseContext, recoupOrgId: "org-uuid" }, + context: { ...baseContext, recoupOrgId: "org-uuid" }, } as never); const opts = sandbox.exec.mock.calls[0]?.[3] as { env?: Record }; expect(opts.env).toEqual({ RECOUP_ORG_ID: "org-uuid" }); @@ -123,7 +123,7 @@ describe("bashTool.execute", () => { const tool = bashTool; const result = (await tool.execute!({ command: "npm run dev", detached: true }, { - experimental_context: baseContext, + context: baseContext, } as never)) as { success: boolean; stdout: string }; expect(result.success).toBe(true); expect(result.stdout).toMatch(/cmd-123/); @@ -136,7 +136,7 @@ describe("bashTool.execute", () => { const tool = bashTool; const result = (await tool.execute!({ command: "npm run dev", detached: true }, { - experimental_context: baseContext, + context: baseContext, } as never)) as { success: boolean; stderr: string }; expect(result.success).toBe(false); expect(result.stderr).toMatch(/detached mode is not supported/i); @@ -150,7 +150,7 @@ describe("bashTool.execute", () => { const tool = bashTool; await tool.execute!({ command: "npm run dev", detached: true }, { - experimental_context: { ...baseContext, recoupOrgId: "org-uuid" }, + context: { ...baseContext, recoupOrgId: "org-uuid" }, } as never); // execDetached signature is (command, cwd) — no env arg. expect(sandbox.execDetached.mock.calls[0]).toHaveLength(2); diff --git a/lib/agent/tools/__tests__/editFileTool.test.ts b/lib/agent/tools/__tests__/editFileTool.test.ts index 3a2cac81d..5fc2f3bd0 100644 --- a/lib/agent/tools/__tests__/editFileTool.test.ts +++ b/lib/agent/tools/__tests__/editFileTool.test.ts @@ -29,7 +29,7 @@ describe("editFileTool", () => { const tool = editFileTool; const result = (await tool.execute!( { filePath: "a.txt", oldString: "old value", newString: "new value" }, - { experimental_context: ctx } as never, + { context: ctx } as never, )) as { success: boolean; replacements: number; startLine: number }; expect(result.success).toBe(true); expect(result.replacements).toBe(1); @@ -42,7 +42,7 @@ describe("editFileTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = editFileTool; const result = (await tool.execute!({ filePath: "a.txt", oldString: "x", newString: "x" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/must be different/); @@ -54,7 +54,7 @@ describe("editFileTool", () => { const tool = editFileTool; const result = (await tool.execute!( { filePath: "a.txt", oldString: "missing", newString: "other" }, - { experimental_context: ctx } as never, + { context: ctx } as never, )) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/not found/); @@ -65,7 +65,7 @@ describe("editFileTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = editFileTool; const result = (await tool.execute!({ filePath: "a.txt", oldString: "foo", newString: "baz" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/2 times/); @@ -77,7 +77,7 @@ describe("editFileTool", () => { const tool = editFileTool; const result = (await tool.execute!( { filePath: "a.txt", oldString: "foo", newString: "qux", replaceAll: true }, - { experimental_context: ctx } as never, + { context: ctx } as never, )) as { success: boolean; replacements: number }; expect(result.success).toBe(true); expect(result.replacements).toBe(3); diff --git a/lib/agent/tools/__tests__/globTool.test.ts b/lib/agent/tools/__tests__/globTool.test.ts index 3f35d0a71..967b6e905 100644 --- a/lib/agent/tools/__tests__/globTool.test.ts +++ b/lib/agent/tools/__tests__/globTool.test.ts @@ -30,7 +30,7 @@ describe("globTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = globTool; const result = (await tool.execute!({ pattern: "**/*.ts" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; count: number; @@ -55,7 +55,7 @@ describe("globTool", () => { ); vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = globTool; - await tool.execute!({ pattern: "**/*.ts" }, { experimental_context: ctx } as never); + await tool.execute!({ pattern: "**/*.ts" }, { context: ctx } as never); const cmd = sb.exec.mock.calls[0]?.[0] as string; expect(cmd).not.toContain("-maxdepth"); }); @@ -72,7 +72,7 @@ describe("globTool", () => { ); vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = globTool; - await tool.execute!({ pattern: "*.json" }, { experimental_context: ctx } as never); + await tool.execute!({ pattern: "*.json" }, { context: ctx } as never); expect(sb.exec.mock.calls[0]?.[0]).toMatch(/-maxdepth\s+1/); }); @@ -89,7 +89,7 @@ describe("globTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = globTool; const result = (await tool.execute!({ pattern: "**/*.ts" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/exit 2/); diff --git a/lib/agent/tools/__tests__/grepTool.test.ts b/lib/agent/tools/__tests__/grepTool.test.ts index e3545f501..f8d654371 100644 --- a/lib/agent/tools/__tests__/grepTool.test.ts +++ b/lib/agent/tools/__tests__/grepTool.test.ts @@ -29,7 +29,7 @@ describe("grepTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = grepTool; const result = (await tool.execute!({ pattern: "login", path: "src" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; matches: Array<{ file: string; line: number; content: string }>; @@ -58,7 +58,7 @@ describe("grepTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = grepTool; const result = (await tool.execute!({ pattern: "nothing", path: "src" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; matchCount: number }; expect(result.success).toBe(true); expect(result.matchCount).toBe(0); @@ -77,7 +77,7 @@ describe("grepTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = grepTool; const result = (await tool.execute!({ pattern: "[", path: "src" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/invalid regex/); @@ -96,7 +96,7 @@ describe("grepTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = grepTool; await tool.execute!({ pattern: "x", path: ".", caseSensitive: false }, { - experimental_context: ctx, + context: ctx, } as never); expect(sb.exec.mock.calls[0]?.[0]).toContain(" -i "); }); diff --git a/lib/agent/tools/__tests__/readFileTool.test.ts b/lib/agent/tools/__tests__/readFileTool.test.ts index 6d1d27fa3..39ca44e51 100644 --- a/lib/agent/tools/__tests__/readFileTool.test.ts +++ b/lib/agent/tools/__tests__/readFileTool.test.ts @@ -32,7 +32,7 @@ describe("readFileTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = readFileTool; const result = (await tool.execute!({ filePath: "README.md" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; content: string; totalLines: number; path: string }; expect(result.success).toBe(true); expect(result.totalLines).toBe(3); @@ -50,7 +50,7 @@ describe("readFileTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = readFileTool; const result = (await tool.execute!({ filePath: "x.txt", offset: 2, limit: 2 }, { - experimental_context: ctx, + context: ctx, } as never)) as { content: string; startLine: number; endLine: number }; expect(result.startLine).toBe(2); // `endLine` is the last line included (1-indexed). With offset=2,limit=2 @@ -68,7 +68,7 @@ describe("readFileTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = readFileTool; const result = (await tool.execute!({ filePath: "src" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/directory/i); @@ -81,7 +81,7 @@ describe("readFileTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = readFileTool; const result = (await tool.execute!({ filePath: "missing.ts" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/not found/); diff --git a/lib/agent/tools/__tests__/sdkV7Runtime.test.ts b/lib/agent/tools/__tests__/sdkV7Runtime.test.ts new file mode 100644 index 000000000..276b84c26 --- /dev/null +++ b/lib/agent/tools/__tests__/sdkV7Runtime.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it, vi } from "vitest"; +import { generateText, isStepCount, streamText, tool } from "ai"; +import { MockLanguageModelV4, convertArrayToReadableStream } from "ai/test"; +import { z } from "zod"; +import { buildToolsContext } from "../buildToolsContext"; +import type { AgentContext } from "../AgentContext"; +import { buildMessageMetadataCallback } from "../../messageMetadata/buildMessageMetadataCallback"; + +const usage = { + inputTokens: { total: 10, noCache: 6, cacheRead: 3, cacheWrite: 1 }, + outputTokens: { total: 5, text: 3, reasoning: 2 }, +}; + +describe("installed v7 runtime contracts (no provider calls)", () => { + it("passes server context by tool name without putting it in model inputs and retains all steps", async () => { + const execute = vi.fn(async (_input: { value: string }, options: { context: AgentContext }) => { + expect(options.context.recoupAccessToken).toBe("fixture-private-context"); + return "checked"; + }); + const tools = { + inspect: tool({ inputSchema: z.object({ value: z.string() }), execute }), + }; + const model = new MockLanguageModelV4({ + doGenerate: [ + { + content: [ + { + type: "tool-call", + toolCallId: "call-1", + toolName: "inspect", + input: '{"value":"test"}', + }, + ], + finishReason: { unified: "tool-calls", raw: undefined }, + usage, + warnings: [], + }, + { + content: [{ type: "text", text: "done" }], + finishReason: { unified: "stop", raw: undefined }, + usage, + warnings: [], + }, + ], + }); + const context: AgentContext = { + sandbox: { state: {}, workingDirectory: "." }, + model, + recoupAccessToken: "fixture-private-context", + }; + const result = await generateText({ + model, + tools, + toolsContext: buildToolsContext(tools, context), + prompt: "inspect test", + stopWhen: isStepCount(2), + }); + expect(execute).toHaveBeenCalledOnce(); + expect(result.responseMessages.map(message => message.role)).toEqual([ + "assistant", + "tool", + "assistant", + ]); + expect(JSON.stringify(model.doGenerateCalls)).not.toContain("fixture-private-context"); + expect(result.usage.inputTokenDetails.cacheReadTokens).toBe(6); + expect(result.usage.outputTokenDetails.reasoningTokens).toBe(4); + }); + + it("emits cumulative nested usage metadata and omits per-step start/finish chunks", async () => { + const model = new MockLanguageModelV4({ + doStream: { + stream: convertArrayToReadableStream([ + { type: "stream-start", warnings: [] }, + { type: "text-start", id: "text-1" }, + { type: "text-delta", id: "text-1", delta: "done" }, + { type: "text-end", id: "text-1" }, + { type: "finish", finishReason: { unified: "stop", raw: undefined }, usage }, + ]), + }, + }); + const result = streamText({ model, prompt: "hello" }); + const chunks = []; + const onEnd = vi.fn(); + for await (const chunk of result.toUIMessageStream({ + sendStart: false, + sendFinish: false, + generateMessageId: () => "stable-assistant", + onEnd, + messageMetadata: buildMessageMetadataCallback({ modelId: "fixture" }), + })) + chunks.push(chunk); + expect(chunks.some(chunk => chunk.type === "start" || chunk.type === "finish")).toBe(false); + expect(chunks).toContainEqual( + expect.objectContaining({ + type: "message-metadata", + messageMetadata: expect.objectContaining({ + totalMessageUsage: expect.objectContaining({ + inputTokens: 10, + outputTokens: 5, + inputTokenDetails: { noCacheTokens: 6, cacheReadTokens: 3, cacheWriteTokens: 1 }, + outputTokenDetails: { textTokens: 3, reasoningTokens: 2 }, + }), + }), + }), + ); + expect(onEnd).toHaveBeenCalledOnce(); + expect(onEnd.mock.calls[0][0].responseMessage.id).toBe("stable-assistant"); + }); +}); diff --git a/lib/agent/tools/__tests__/skillTool.test.ts b/lib/agent/tools/__tests__/skillTool.test.ts index 0b3196dbc..7a110e27d 100644 --- a/lib/agent/tools/__tests__/skillTool.test.ts +++ b/lib/agent/tools/__tests__/skillTool.test.ts @@ -24,7 +24,7 @@ describe("skillTool", () => { it("returns success:false with available skills when the requested skill isn't in context", async () => { vi.mocked(connectVercel).mockResolvedValue(makeSandbox(vi.fn()) as never); const result = (await skillTool.execute!({ skill: "unknown" }, { - experimental_context: { + context: { ...baseCtx, skills: [ { @@ -51,7 +51,7 @@ describe("skillTool", () => { it("returns success:false when no skills are loaded", async () => { vi.mocked(connectVercel).mockResolvedValue(makeSandbox(vi.fn()) as never); const result = (await skillTool.execute!({ skill: "commit" }, { - experimental_context: { ...baseCtx, skills: [] }, + context: { ...baseCtx, skills: [] }, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/Available skills: none/); @@ -63,7 +63,7 @@ describe("skillTool", () => { const result = (await skillTool.execute!( { skill: "COMMIT" }, // model typed it loud { - experimental_context: { + context: { ...baseCtx, skills: [ { @@ -85,7 +85,7 @@ describe("skillTool", () => { const sb = makeSandbox(vi.fn().mockResolvedValue(skillMd("Run git commit -m ..."))); vi.mocked(connectVercel).mockResolvedValue(sb as never); const result = (await skillTool.execute!({ skill: "commit" }, { - experimental_context: { + context: { ...baseCtx, skills: [ { @@ -109,7 +109,7 @@ describe("skillTool", () => { const sb = makeSandbox(vi.fn().mockResolvedValue(skillMd('git commit -m "$ARGUMENTS"'))); vi.mocked(connectVercel).mockResolvedValue(sb as never); const result = (await skillTool.execute!({ skill: "commit", args: "fix bug" }, { - experimental_context: { + context: { ...baseCtx, skills: [ { @@ -129,7 +129,7 @@ describe("skillTool", () => { it("rejects skills with disable-model-invocation set", async () => { vi.mocked(connectVercel).mockResolvedValue(makeSandbox(vi.fn()) as never); const result = (await skillTool.execute!({ skill: "internal" }, { - experimental_context: { + context: { ...baseCtx, skills: [ { @@ -150,7 +150,7 @@ describe("skillTool", () => { const sb = makeSandbox(vi.fn().mockRejectedValue(new Error("ENOENT"))); vi.mocked(connectVercel).mockResolvedValue(sb as never); const result = (await skillTool.execute!({ skill: "commit" }, { - experimental_context: { + context: { ...baseCtx, skills: [ { diff --git a/lib/agent/tools/__tests__/taskTool.test.ts b/lib/agent/tools/__tests__/taskTool.test.ts index 8e876afdb..3a36148cc 100644 --- a/lib/agent/tools/__tests__/taskTool.test.ts +++ b/lib/agent/tools/__tests__/taskTool.test.ts @@ -28,7 +28,7 @@ function makeStreamResult(opts: { const calls = opts.toolCalls ?? []; const finishCount = opts.finishSteps ?? 1; return { - fullStream: (async function* () { + stream: (async function* () { for (const c of calls) { yield { type: "tool-call", toolName: c.toolName, input: c.input }; } @@ -39,7 +39,7 @@ function makeStreamResult(opts: { }; } })(), - response: Promise.resolve({ messages: opts.responseMessages ?? [] }), + responseMessages: Promise.resolve(opts.responseMessages ?? []), totalUsage: Promise.resolve(opts.totalUsage ?? { inputTokens: 0, outputTokens: 0 }), finishReason: Promise.resolve("stop"), }; @@ -60,7 +60,7 @@ describe("taskTool.execute (async generator)", () => { it("yields an initial chunk with toolCallCount=0 + startedAt + modelId before the subagent does any work", async () => { vi.mocked(streamText).mockReturnValue(makeStreamResult({}) as never); const gen = taskTool.execute!({ task: "x", instructions: "y" }, { - experimental_context: ctx, + context: ctx, } as never) as AsyncGenerator; const first = await gen.next(); expect(first.done).toBe(false); @@ -86,7 +86,7 @@ describe("taskTool.execute (async generator)", () => { ); const chunks = (await drainGenerator( taskTool.execute!({ task: "x", instructions: "y" }, { - experimental_context: ctx, + context: ctx, } as never) as AsyncGenerator, )) as TaskToolOutput[]; // Two tool-call yields + one finish-step yield (sticky pending so the @@ -110,7 +110,7 @@ describe("taskTool.execute (async generator)", () => { ); const chunks = (await drainGenerator( taskTool.execute!({ task: "x", instructions: "y" }, { - experimental_context: ctx, + context: ctx, } as never) as AsyncGenerator, )) as TaskToolOutput[]; const usageChunks = chunks.filter(c => c.usage); @@ -129,7 +129,7 @@ describe("taskTool.execute (async generator)", () => { vi.mocked(streamText).mockReturnValue(makeStreamResult({ responseMessages }) as never); const chunks = (await drainGenerator( taskTool.execute!({ task: "x", instructions: "y" }, { - experimental_context: ctx, + context: ctx, } as never) as AsyncGenerator, )) as TaskToolOutput[]; const finalChunk = chunks.find(c => c.final); @@ -143,7 +143,7 @@ describe("taskTool.execute (async generator)", () => { vi.mocked(streamText).mockReturnValue(makeStreamResult({}) as never); await drainGenerator( taskTool.execute!({ task: "x", instructions: "y" }, { - experimental_context: { ...ctx, subagentModel: subagentModelOverride }, + context: { ...ctx, subagentModel: subagentModelOverride }, } as never) as AsyncGenerator, ); const args = vi.mocked(streamText).mock.calls[0]?.[0] as { model: unknown }; @@ -152,7 +152,7 @@ describe("taskTool.execute (async generator)", () => { it("throws when agent context is missing the `model` field", async () => { const gen = taskTool.execute!({ task: "x", instructions: "y" }, { - experimental_context: { sandbox: ctx.sandbox /* no model */ }, + context: { sandbox: ctx.sandbox /* no model */ }, } as never) as AsyncGenerator; await expect(gen.next()).rejects.toThrow(/model not initialized/i); }); @@ -161,7 +161,7 @@ describe("taskTool.execute (async generator)", () => { vi.mocked(streamText).mockReturnValue(makeStreamResult({}) as never); await drainGenerator( taskTool.execute!({ task: "x", instructions: "y" }, { - experimental_context: ctx, + context: ctx, } as never) as AsyncGenerator, ); const args = vi.mocked(streamText).mock.calls[0]?.[0] as { tools: Record }; @@ -179,7 +179,7 @@ describe("taskTool.execute (async generator)", () => { vi.mocked(streamText).mockReturnValue(makeStreamResult({}) as never); await drainGenerator( taskTool.execute!({ task: "x", instructions: "y" }, { - experimental_context: ctx, + context: ctx, } as never) as AsyncGenerator, ); const args = vi.mocked(streamText).mock.calls[0]?.[0] as { diff --git a/lib/agent/tools/__tests__/webFetchTool.test.ts b/lib/agent/tools/__tests__/webFetchTool.test.ts index 47fb75c92..7d8c11be6 100644 --- a/lib/agent/tools/__tests__/webFetchTool.test.ts +++ b/lib/agent/tools/__tests__/webFetchTool.test.ts @@ -28,7 +28,7 @@ describe("webFetchTool", () => { ); vi.mocked(connectVercel).mockResolvedValue(sb as never); const result = (await webFetchTool.execute!({ url: "https://example.com/api" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; status: number; body: string; truncated: boolean }; expect(result).toEqual({ success: true, @@ -50,7 +50,7 @@ describe("webFetchTool", () => { ); vi.mocked(connectVercel).mockResolvedValue(sb as never); const result = (await webFetchTool.execute!({ url: "https://example.com/huge" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; truncated: boolean }; expect(result.success).toBe(true); expect(result.truncated).toBe(true); @@ -68,7 +68,7 @@ describe("webFetchTool", () => { ); vi.mocked(connectVercel).mockResolvedValue(sb as never); const result = (await webFetchTool.execute!({ url: "https://example.com/unreachable" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/Failed to connect/); @@ -87,7 +87,7 @@ describe("webFetchTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); await webFetchTool.execute!( { url: "https://example.com/api", method: "POST", body: '{"x":1}' }, - { experimental_context: ctx } as never, + { context: ctx } as never, ); const cmd = sb.exec.mock.calls[0]?.[0] as string; expect(cmd).toContain("-X POST"); diff --git a/lib/agent/tools/__tests__/wrappedTaskSdk.test.ts b/lib/agent/tools/__tests__/wrappedTaskSdk.test.ts new file mode 100644 index 000000000..49632f2a8 --- /dev/null +++ b/lib/agent/tools/__tests__/wrappedTaskSdk.test.ts @@ -0,0 +1,133 @@ +import { expect, it, vi } from "vitest"; +import { generateText, streamText } from "ai"; +import { MockLanguageModelV4 } from "ai/test"; +import { taskTool } from "../taskTool"; +import { buildToolsContext } from "../buildToolsContext"; +import { wrapToolsWithAbort } from "../../contextManagement/wrapToolsWithAbort"; + +vi.mock("ai", async () => ({ + ...(await vi.importActual("ai")), + streamText: vi.fn(), +})); + +it("runs the actual wrapped task generator through the installed SDK instead of emitting a fallback", async () => { + const model = new MockLanguageModelV4({ + doGenerate: { + content: [ + { + type: "tool-call", + toolCallId: "task-call", + toolName: "task", + input: '{"task":"inspect","instructions":"inspect fixture"}', + }, + ], + finishReason: { unified: "tool-calls", raw: undefined }, + warnings: [], + usage: { + inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 }, + outputTokens: { total: 1, text: 1, reasoning: 0 }, + }, + }, + }); + let childStreamEntered = 0; + vi.mocked(streamText).mockReturnValue({ + stream: (async function* () { + childStreamEntered++; + yield { type: "finish-step", usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 } }; + })(), + responseMessages: Promise.resolve([ + { role: "assistant", content: [{ type: "text", text: "actual child completed" }] }, + ]), + } as never); + const tools = wrapToolsWithAbort({ task: taskTool }, new AbortController().signal); + const result = await generateText({ + model, + prompt: "run child", + tools, + toolsContext: buildToolsContext(tools, { + model, + sandbox: { state: {}, workingDirectory: "." }, + }), + }); + expect(streamText).toHaveBeenCalledOnce(); + expect(childStreamEntered).toBe(1); + expect(result.toolResults[0].output).toMatchObject({ + final: [{ role: "assistant", content: [{ type: "text", text: "actual child completed" }] }], + usage: { inputTokens: 2, outputTokens: 3 }, + }); + expect(JSON.stringify(result.responseMessages)).toContain("actual child completed"); + expect(JSON.stringify(result.responseMessages)).not.toContain("Task completed."); +}); + +it("aborts the actual child stream during iteration and runs cleanup once", async () => { + vi.mocked(streamText).mockClear(); + const controller = new AbortController(); + let entered = 0; + let cleaned = 0; + let release!: () => void; + const gate = new Promise(resolve => { + release = resolve; + }); + const model = new MockLanguageModelV4({ + doGenerate: { + content: [ + { + type: "tool-call", + toolCallId: "task-call", + toolName: "task", + input: '{"task":"inspect","instructions":"inspect fixture"}', + }, + ], + finishReason: { unified: "tool-calls", raw: undefined }, + warnings: [], + usage: { + inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 }, + outputTokens: { total: 1, text: 1, reasoning: 0 }, + }, + }, + }); + vi.mocked(streamText).mockReturnValue({ + stream: (async function* () { + entered++; + try { + await gate; + } finally { + cleaned++; + } + })(), + responseMessages: Promise.resolve([]), + totalUsage: Promise.resolve({ inputTokens: 0, outputTokens: 0, totalTokens: 0 }), + } as never); + const tools = wrapToolsWithAbort({ task: taskTool }, controller.signal); + const pending = generateText({ + model, + prompt: "run child", + tools, + abortSignal: controller.signal, + toolsContext: buildToolsContext(tools, { + model, + sandbox: { state: {}, workingDirectory: "." }, + }), + }); + // Observe rejection before abort so this probe cannot introduce an unhandled rejection. + const outcome = pending.then( + value => ({ value }), + error => ({ error }), + ); + await vi.waitFor(() => expect(entered).toBe(1)); + controller.abort(); + const settled = await outcome; + release(); + await vi.waitFor(() => expect(cleaned).toBe(1)); + if (!("value" in settled)) throw settled.error; + expect(settled.value.toolResults).toEqual([]); + expect(settled.value.steps[0].content).toContainEqual( + expect.objectContaining({ + type: "tool-error", + error: expect.objectContaining({ name: "ToolAbortedError" }), + }), + ); + expect(JSON.stringify(settled.value.responseMessages)).not.toContain("Task completed."); + expect(streamText).toHaveBeenCalledOnce(); + expect(vi.mocked(streamText).mock.calls[0][0].abortSignal?.aborted).toBe(true); +}); diff --git a/lib/agent/tools/__tests__/writeFileTool.test.ts b/lib/agent/tools/__tests__/writeFileTool.test.ts index 3656a777c..138088b9d 100644 --- a/lib/agent/tools/__tests__/writeFileTool.test.ts +++ b/lib/agent/tools/__tests__/writeFileTool.test.ts @@ -28,7 +28,7 @@ describe("writeFileTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = writeFileTool; const result = (await tool.execute!({ filePath: "src/index.ts", content: "export {}" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; path: string; bytesWritten: number }; expect(result.success).toBe(true); expect(result.path).toBe("src/index.ts"); @@ -44,7 +44,7 @@ describe("writeFileTool", () => { vi.mocked(connectVercel).mockResolvedValue(sb as never); const tool = writeFileTool; const result = (await tool.execute!({ filePath: "a.ts", content: "x" }, { - experimental_context: ctx, + context: ctx, } as never)) as { success: boolean; error: string }; expect(result.success).toBe(false); expect(result.error).toMatch(/EACCES/); diff --git a/lib/agent/tools/agentContextSchema.ts b/lib/agent/tools/agentContextSchema.ts new file mode 100644 index 000000000..cc8ec031c --- /dev/null +++ b/lib/agent/tools/agentContextSchema.ts @@ -0,0 +1,6 @@ +import { z } from "zod"; +import type { AgentContext } from "./AgentContext"; +import { isAgentContext } from "./isAgentContext"; + +/** Server-only context validation; preserves model instances and sandbox state by reference. */ +export const agentContextSchema = z.custom(isAgentContext, "Invalid agent context"); diff --git a/lib/agent/tools/bashTool.ts b/lib/agent/tools/bashTool.ts index 479a608db..59bade1b6 100644 --- a/lib/agent/tools/bashTool.ts +++ b/lib/agent/tools/bashTool.ts @@ -1,5 +1,7 @@ -import { tool } from "ai"; +import { agentContextSchema } from "./agentContextSchema"; +import { tool, type ToolExecutionOptions } from "ai"; import { z } from "zod"; +import type { AgentContext } from "@/lib/agent/tools/AgentContext"; import * as path from "path"; import { buildRecoupExecEnv } from "@/lib/agent/tools/buildRecoupExecEnv"; import { getSandbox } from "@/lib/agent/tools/getSandbox"; @@ -60,8 +62,12 @@ IMPORTANT: - Never use interactive commands (vim, nano, top, bash, ssh, etc.) - Always quote file paths that may contain spaces - Use detached: true to start dev servers / long-running processes in the background`, + contextSchema: agentContextSchema, inputSchema: bashInputSchema, - execute: async ({ command, cwd, detached }, { experimental_context, abortSignal }) => { + execute: async ( + { command, cwd, detached }, + { context: experimental_context, abortSignal }: ToolExecutionOptions, + ) => { const sandbox = await getSandbox(experimental_context, "bash"); const workingDirectory = sandbox.workingDirectory; const workingDir = cwd diff --git a/lib/agent/tools/buildToolsContext.ts b/lib/agent/tools/buildToolsContext.ts new file mode 100644 index 000000000..61e050327 --- /dev/null +++ b/lib/agent/tools/buildToolsContext.ts @@ -0,0 +1,24 @@ +import type { ToolSet } from "ai"; +import type { AgentContext } from "@/lib/agent/tools/AgentContext"; + +/** + * Build the AI SDK v7 `toolsContext` map. + * + * v7 split the old single `experimental_context` into shared `runtimeContext` + * and a per-tool-name `toolsContext` map (see the AI SDK 7.0 migration guide: + * "Context: experimental_context Became Tool context"). Every Recoup agent + * tool reads the same `AgentContext` (sandbox handle, org id, skills, model), + * so we fan the single context out to one entry per tool in the set. + * + * Preserve the tool-name keys so strict callers can prove every required + * contextual tool has an entry. Object.fromEntries erases those keys; the + * assertion restores exactly the keys enumerated from the input tool set. + */ +export function buildToolsContext( + tools: TOOLS, + context: AgentContext, +): { [K in keyof TOOLS]: AgentContext } { + return Object.fromEntries(Object.keys(tools).map(name => [name, context])) as { + [K in keyof TOOLS]: AgentContext; + }; +} diff --git a/lib/agent/tools/editFileTool.ts b/lib/agent/tools/editFileTool.ts index d8274c0bc..d2ba45370 100644 --- a/lib/agent/tools/editFileTool.ts +++ b/lib/agent/tools/editFileTool.ts @@ -1,3 +1,4 @@ +import { agentContextSchema } from "./agentContextSchema"; import { tool } from "ai"; import { z } from "zod"; import * as path from "path"; @@ -44,10 +45,11 @@ IMPORTANT: - Preserve exact indentation and spacing from the file's content as returned by readFileTool - Never include line numbers or the "N: " line prefixes from the read output in oldString or newString - If oldString appears multiple times and replaceAll is false, the tool FAILS with an error and occurrence count`, + contextSchema: agentContextSchema, inputSchema: editInputSchema, execute: async ( { filePath, oldString, newString, replaceAll = false }, - { experimental_context }, + { context: experimental_context }, ) => { const sandbox = await getSandbox(experimental_context, "edit"); const workingDirectory = sandbox.workingDirectory; diff --git a/lib/agent/tools/getMainModel.ts b/lib/agent/tools/getMainModel.ts index 961a038b5..ac5ba6947 100644 --- a/lib/agent/tools/getMainModel.ts +++ b/lib/agent/tools/getMainModel.ts @@ -2,7 +2,7 @@ import type { LanguageModel } from "ai"; import { isAgentContext } from "@/lib/agent/tools/isAgentContext"; /** - * Resolve the main agent's language model from `experimental_context`. + * Resolve the main agent's language model from `toolsContext`. * Mirrors open-agents' `getMainModel` (`tools/utils.ts`). Throws with a * descriptive error if the context wasn't populated by `runAgentStep`. * @@ -19,7 +19,7 @@ export function getMainModel(experimental_context: unknown, toolName?: string): : "Context is undefined or null"; throw new Error( `Model not initialized in context${toolInfo}. ${contextInfo}. ` + - "Ensure runAgentStep sets experimental_context: { model, ... }", + "Ensure runAgentStep sets toolsContext for this tool with { model, ... }", ); } return context.model; diff --git a/lib/agent/tools/getSubagentModel.ts b/lib/agent/tools/getSubagentModel.ts index 07735485e..ce4646c2d 100644 --- a/lib/agent/tools/getSubagentModel.ts +++ b/lib/agent/tools/getSubagentModel.ts @@ -2,7 +2,7 @@ import type { LanguageModel } from "ai"; import { isAgentContext } from "@/lib/agent/tools/isAgentContext"; /** - * Resolve the subagent's language model from `experimental_context`, + * Resolve the subagent's language model from `toolsContext`, * falling back to the main agent's model when no dedicated subagent * model is configured. Mirrors open-agents' `getSubagentModel` * (`tools/utils.ts`): `ctx.subagentModel ?? ctx.model`. @@ -17,7 +17,7 @@ export function getSubagentModel(experimental_context: unknown, toolName?: strin const toolInfo = toolName ? ` (tool: ${toolName})` : ""; throw new Error( `Model not initialized in context${toolInfo}. ` + - "Ensure runAgentStep sets experimental_context: { model, ... }", + "Ensure runAgentStep sets toolsContext for this tool with { model, ... }", ); } return context.subagentModel ?? context.model; diff --git a/lib/agent/tools/globTool.ts b/lib/agent/tools/globTool.ts index d1de234d2..f7aaaf58d 100644 --- a/lib/agent/tools/globTool.ts +++ b/lib/agent/tools/globTool.ts @@ -1,5 +1,7 @@ -import { tool } from "ai"; +import { agentContextSchema } from "./agentContextSchema"; +import { tool, type ToolExecutionOptions } from "ai"; import { z } from "zod"; +import type { AgentContext } from "@/lib/agent/tools/AgentContext"; import * as path from "path"; import { getSandbox } from "@/lib/agent/tools/getSandbox"; import { shellEscape } from "@/lib/agent/tools/shellEscape"; @@ -51,10 +53,11 @@ USAGE: IMPORTANT: - Patterns are matched primarily on the final path segment (file name), with basic "*" and "**" support - Use this to narrow down candidate files before calling readFileTool or grepTool`, + contextSchema: agentContextSchema, inputSchema: globInputSchema, execute: async ( { pattern, path: basePath, limit = DEFAULT_LIMIT }, - { experimental_context, abortSignal }, + { context: experimental_context, abortSignal }: ToolExecutionOptions, ) => { const sandbox = await getSandbox(experimental_context, "glob"); const workingDirectory = sandbox.workingDirectory; diff --git a/lib/agent/tools/grepTool.ts b/lib/agent/tools/grepTool.ts index f172f61af..4aafe42b5 100644 --- a/lib/agent/tools/grepTool.ts +++ b/lib/agent/tools/grepTool.ts @@ -1,5 +1,7 @@ -import { tool } from "ai"; +import { agentContextSchema } from "./agentContextSchema"; +import { tool, type ToolExecutionOptions } from "ai"; import { z } from "zod"; +import type { AgentContext } from "@/lib/agent/tools/AgentContext"; import * as path from "path"; import { getSandbox } from "@/lib/agent/tools/getSandbox"; import { shellEscape } from "@/lib/agent/tools/shellEscape"; @@ -53,10 +55,11 @@ IMPORTANT: - ALWAYS use this tool for code/content searches instead of running grep/rg via bashTool - Use caseSensitive: false for case-insensitive searches - Hidden files and node_modules are skipped when searching directories`, + contextSchema: agentContextSchema, inputSchema: grepInputSchema, execute: async ( { pattern, path: searchPath, glob, caseSensitive = true }, - { experimental_context, abortSignal }, + { context: experimental_context, abortSignal }: ToolExecutionOptions, ) => { const sandbox = await getSandbox(experimental_context, "grep"); const workingDirectory = sandbox.workingDirectory; diff --git a/lib/agent/tools/isAgentContext.ts b/lib/agent/tools/isAgentContext.ts index 0049ac010..39252bc68 100644 --- a/lib/agent/tools/isAgentContext.ts +++ b/lib/agent/tools/isAgentContext.ts @@ -1,7 +1,7 @@ import type { AgentContext } from "@/lib/agent/tools/AgentContext"; /** - * Type-guard that confirms an arbitrary `experimental_context` shape has + * Type-guard that confirms an arbitrary `toolsContext` shape has * the AgentContext fields tools rely on at runtime. Validates each required * leaf (sandbox object, state object, non-empty workingDirectory) so callers * can trust the narrowed type — earlier weaker guards returned true for diff --git a/lib/agent/tools/readFileTool.ts b/lib/agent/tools/readFileTool.ts index f5a486a64..2cd6e8cbd 100644 --- a/lib/agent/tools/readFileTool.ts +++ b/lib/agent/tools/readFileTool.ts @@ -1,3 +1,4 @@ +import { agentContextSchema } from "./agentContextSchema"; import { tool } from "ai"; import { z } from "zod"; import * as path from "path"; @@ -29,8 +30,9 @@ IMPORTANT: - Always read a file at least once before editing it with the edit/write tools - This tool can only read files, not directories — attempting to read a directory returns an error - You can call multiple reads in parallel to speculatively load several files`, + contextSchema: agentContextSchema, inputSchema: readInputSchema, - execute: async ({ filePath, offset = 1, limit = 2000 }, { experimental_context }) => { + execute: async ({ filePath, offset = 1, limit = 2000 }, { context: experimental_context }) => { const sandbox = await getSandbox(experimental_context, "read"); const workingDirectory = sandbox.workingDirectory; diff --git a/lib/agent/tools/skillTool.ts b/lib/agent/tools/skillTool.ts index 8c74f35d1..8e329af40 100644 --- a/lib/agent/tools/skillTool.ts +++ b/lib/agent/tools/skillTool.ts @@ -1,3 +1,4 @@ +import { agentContextSchema } from "./agentContextSchema"; import * as path from "path"; import { tool } from "ai"; import { z } from "zod"; @@ -42,8 +43,9 @@ Important: - When the user's message starts with "/", they are invoking a skill — call this tool FIRST before any other tool - NEVER just announce or mention a skill without actually calling this tool - Only use skills listed in "Available skills" in your system prompt`, + contextSchema: agentContextSchema, inputSchema: skillInputSchema, - execute: async ({ skill, args }, { experimental_context }) => { + execute: async ({ skill, args }, { context: experimental_context }) => { const sandbox = await getSandbox(experimental_context, "skill"); const skills = getSkills(experimental_context); diff --git a/lib/agent/tools/taskTool.ts b/lib/agent/tools/taskTool.ts index 270974fce..22ec4dda7 100644 --- a/lib/agent/tools/taskTool.ts +++ b/lib/agent/tools/taskTool.ts @@ -1,6 +1,16 @@ -import { streamText, stepCountIs, tool, type LanguageModelUsage, type ModelMessage } from "ai"; +import { agentContextSchema } from "./agentContextSchema"; +import { + streamText, + isStepCount, + tool, + type LanguageModelUsage, + type ModelMessage, + type ToolExecutionOptions, +} from "ai"; import { z } from "zod"; +import type { AgentContext } from "@/lib/agent/tools/AgentContext"; import { buildSubagentTools } from "@/lib/agent/tools/buildSubagentTools"; +import { buildToolsContext } from "@/lib/agent/tools/buildToolsContext"; import { getSubagentModel } from "@/lib/agent/tools/getSubagentModel"; import { sumLanguageModelUsage } from "@/lib/agent/messageMetadata/sumLanguageModelUsage"; @@ -94,9 +104,13 @@ IMPORTANT: - Be explicit and concrete — the subagent cannot ask clarifying questions - Include critical context (APIs, function names, file paths) in the instructions - The parent agent does not see the subagent's internal tool calls, only its final summary`, + contextSchema: agentContextSchema, inputSchema: taskInputSchema, outputSchema: taskOutputSchema, - execute: async function* ({ task, instructions }, { experimental_context, abortSignal }) { + execute: async function* ( + { task, instructions }, + { context: experimental_context, abortSignal }: ToolExecutionOptions, + ) { const subagentModel = getSubagentModel(experimental_context, "task"); const subagentModelId = typeof subagentModel === "string" @@ -106,13 +120,14 @@ IMPORTANT: // `prompt` (not `messages: []`) is required — the AI SDK records zero // steps and throws NoOutputGeneratedError if the model has only a // system prompt with no user turn. Mirrors open-agents' task tool. + const subagentTools = buildSubagentTools(); const result = streamText({ model: subagentModel, - system: `${SUBAGENT_SYSTEM_PROMPT}\n\n## Your Task\n${task}\n\n## Instructions\n${instructions}`, + instructions: `${SUBAGENT_SYSTEM_PROMPT}\n\n## Your Task\n${task}\n\n## Instructions\n${instructions}`, prompt: "Complete this task and provide a summary of what you accomplished.", - tools: buildSubagentTools(), - stopWhen: stepCountIs(SUBAGENT_STEP_LIMIT), - experimental_context, + tools: subagentTools, + stopWhen: isStepCount(SUBAGENT_STEP_LIMIT), + toolsContext: buildToolsContext(subagentTools, experimental_context), abortSignal, }); @@ -126,7 +141,7 @@ IMPORTANT: // the first step finishes. yield { toolCallCount, startedAt, modelId: subagentModelId }; - for await (const part of result.fullStream) { + for await (const part of result.stream) { if (part.type === "tool-call") { toolCallCount += 1; pending = { name: part.toolName, input: part.input }; @@ -141,10 +156,10 @@ IMPORTANT: } } - const response = await result.response; + const responseMessages = await result.responseMessages; const finalUsage = usage ?? (await result.totalUsage); yield { - final: response.messages, + final: responseMessages, toolCallCount, usage: finalUsage, startedAt, diff --git a/lib/agent/tools/webFetchTool.ts b/lib/agent/tools/webFetchTool.ts index b395457f9..53030c2cf 100644 --- a/lib/agent/tools/webFetchTool.ts +++ b/lib/agent/tools/webFetchTool.ts @@ -1,5 +1,7 @@ -import { tool } from "ai"; +import { agentContextSchema } from "./agentContextSchema"; +import { tool, type ToolExecutionOptions } from "ai"; import { z } from "zod"; +import type { AgentContext } from "@/lib/agent/tools/AgentContext"; import { buildRecoupExecEnv } from "@/lib/agent/tools/buildRecoupExecEnv"; import { getSandbox } from "@/lib/agent/tools/getSandbox"; import { shellEscape } from "@/lib/agent/tools/shellEscape"; @@ -45,12 +47,17 @@ USAGE: - Supports GET, POST, PUT, PATCH, DELETE, and HEAD methods - Returns the response status and body text - Body is truncated to ${MAX_BODY_LENGTH} characters to avoid overwhelming context`, + contextSchema: agentContextSchema, inputSchema: fetchInputSchema, outputSchema: fetchOutputSchema, execute: async ( - { url, method = "GET", headers, body }, - { experimental_context, abortSignal }, + { url, method: methodInput, headers, body }, + { context: experimental_context, abortSignal }: ToolExecutionOptions, ) => { + // Default applied in-body rather than via a destructure default: combined + // with `outputSchema`, a parameter default poisons the AI SDK v7 `tool()` + // INPUT inference and breaks the typed-overload resolution. + const method = methodInput ?? "GET"; const sandbox = await getSandbox(experimental_context, "web_fetch"); const workingDirectory = sandbox.workingDirectory; const recoupEnv = buildRecoupExecEnv(experimental_context); @@ -99,7 +106,7 @@ USAGE: // exit 23 = curl wrote partial output (`head -c` cut it off — expected for large responses). if (result.exitCode !== 0 && result.exitCode !== 23) { return { - success: false, + success: false as const, error: `Fetch failed: ${result.stderr || result.stdout || "Unknown error"}`, }; } @@ -111,14 +118,14 @@ USAGE: const status = /^\d+$/.test(statusText) ? parseInt(statusText, 10) : null; return { - success: true, + success: true as const, status, body: responseBody, truncated: result.exitCode === 23, }; } catch (error) { const message = error instanceof Error ? error.message : String(error); - return { success: false, error: `Fetch failed: ${message}` }; + return { success: false as const, error: `Fetch failed: ${message}` }; } }, }); diff --git a/lib/agent/tools/writeFileTool.ts b/lib/agent/tools/writeFileTool.ts index c8e59e3c3..dcddc61f1 100644 --- a/lib/agent/tools/writeFileTool.ts +++ b/lib/agent/tools/writeFileTool.ts @@ -1,3 +1,4 @@ +import { agentContextSchema } from "./agentContextSchema"; import { tool } from "ai"; import { z } from "zod"; import * as path from "path"; @@ -38,8 +39,9 @@ IMPORTANT: - Prefer editing existing files over creating new ones unless a new file is explicitly needed - NEVER proactively create documentation files (e.g., *.md) unless the user explicitly requests them - Do not write files that contain secrets or credentials (API keys, passwords, .env, etc.)`, + contextSchema: agentContextSchema, inputSchema: writeInputSchema, - execute: async ({ filePath, content }, { experimental_context }) => { + execute: async ({ filePath, content }, { context: experimental_context }) => { const sandbox = await getSandbox(experimental_context, "write"); const workingDirectory = sandbox.workingDirectory; diff --git a/lib/agents/CompactAgent/__tests__/createCompactAgent.test.ts b/lib/agents/CompactAgent/__tests__/createCompactAgent.test.ts index a0f713f7e..9d0e35628 100644 --- a/lib/agents/CompactAgent/__tests__/createCompactAgent.test.ts +++ b/lib/agents/CompactAgent/__tests__/createCompactAgent.test.ts @@ -6,7 +6,7 @@ vi.mock("ai", () => ({ config, generate: vi.fn(), })), - stepCountIs: vi.fn().mockReturnValue("stepCountMock"), + isStepCount: vi.fn().mockReturnValue("stepCountMock"), })); vi.mock("@/lib/const", () => ({ diff --git a/lib/agents/CompactAgent/createCompactAgent.ts b/lib/agents/CompactAgent/createCompactAgent.ts index 144a60284..0d2b5ee9d 100644 --- a/lib/agents/CompactAgent/createCompactAgent.ts +++ b/lib/agents/CompactAgent/createCompactAgent.ts @@ -1,4 +1,4 @@ -import { ToolLoopAgent, stepCountIs } from "ai"; +import { ToolLoopAgent, isStepCount } from "ai"; import { LIGHTWEIGHT_MODEL } from "@/lib/const"; const DEFAULT_INSTRUCTIONS = `You are a conversation summarizer. Create a concise summary of the conversation that: @@ -19,6 +19,6 @@ export function createCompactAgent(customInstructions?: string) { return new ToolLoopAgent({ model: LIGHTWEIGHT_MODEL, instructions: customInstructions || DEFAULT_INSTRUCTIONS, - stopWhen: stepCountIs(1), + stopWhen: isStepCount(1), }); } diff --git a/lib/agents/EmailReplyAgent/createEmailReplyAgent.ts b/lib/agents/EmailReplyAgent/createEmailReplyAgent.ts index 29452b7d3..31a9730bb 100644 --- a/lib/agents/EmailReplyAgent/createEmailReplyAgent.ts +++ b/lib/agents/EmailReplyAgent/createEmailReplyAgent.ts @@ -1,4 +1,4 @@ -import { Output, ToolLoopAgent, stepCountIs } from "ai"; +import { Output, ToolLoopAgent, isStepCount } from "ai"; import { z } from "zod"; import { LIGHTWEIGHT_MODEL, INBOUND_EMAIL_DOMAIN } from "@/lib/const"; @@ -25,6 +25,6 @@ export function createEmailReplyAgent() { model: LIGHTWEIGHT_MODEL, instructions, output: Output.object({ schema: replyDecisionSchema }), - stopWhen: stepCountIs(1), + stopWhen: isStepCount(1), }); } diff --git a/lib/agents/content/createContentPromptAgent.ts b/lib/agents/content/createContentPromptAgent.ts index 93dc5d10e..a0c31c226 100644 --- a/lib/agents/content/createContentPromptAgent.ts +++ b/lib/agents/content/createContentPromptAgent.ts @@ -1,4 +1,4 @@ -import { Output, ToolLoopAgent, stepCountIs } from "ai"; +import { Output, ToolLoopAgent, isStepCount } from "ai"; import { z } from "zod"; import { LIGHTWEIGHT_MODEL } from "@/lib/const"; import { CONTENT_TEMPLATES, DEFAULT_CONTENT_TEMPLATE } from "@/lib/content/contentTemplates"; @@ -71,6 +71,6 @@ export function createContentPromptAgent() { model: LIGHTWEIGHT_MODEL, instructions, output: Output.object({ schema: contentPromptFlagsSchema }), - stopWhen: stepCountIs(1), + stopWhen: isStepCount(1), }); } diff --git a/lib/agents/generalAgent/__tests__/getGeneralAgent.test.ts b/lib/agents/generalAgent/__tests__/getGeneralAgent.test.ts index 41f316891..17a28073c 100644 --- a/lib/agents/generalAgent/__tests__/getGeneralAgent.test.ts +++ b/lib/agents/generalAgent/__tests__/getGeneralAgent.test.ts @@ -519,6 +519,23 @@ describe("getGeneralAgent", () => { }); }); + it("restores base instructions when a tool-chain override ends", async () => { + const result = await getGeneralAgent({ + accountId: "account-123", + orgId: null, + messages: [{ id: "1", role: "user", content: "Hello" }], + }); + const settings = (result.agent as any).settings; + const next = settings.prepareStep({ + steps: [], + stepNumber: 2, + model: settings.model, + messages: [], + instructions: "previous chain override", + }); + expect(next.instructions).toBe(finalInstructions); + }); + it("creates ToolLoopAgent with prepareStep function", async () => { const body: ChatRequestBody = { accountId: "account-123", diff --git a/lib/agents/generalAgent/getAnthropicProviderOptions.ts b/lib/agents/generalAgent/getAnthropicProviderOptions.ts index 8facc699c..2a3fb7d1d 100644 --- a/lib/agents/generalAgent/getAnthropicProviderOptions.ts +++ b/lib/agents/generalAgent/getAnthropicProviderOptions.ts @@ -14,13 +14,13 @@ const ADAPTIVE_THINKING_MODELS = new Set([ * @param modelId - The model ID selected for the general agent. * @returns Anthropic options accepted by the installed SDK. */ -export function getAnthropicProviderOptions(modelId: string): AnthropicProviderOptions { +export function getAnthropicProviderOptions(modelId: string) { if (ADAPTIVE_THINKING_MODELS.has(modelId)) { return { thinking: { type: "adaptive", display: "summarized" }, effort: "medium", - }; + } satisfies AnthropicProviderOptions; } - return { thinking: { type: "enabled", budgetTokens: 12000 } }; + return { thinking: { type: "enabled", budgetTokens: 12000 } } satisfies AnthropicProviderOptions; } diff --git a/lib/agents/generalAgent/getGeneralAgent.ts b/lib/agents/generalAgent/getGeneralAgent.ts index ea48d5257..e634582c1 100644 --- a/lib/agents/generalAgent/getGeneralAgent.ts +++ b/lib/agents/generalAgent/getGeneralAgent.ts @@ -1,5 +1,5 @@ -import { ToolLoopAgent } from "ai"; -import { CHAT_AGENT_STOP_WHEN } from "@/lib/chat/const"; +import { ToolLoopAgent, isStepCount } from "ai"; +import { CHAT_AGENT_MAX_ITERATIONS } from "@/lib/chat/const"; import { GoogleGenerativeAIProviderOptions } from "@ai-sdk/google"; import { OpenAIResponsesProviderOptions } from "@ai-sdk/openai"; import { DEFAULT_MODEL } from "@/lib/const"; @@ -53,7 +53,7 @@ export default async function getGeneralAgent(body: ChatRequestBody): Promise { const next = getPrepareStepResult(options); - if (next) return { ...options, ...next }; - return options; + return { ...options, instructions, ...next }; }, providerOptions: { anthropic: getAnthropicProviderOptions(model), diff --git a/lib/ai/generateArray.ts b/lib/ai/generateArray.ts index c33c459fe..1a07c3b4c 100644 --- a/lib/ai/generateArray.ts +++ b/lib/ai/generateArray.ts @@ -16,7 +16,7 @@ const generateArray = async ({ }): Promise => { const result = await generateObject({ model: DEFAULT_MODEL, - system, + instructions: system, prompt, output: "array", schema: z.object({ diff --git a/lib/ai/generateText.ts b/lib/ai/generateText.ts index 0d509f899..ae70712d5 100644 --- a/lib/ai/generateText.ts +++ b/lib/ai/generateText.ts @@ -11,7 +11,7 @@ const generateText = async ({ model?: string; }) => { const result = await generate({ - system, + instructions: system, model: model || DEFAULT_MODEL, prompt, }); diff --git a/lib/chat/__tests__/buildRunAgentInput.test.ts b/lib/chat/__tests__/buildRunAgentInput.test.ts index 45af4f7cc..842dcb4cc 100644 --- a/lib/chat/__tests__/buildRunAgentInput.test.ts +++ b/lib/chat/__tests__/buildRunAgentInput.test.ts @@ -59,3 +59,13 @@ describe("buildRunAgentInput", () => { expect(parseGitHubRepoIdentifiers).toHaveBeenCalledWith(null); }); }); +it("records explicit server requirements for fresh and headless continuation inputs", () => { + expect(buildRunAgentInput(base).streamProtocol).toBe("unmarked-v1"); + expect( + buildRunAgentInput({ + ...base, + interactive: false, + messages: [{ id: "a", role: "assistant", parts: [] }], + }).streamProtocol, + ).toBe("canonical-base-v1"); +}); diff --git a/lib/chat/__tests__/chatStartRecovery.test.ts b/lib/chat/__tests__/chatStartRecovery.test.ts index 8d5f887b4..85cf28fff 100644 --- a/lib/chat/__tests__/chatStartRecovery.test.ts +++ b/lib/chat/__tests__/chatStartRecovery.test.ts @@ -1,3 +1,4 @@ +import { gateStoredContinuation } from "@/lib/chat/continuation/gateStoredContinuation"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { NextRequest } from "next/server"; @@ -9,6 +10,9 @@ import { isSandboxActive } from "@/lib/sandbox/isSandboxActive"; import { compareAndSetChatActiveStreamId } from "@/lib/chat/compareAndSetChatActiveStreamId"; import { persistLatestUserMessage } from "@/lib/chat/persistLatestUserMessage"; import { start, getRun } from "workflow/api"; +vi.mock("@/lib/chat/continuation/gateStoredContinuation", () => ({ + gateStoredContinuation: vi.fn(async () => null), +})); vi.mock("@/lib/chat/validateChatWorkflow", () => ({ validateChatWorkflow: vi.fn() })); vi.mock("@/lib/supabase/sessions/selectSessions", () => ({ selectSessions: vi.fn() })); @@ -102,7 +106,9 @@ function mockStartedRun(runId = "wrun_test_run_1") { } beforeEach(() => { + vi.mocked(gateStoredContinuation).mockResolvedValue(null); vi.resetAllMocks(); + vi.mocked(gateStoredContinuation).mockResolvedValue(null); mockValidated(); vi.mocked(validateChatWorkflow).mockResolvedValue({ messages: [ @@ -150,6 +156,7 @@ describe("POST start recovery with the real reconciliation path", () => { expect(response.status).toBe(409); expect(await response.json()).toMatchObject({ error: expect.stringContaining("GET /api/chat/"), + admission: "not_admitted", }); expect(response.headers.get("x-workflow-run-id")).toBeNull(); expect(getReadable).not.toHaveBeenCalled(); diff --git a/lib/chat/__tests__/chatWorkflowReadableSdk.test.ts b/lib/chat/__tests__/chatWorkflowReadableSdk.test.ts index b23ae0ee8..c3779b9bc 100644 --- a/lib/chat/__tests__/chatWorkflowReadableSdk.test.ts +++ b/lib/chat/__tests__/chatWorkflowReadableSdk.test.ts @@ -1,3 +1,5 @@ +import { CONTINUATION_WORKFLOW } from "../continuation/streamProtocol"; +import { createRequire } from "node:module"; import { it, expect, vi, beforeEach } from "vitest"; import { NextRequest } from "next/server"; @@ -93,6 +95,10 @@ beforeEach(() => { vi.mocked(compareAndSetChatActiveStreamId).mockResolvedValue({ ok: true, claimed: true }); }); +const require = createRequire(import.meta.url); +const { stringify } = createRequire(require.resolve("@workflow/core/serialization-format"))( + "devalue", +); const runId = "wrun_synthetic_sdk_boundary"; function syntheticWorld(mode: "cancel" | "eof" | "error") { let entered!: () => void; @@ -102,7 +108,27 @@ function syntheticWorld(mode: "cancel" | "eof" | "error") { const events = vi.fn(async () => ({})); const release = vi.fn(); setWorld({ - runs: { get: async () => ({ runId, status: "running" }) }, + runs: { + get: async () => ({ + runId, + status: "running", + workflowName: CONTINUATION_WORKFLOW, + input: new TextEncoder().encode( + "devl" + + stringify([ + { + accountId: ACCOUNT_ID, + chatId: CHAT_ID, + sessionId: SESSION_ID, + modelId: "model", + messages: [], + agentContext: {}, + streamProtocol: "unmarked-v1", + }, + ]), + ), + }), + }, events: { create: events }, getStreamInfo: async () => ({ tailIndex: 17 }), readFromStream: async () => { @@ -121,7 +147,7 @@ function syntheticWorld(mode: "cancel" | "eof" | "error") { vi.mocked(start).mockResolvedValue(getRun(runId) as never); vi.mocked(validateChatOwnership).mockResolvedValue({ auth: { accountId: ACCOUNT_ID }, - chat: { id: CHAT_ID, active_stream_id: runId }, + chat: { id: CHAT_ID, session_id: SESSION_ID, active_stream_id: runId }, } as never); return { subscribed, events, release }; } diff --git a/lib/chat/__tests__/continuationCors.test.ts b/lib/chat/__tests__/continuationCors.test.ts new file mode 100644 index 000000000..3958a7e20 --- /dev/null +++ b/lib/chat/__tests__/continuationCors.test.ts @@ -0,0 +1,23 @@ +import { expect, it, vi } from "vitest"; +import { OPTIONS as start } from "@/app/api/chat/route"; +import { OPTIONS as resume } from "@/app/api/chat/[chatId]/stream/route"; +import { OPTIONS as headless } from "@/app/api/chat/runs/route"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +it("allows the exact capability header on every chat stream preflight", async () => { + for (const options of [start, resume, headless]) { + const response = await options(); + expect(response.headers.get("Access-Control-Allow-Headers")?.split(", ")).toContain( + "X-Recoup-Stream-Continuation", + ); + expect(response.headers.get("Access-Control-Expose-Headers")).toBe( + "x-workflow-run-id, x-workflow-stream-tail-index", + ); + } + expect(getCorsHeaders()["Access-Control-Allow-Headers"]).toBe( + "Content-Type, Authorization, X-Requested-With, x-api-key", + ); +}); + +vi.mock("@/lib/chat/handleChatWorkflowStream", () => ({ handleChatWorkflowStream: vi.fn() })); +vi.mock("@/lib/chat/handleResumeChatStream", () => ({ handleResumeChatStream: vi.fn() })); +vi.mock("@/lib/chat/runs/handleStartChatRun", () => ({ handleStartChatRun: vi.fn() })); diff --git a/lib/chat/__tests__/explicitStopLifecycle.test.ts b/lib/chat/__tests__/explicitStopLifecycle.test.ts index 75c6e4bea..dc87f6315 100644 --- a/lib/chat/__tests__/explicitStopLifecycle.test.ts +++ b/lib/chat/__tests__/explicitStopLifecycle.test.ts @@ -1,3 +1,4 @@ +import { gateStoredContinuation } from "@/lib/chat/continuation/gateStoredContinuation"; import { it, expect, vi, beforeEach, afterEach } from "vitest"; import { NextRequest } from "next/server"; @@ -12,6 +13,9 @@ import { selectChats } from "@/lib/supabase/chats/selectChats"; import { isSandboxActive } from "@/lib/sandbox/isSandboxActive"; import { compareAndSetChatActiveStreamId } from "@/lib/chat/compareAndSetChatActiveStreamId"; import { start, getRun } from "workflow/api"; +vi.mock("@/lib/chat/continuation/gateStoredContinuation", () => ({ + gateStoredContinuation: vi.fn(async () => null), +})); vi.mock("@/lib/chat/validateChatWorkflow", () => ({ validateChatWorkflow: vi.fn() })); vi.mock("@/lib/supabase/sessions/selectSessions", () => ({ selectSessions: vi.fn() })); @@ -89,7 +93,9 @@ vi.mock("@/lib/chat/validateStopChatWorkflowRequest", () => ({ validateStopChatWorkflowRequest: vi.fn(), })); beforeEach(() => { + vi.mocked(gateStoredContinuation).mockResolvedValue(null); vi.resetAllMocks(); + vi.mocked(gateStoredContinuation).mockResolvedValue(null); vi.useFakeTimers(); mockValidated(); mockSessionOwnedActive(); diff --git a/lib/chat/__tests__/fencedLifecycleContracts.test.ts b/lib/chat/__tests__/fencedLifecycleContracts.test.ts index 5b6c5b4e2..e05c1a9b1 100644 --- a/lib/chat/__tests__/fencedLifecycleContracts.test.ts +++ b/lib/chat/__tests__/fencedLifecycleContracts.test.ts @@ -1,3 +1,4 @@ +import { gateStoredContinuation } from "../continuation/gateStoredContinuation"; import { beforeEach, afterEach, expect, it, vi } from "vitest"; import { NextRequest } from "next/server"; import { getRun } from "workflow/api"; @@ -5,6 +6,9 @@ import { handleStopChatWorkflow } from "@/lib/chat/handleStopChatWorkflow"; import { handleResumeChatStream } from "@/lib/chat/handleResumeChatStream"; import { stopFencedChatWorkflow } from "../fence/lifecycle/stopFencedChatWorkflow"; import { resumeFencedChatStream } from "../fence/lifecycle/resumeFencedChatStream"; +vi.mock("../continuation/gateStoredContinuation", () => ({ + gateStoredContinuation: vi.fn(async () => null), +})); const { rpc, ownership, stopValidation, cas } = vi.hoisted(() => ({ rpc: vi.fn(), ownership: vi.fn(), @@ -31,11 +35,12 @@ const target = { const request = new NextRequest("https://api.test/stream?streamLifecycle=explicit-stop-v1"); beforeEach(() => { vi.resetAllMocks(); + vi.mocked(gateStoredContinuation).mockResolvedValue(null); vi.useFakeTimers(); cas.mockResolvedValue({ ok: true, claimed: true }); const validated = { auth: { accountId: target.effectiveAccount }, - chat: { id: "chat", active_stream_id: target.runId }, + chat: { id: "chat", session_id: "session", active_stream_id: target.runId }, }; ownership.mockResolvedValue(validated); stopValidation.mockResolvedValue(validated); @@ -57,7 +62,7 @@ it.each(["pending", "cancel-failed", "timeout"])( if (mode === "pending") { input = { ...target, phase: "pending", runId: null }; stopValidation.mockResolvedValue({ - chat: { id: "chat", active_stream_id: "pending-original" }, + chat: { id: "chat", session_id: "session", active_stream_id: "pending-original" }, }); } const cancel = vi.fn(async () => { @@ -89,7 +94,7 @@ it("preserves actual resume status-read failure contract instead of fake complet }, } as never); const legacy = await handleResumeChatStream(request, "chat"); - const fenced = await resumeFencedChatStream(target, new URL(request.url)); + const fenced = await resumeFencedChatStream(target, request); expect(fenced.status).toBe(502); expect(fenced.status).toBe(legacy.status); expect(await fenced.json()).toEqual(await legacy.json()); @@ -98,7 +103,7 @@ it("preserves actual resume status-read failure contract instead of fake complet it("preserves finish-only terminal resume shape after successful authoritative release", async () => { vi.mocked(getRun).mockReturnValue({ status: Promise.resolve("completed") } as never); const legacy = await handleResumeChatStream(request, "chat"); - const fenced = await resumeFencedChatStream(target, new URL(request.url)); + const fenced = await resumeFencedChatStream(target, request); expect(fenced.status).toBe(200); expect(await fenced.text()).toEqual(await legacy.text()); expect(cas).toHaveBeenCalledExactlyOnceWith("chat", target.runId, null); diff --git a/lib/chat/__tests__/gateChatStreamStart.test.ts b/lib/chat/__tests__/gateChatStreamStart.test.ts index 74b8d5e4d..1047df707 100644 --- a/lib/chat/__tests__/gateChatStreamStart.test.ts +++ b/lib/chat/__tests__/gateChatStreamStart.test.ts @@ -33,7 +33,12 @@ describe("gateChatStreamStart", () => { expect(res).not.toBeNull(); expect(res!.status).toBe(409); expect(res!.headers.get("x-workflow-run-id")).toBeNull(); - expect(await res!.json()).toMatchObject({ error: expect.stringContaining("GET /api/chat/") }); + const body = await res!.json(); + expect(body).toMatchObject({ + error: expect.stringContaining("GET /api/chat/"), + admission: "not_admitted", + }); + expect(body).not.toHaveProperty("runId"); }); it("returns a retryable 503 on an unresolved slot", async () => { diff --git a/lib/chat/__tests__/handleChatWorkflowStream.test.ts b/lib/chat/__tests__/handleChatWorkflowStream.test.ts index a54d7e2a2..cd4ee488b 100644 --- a/lib/chat/__tests__/handleChatWorkflowStream.test.ts +++ b/lib/chat/__tests__/handleChatWorkflowStream.test.ts @@ -1,3 +1,4 @@ +import { gateStoredContinuation } from "../continuation/gateStoredContinuation"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { NextRequest, NextResponse } from "next/server"; @@ -11,6 +12,9 @@ import { compareAndSetChatActiveStreamId } from "@/lib/chat/compareAndSetChatAct import { gateChatStreamStart } from "@/lib/chat/gateChatStreamStart"; import { persistLatestUserMessage } from "@/lib/chat/persistLatestUserMessage"; import { start, getRun } from "workflow/api"; +vi.mock("../continuation/gateStoredContinuation", () => ({ + gateStoredContinuation: vi.fn(async () => null), +})); vi.mock("@/lib/chat/validateChatWorkflow", () => ({ validateChatWorkflow: vi.fn() })); vi.mock("@/lib/supabase/sessions/selectSessions", () => ({ selectSessions: vi.fn() })); @@ -376,3 +380,145 @@ describe("handleChatWorkflowStream", () => { }); }); }); + +it("rejects unproven projection before claiming, writing or starting a run", async () => { + mockSessionOwnedActive(); + mockChatOwned(); + vi.mocked(validateChatWorkflow).mockResolvedValue({ + accountId: ACCOUNT_ID, + chatId: CHAT_ID, + sessionId: SESSION_ID, + orgId: null, + messages: [ + { + id: "a", + role: "assistant", + parts: [ + { + type: "data-recoup-sdk-observation", + id: "a:projection:0", + data: { fallback: { partIndex: 1 } }, + }, + ], + }, + ], + }); + const response = await handleChatWorkflowStream(makeRequest()); + expect(response.status).toBe(400); + expect(compareAndSetChatActiveStreamId).not.toHaveBeenCalled(); + expect(persistLatestUserMessage).not.toHaveBeenCalled(); + expect(start).not.toHaveBeenCalled(); +}); + +it.each(["custom", "reasoning-file", "tool-approval-request", "tool-approval-response"])( + "rejects caller raw %s before persistence or workflow start", + async type => { + mockSessionOwnedActive(); + mockChatOwned(); + vi.mocked(validateChatWorkflow).mockResolvedValue({ + accountId: ACCOUNT_ID, + chatId: CHAT_ID, + sessionId: SESSION_ID, + orgId: null, + messages: [ + { id: "a", role: "assistant", parts: [{ type, kind: "caller.fake", approved: true }] }, + ], + }); + expect((await handleChatWorkflowStream(makeRequest())).status).toBe(400); + expect(compareAndSetChatActiveStreamId).not.toHaveBeenCalled(); + expect(persistLatestUserMessage).not.toHaveBeenCalled(); + expect(start).not.toHaveBeenCalled(); + }, +); + +it("refuses an unsupported continuation before claim, persistence, or workflow start", async () => { + mockValidated(); + mockSessionOwnedActive(); + mockChatOwned(); + const validated = await vi.mocked(validateChatWorkflow).getMockImplementation()!(makeRequest()); + vi.mocked(validateChatWorkflow).mockResolvedValue({ + ...validated, + messages: [{ id: "a", role: "assistant", parts: [{ type: "text", text: "prior" }] }], + } as never); + const response = await handleChatWorkflowStream(makeRequest()); + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ + error: "stream_continuation_upgrade_required", + admission: "not_admitted", + }); + expect(compareAndSetChatActiveStreamId).not.toHaveBeenCalled(); + expect(persistLatestUserMessage).not.toHaveBeenCalled(); + expect(start).not.toHaveBeenCalled(); +}); +it("reports admitted readback failure without cancelling, restarting, or creating a reader", async () => { + mockValidated(); + mockSessionOwnedActive(); + mockChatOwned(); + vi.mocked(compareAndSetChatActiveStreamId).mockResolvedValue({ + ok: true, + claimed: true, + } as never); + const getReadable = vi.fn(); + const cancel = vi.fn(); + vi.mocked(start).mockResolvedValue({ runId: "run", getReadable } as never); + vi.mocked(getRun).mockReturnValue({ cancel } as never); + vi.mocked(gateStoredContinuation).mockResolvedValueOnce( + NextResponse.json( + { error: "stream_continuation_evidence_unavailable", admission: "admitted", runId: "run" }, + { status: 503 }, + ), + ); + const response = await handleChatWorkflowStream(makeRequest()); + expect(response.status).toBe(503); + expect(await response.json()).toMatchObject({ admission: "admitted", runId: "run" }); + expect(start).toHaveBeenCalledTimes(1); + expect(getReadable).not.toHaveBeenCalled(); + expect(cancel).not.toHaveBeenCalled(); +}); +it.each([ + { promotion: "race", cancelFails: false }, + { promotion: "race", cancelFails: true }, + { promotion: "unavailable", cancelFails: false }, + { promotion: "unavailable", cancelFails: true }, +])("reports the admitted run after promotion loss: %j", async ({ promotion, cancelFails }) => { + mockValidated(); + mockSessionOwnedActive(); + mockChatOwned(); + vi.mocked(compareAndSetChatActiveStreamId) + .mockResolvedValueOnce({ ok: true, claimed: true }) + .mockResolvedValueOnce( + (promotion === "race" ? { ok: true, claimed: false } : { ok: false }) as never, + ); + const getReadable = vi.fn(); + const cancel = vi.fn(async () => { + if (cancelFails) throw new Error("synthetic cancellation failure"); + }); + vi.mocked(start).mockResolvedValue({ runId: "wrun_created", getReadable } as never); + vi.mocked(getRun).mockReturnValue({ cancel } as never); + const response = await handleChatWorkflowStream(makeRequest()); + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ + status: "error", + error: "chat_stream_ownership_lost", + admission: "admitted", + runId: "wrun_created", + }); + expect(start).toHaveBeenCalledTimes(1); + expect(getRun).toHaveBeenCalledExactlyOnceWith("wrun_created"); + expect(cancel).toHaveBeenCalledTimes(1); + expect(getReadable).not.toHaveBeenCalled(); + expect(gateStoredContinuation).not.toHaveBeenCalled(); +}); +it("reports a preclaim conflict as not admitted without inventing a run ID", async () => { + mockValidated(); + mockSessionOwnedActive(); + mockChatOwned(); + vi.mocked(compareAndSetChatActiveStreamId).mockResolvedValueOnce({ ok: true, claimed: false }); + const response = await handleChatWorkflowStream(makeRequest()); + expect(response.status).toBe(409); + const body = await response.json(); + expect(body.admission).toBe("not_admitted"); + expect(body).not.toHaveProperty("runId"); + expect(start).not.toHaveBeenCalled(); + expect(getRun).not.toHaveBeenCalled(); +}); diff --git a/lib/chat/__tests__/handleResumeChatStream.test.ts b/lib/chat/__tests__/handleResumeChatStream.test.ts index 434c13d1d..3a060cb6a 100644 --- a/lib/chat/__tests__/handleResumeChatStream.test.ts +++ b/lib/chat/__tests__/handleResumeChatStream.test.ts @@ -1,9 +1,13 @@ +import { gateStoredContinuation } from "../continuation/gateStoredContinuation"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { NextRequest, NextResponse } from "next/server"; import { handleResumeChatStream } from "@/lib/chat/handleResumeChatStream"; import { validateChatOwnership } from "@/lib/chat/validateChatOwnership"; import { compareAndSetChatActiveStreamId } from "@/lib/chat/compareAndSetChatActiveStreamId"; import { getRun } from "workflow/api"; +vi.mock("../continuation/gateStoredContinuation", () => ({ + gateStoredContinuation: vi.fn(async () => null), +})); vi.mock("@/lib/chat/validateChatOwnership", () => ({ validateChatOwnership: vi.fn() })); vi.mock("@/lib/chat/compareAndSetChatActiveStreamId", () => ({ @@ -173,3 +177,19 @@ describe("handleResumeChatStream", () => { expect(res.headers.get("x-workflow-stream-tail-index")).toBeNull(); }); }); + +it.each(["running", "completed"])( + "gates %s before status, reader, tail or stale-slot clear", + async status => { + withChat(RUN_ID); + const readable = withRun(status); + vi.mocked(gateStoredContinuation).mockResolvedValueOnce( + NextResponse.json({ error: "stream_continuation_upgrade_required" }, { status: 409 }), + ); + const response = await handleResumeChatStream(request("?startIndex=99"), CHAT_ID); + expect(response.status).toBe(409); + expect(getRun).not.toHaveBeenCalled(); + expect(readable).not.toHaveBeenCalled(); + expect(compareAndSetChatActiveStreamId).not.toHaveBeenCalled(); + }, +); diff --git a/lib/chat/__tests__/integration/chatEndToEnd.test.ts b/lib/chat/__tests__/integration/chatEndToEnd.test.ts index c1cfb41c9..323f6390c 100644 --- a/lib/chat/__tests__/integration/chatEndToEnd.test.ts +++ b/lib/chat/__tests__/integration/chatEndToEnd.test.ts @@ -121,7 +121,7 @@ vi.mock("@/lib/ai/generateText", () => ({ // Mock AI SDK vi.mock("ai", () => ({ convertToModelMessages: vi.fn((messages: unknown[]) => messages), - stepCountIs: vi.fn().mockReturnValue(() => true), + isStepCount: vi.fn().mockReturnValue(() => true), ToolLoopAgent: vi.fn().mockImplementation(() => ({ stream: vi.fn(), tools: {}, @@ -359,17 +359,18 @@ describe("Chat Integration Tests", () => { it("calculates and deducts credits based on usage", async () => { mockGetCreditUsage.mockResolvedValue(0.5); + const usage = { + inputTokens: 1000, + outputTokens: 500, + inputTokenDetails: { cacheReadTokens: 0 }, + }; await handleChatCredits({ - usage: { promptTokens: 1000, completionTokens: 500 }, + usage: usage as never, model: "gpt-4", accountId: "account-123", }); - expect(mockGetCreditUsage).toHaveBeenCalledWith( - { promptTokens: 1000, completionTokens: 500 }, - "gpt-4", - undefined, - ); + expect(mockGetCreditUsage).toHaveBeenCalledWith(usage, "gpt-4", undefined); expect(mockRecordCreditDeduction).toHaveBeenCalledWith( expect.objectContaining({ accountId: "account-123", @@ -395,7 +396,11 @@ describe("Chat Integration Tests", () => { mockRecordCreditDeduction.mockResolvedValue({ success: true, newBalance: 332 }); await handleChatCredits({ - usage: { promptTokens: 10, completionTokens: 5 }, + usage: { + inputTokens: 10, + outputTokens: 5, + inputTokenDetails: { cacheReadTokens: 0 }, + } as never, model: "gpt-4", accountId: "account-123", }); @@ -423,7 +428,11 @@ describe("Chat Integration Tests", () => { mockGetCreditUsage.mockResolvedValue(0.001); await handleChatCredits({ - usage: { promptTokens: 5, completionTokens: 5 }, + usage: { + inputTokens: 5, + outputTokens: 5, + inputTokenDetails: { cacheReadTokens: 0 }, + } as never, model: "gpt-4", accountId: "account-123", }); diff --git a/lib/chat/__tests__/types.test.ts b/lib/chat/__tests__/types.test.ts index f4755355c..39f21e8ae 100644 --- a/lib/chat/__tests__/types.test.ts +++ b/lib/chat/__tests__/types.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { stepCountIs, ToolLoopAgent } from "ai"; +import { isStepCount, ToolLoopAgent } from "ai"; import type { ChatConfig, RoutingDecision } from "../types"; describe("Chat Types", () => { @@ -27,7 +27,7 @@ describe("Chat Types", () => { model: "gpt-4", instructions: "Test instructions", agent: new ToolLoopAgent({ model: "gpt-4" }), - stopWhen: stepCountIs(5), + stopWhen: isStepCount(5), }; expect(decision.stopWhen).toBeDefined(); }); diff --git a/lib/chat/__tests__/validateChatWorkflow.test.ts b/lib/chat/__tests__/validateChatWorkflow.test.ts index 3382f1e02..568fccbab 100644 --- a/lib/chat/__tests__/validateChatWorkflow.test.ts +++ b/lib/chat/__tests__/validateChatWorkflow.test.ts @@ -212,3 +212,14 @@ it("rejects actor overrides, missing explicit dates and obsolete context shape", vi.unstubAllEnvs(); } }); +it("never accepts a body override of the server-owned stream requirement", async () => { + vi.mocked(validateAuthContext).mockResolvedValue({ accountId: ACCOUNT_ID, orgId: null } as never); + const result = await validateChatWorkflow( + new NextRequest("https://test/api/chat", { + method: "POST", + body: JSON.stringify({ ...validBody, streamProtocol: "canonical-base-v1" }), + }), + ); + expect(result).not.toBeInstanceOf(NextResponse); + expect(result).not.toHaveProperty("streamProtocol"); +}); diff --git a/lib/chat/buildRunAgentInput.ts b/lib/chat/buildRunAgentInput.ts index ffa6e90ef..90b8f2f52 100644 --- a/lib/chat/buildRunAgentInput.ts +++ b/lib/chat/buildRunAgentInput.ts @@ -1,3 +1,4 @@ +import type { StreamProtocol } from "./continuation/streamProtocol"; import type { UIMessage } from "ai"; import type { RunAgentWorkflowInput } from "@/app/lib/workflows/runAgentWorkflow"; import type { DurableAgentContext } from "@/lib/agent/tools/AgentContext"; @@ -9,6 +10,7 @@ import type { CatalogSurfaceRequest } from "@/lib/intelligent-ui/catalogSurfaceR export type BuildRunAgentInputParams = { messages: UIMessage[]; + streamProtocol?: StreamProtocol; devCatalogSurface?: CatalogSurfaceRequest; chatId: string; sessionId: string; @@ -45,6 +47,7 @@ export type BuildRunAgentInputParams = { */ export function buildRunAgentInput({ messages, + streamProtocol, devCatalogSurface, chatId, sessionId, @@ -65,6 +68,11 @@ export function buildRunAgentInput({ return { messages, + streamProtocol: + streamProtocol ?? + (!devCatalogSurface && messages.at(-1)?.role === "assistant" + ? "canonical-base-v1" + : "unmarked-v1"), ...(devCatalogSurface ? { devCatalogSurface } : {}), chatId, sessionId, diff --git a/lib/chat/const.ts b/lib/chat/const.ts index cf7f1b4d4..4f93d2fa7 100644 --- a/lib/chat/const.ts +++ b/lib/chat/const.ts @@ -1,30 +1,6 @@ -import { stepCountIs } from "ai"; - export const MAX_MESSAGES = 55; -/** - * Stop condition for multi-step chat agent loops (model → tool → model → …). - * Used by /api/chat (via getGeneralAgent) and /api/chat/workflow (via - * runAgentStep). 111 is high enough that normal flows never hit the cap - * but bounds runaway loops for cost / replay safety. - * - * Single-shot agents (compact, content, email-reply) use `stepCountIs(1)` - * directly — they're not in the multi-step family. - */ -export const CHAT_AGENT_STOP_WHEN = stepCountIs(111); - -/** - * Upper bound on agent-loop iterations in `runAgentWorkflow`. - * - * The durable workflow loops in its own body with ONE `"use step"` per LLM - * call, so this replaces `CHAT_AGENT_STOP_WHEN` for that path — the stop - * condition moved out of `streamText` and into the workflow. Same 111 for - * behavioural parity: high enough that normal flows never hit it, low - * enough to bound a runaway loop. - * - * `CHAT_AGENT_STOP_WHEN` stays for the non-durable `/api/chat` route - * (`getGeneralAgent`), which still runs its tool loop inside `streamText`. - */ +/** Shared loop bound. Keep this module SDK-free so durable workflows can import it. */ export const CHAT_AGENT_MAX_ITERATIONS = 111; export const SYSTEM_PROMPT = `You are Recoup, a friendly, sharp, and strategic AI assistant for the music industry. You help music executives, artist teams, and self-starting artists analyze fan data, optimize marketing, and grow artist careers. diff --git a/lib/chat/continuation/ContinuationError.ts b/lib/chat/continuation/ContinuationError.ts new file mode 100644 index 000000000..bab2f83f3 --- /dev/null +++ b/lib/chat/continuation/ContinuationError.ts @@ -0,0 +1,10 @@ +export class ContinuationError extends Error { + constructor( + public readonly code: + | "stream_continuation_upgrade_required" + | "stream_continuation_evidence_unavailable" + | "stream_continuation_invalid", + ) { + super(code); + } +} diff --git a/lib/chat/continuation/README.md b/lib/chat/continuation/README.md new file mode 100644 index 000000000..ac810b177 --- /dev/null +++ b/lib/chat/continuation/README.md @@ -0,0 +1,56 @@ +# Canonical continuation v1 + +`X-Recoup-Stream-Continuation: canonical-base-v1` advertises parser capability only. +It grants no identity, history provenance or authority. Server-constructed durable +workflow input records `streamProtocol: canonical-base-v1 | unmarked-v1`. +Missing/unknown stored requirements are unknown, never safe legacy defaults. + +A reused assistant emits exactly one start whose messageMetadata.recoupStream is +`{version:1, mode:"continuation", base:{id,role:"assistant",parts,metadata?}}`. +The base is canonical history after verification, never restored native history. +Original payloads inside verified observation parts remain unchanged. Outer start +ID must equal base ID (1..256 characters). Marker/base unknown keys, non-JSON +values, invalid UI parts, raw custom/reasoning-file parts and nested recoupStream +keys in message metadata fail closed. Opaque observation originals, provider metadata +and tool input/output are data: a property named recoupStream there is preserved. Limits: complete marker UTF-8 JSON <=1,048,576 bytes, <=2048 +parts, depth <=32, <=50,000 visited values. No truncation or URL fetching. + +Every reader (initial, resume, tail and terminal success) first verifies current +ownership, then reads configured World input with resolveData:all and existing +SDK/key hydration. Resolve only the actual legacy tuple or strict fenced wrapper; +match run/account/chat/session and exact runAgentWorkflow identity. Protocol version +is the explicit input enum; this does not admit projection producer identities. +Bound raw/hydrated input to16MiB, depth64 and250,000 values and the overall read to +five seconds. Errors expose neither input nor key material. No stream sniffing. + +Unsupported required capability yields409 stream_continuation_upgrade_required. +Unknown/unavailable run evidence yields503 stream_continuation_evidence_unavailable. +Initial post-start failures report admission:"admitted" plus runId; resume failures +report admission:"existing". Neither cancels/restarts the run or reclaims its slot. +Preflight refusal reports admission:"not_admitted", before claims or effects. +Absolute stored event cursors and raw stream bytes are preserved. + +App must consume/validate the marker and reset to its canonical base before SDK, +onData or persistence on ordinary sends, snapshots, autoreconnect and manual resume +before advertising capability. Remove only recoupStream; preserve other metadata. +Unmarked fresh/full replay/new ID/late-start and no-start-tail behavior remain App +controls, as do collisions, scope cancellation and errors. Source tests with +synthetic World/effect ports are not hosted retention, deployment or release proof. + +The three chat preflights (POST /api/chat, GET /api/chat/{chatId}/stream and +POST /api/chat/runs) opt into this additional allowed request header through +getCorsHeaders. Other published CORS contracts are unchanged. Initial readback +also requires the stored requirement to equal the server-selected requirement. + +The disabled fenced reconnect adapter accepts a request, verifies current +ownership, matches the captured original account/chat, then runs the same stored +protocol gate before status, reader/tail or terminal release. It remains disabled; +this change does not grant adapter deployment or database admission. + +After start succeeds, a failed/lost placeholder promotion returns409 with +`{status:"error",error:"chat_stream_ownership_lost",admission:"admitted",runId}`. +Admission means the run was created; it does not claim successful streaming, +completed cancellation or absence of effects. The existing single cancellation +attempt remains unchanged, and its success/failure does not alter this response. +Before-start409 claim/existing-stream conflicts explicitly say not_admitted and +never invent a runId. Clients must treat ambiguous bare409 responses as unknown. diff --git a/lib/chat/continuation/__tests__/continuation.test.ts b/lib/chat/continuation/__tests__/continuation.test.ts new file mode 100644 index 000000000..dc38529e0 --- /dev/null +++ b/lib/chat/continuation/__tests__/continuation.test.ts @@ -0,0 +1,190 @@ +import { describe, it, expect } from "vitest"; +import { buildContinuationMarker } from "../buildContinuationMarker"; +import { selectStreamProtocol } from "../selectStreamProtocol"; +import { assertMarkerFreeHistory } from "../assertMarkerFreeHistory"; +import { validateContinuationRun } from "../validateContinuationRun"; +const base = { + id: "a", + role: "assistant" as const, + parts: [{ type: "text" as const, text: "prior", state: "done" as const }], +}; +const scope = { runId: "run", accountId: "account", chatId: "chat", sessionId: "session" }; +const record = () => ({ + runId: "run", + workflowName: "workflow//./app/lib/workflows/runAgentWorkflow.ts//runAgentWorkflow", + input: [ + { + ...scope, + runId: undefined, + messages: [], + modelId: "model", + agentContext: {}, + streamProtocol: "canonical-base-v1", + }, + ], +}); +describe("canonical continuation contract", () => { + it("requires exact capability for assistant reuse; fresh stays explicitly unmarked", () => { + for (const capability of [null, "unknown", "canonical-base-v1, canonical-base-v1"]) + expect(() => selectStreamProtocol([base], false, capability)).toThrow( + "stream_continuation_upgrade_required", + ); + expect(selectStreamProtocol([base], false, "canonical-base-v1")).toBe("canonical-base-v1"); + expect(selectStreamProtocol([], false, null)).toBe("unmarked-v1"); + expect(selectStreamProtocol([base], true, null)).toBe("unmarked-v1"); + }); + it("builds an immutable exact canonical base without native substitutions", async () => { + const marker = await buildContinuationMarker(base, "a"); + expect(marker).toEqual({ version: 1, mode: "continuation", base }); + expect(marker.base).not.toBe(base); + }); + it.each([ + { ...base, id: "other" }, + { ...base, role: "user" }, + { ...base, extra: true }, + { ...base, parts: [{ type: "custom", kind: "x" }] }, + { ...base, parts: [{ type: "text", text: 1 }] }, + { ...base, metadata: { recoupStream: {} } }, + { ...base, parts: Array.from({ length: 2049 }, () => ({ type: "text", text: "x" })) }, + { ...base, parts: [{ type: "text", text: "x".repeat(1_048_576) }] }, + { ...base, metadata: { bad: NaN } }, + ])("rejects malformed, native, nested or oversized bases", async value => { + await expect(buildContinuationMarker(value, "a")).rejects.toThrow(); + }); + it("rejects reserved control metadata at history ingress", () => { + expect(() => + assertMarkerFreeHistory([{ ...base, metadata: { nested: { recoupStream: {} } } }]), + ).toThrow(); + expect(() => assertMarkerFreeHistory([base])).not.toThrow(); + }); + it("validates stored requirement and exact scope, not a caller claim", () => { + const run = record(); + delete run.input[0].runId; + expect(validateContinuationRun(run, scope, "canonical-base-v1")).toBe("canonical-base-v1"); + expect(() => validateContinuationRun(run, scope, null)).toThrow( + "stream_continuation_upgrade_required", + ); + for (const field of ["accountId", "chatId", "sessionId"] as const) { + const bad = structuredClone(run); + bad.input[0][field] = "other"; + expect(() => validateContinuationRun(bad, scope, "canonical-base-v1")).toThrow(); + } + for (const field of ["runId", "workflowName"] as const) { + const bad = { ...run, [field]: "other" }; + expect(() => validateContinuationRun(bad, scope, "canonical-base-v1")).toThrow(); + } + for (const protocol of [undefined, null, "unknown"]) { + expect(() => + validateContinuationRun( + { ...run, input: [{ ...run.input[0], streamProtocol: protocol }] }, + scope, + "canonical-base-v1", + ), + ).toThrow(); + } + expect(() => + validateContinuationRun({ ...run, expiredAt: new Date() }, scope, "canonical-base-v1"), + ).toThrow(); + }); +}); +it("rejects deep/value-heavy, accessor and non-JSON markers without invoking accessors", async () => { + let deep: unknown = null; + for (let i = 0; i < 35; i++) deep = { deep }; + await expect(buildContinuationMarker({ ...base, metadata: deep }, "a")).rejects.toThrow(); + await expect( + buildContinuationMarker({ ...base, metadata: Array(50_001).fill(0) }, "a"), + ).rejects.toThrow(); + const metadata = Object.defineProperty({}, "private", { + get() { + throw new Error("getter invoked"); + }, + enumerable: true, + }); + await expect(buildContinuationMarker({ ...base, metadata }, "a")).rejects.toThrow( + "stream_continuation_invalid", + ); + await expect(buildContinuationMarker({ ...base, metadata: new Date() }, "a")).rejects.toThrow(); +}); +it("preserves originals nested inside canonical observation data", async () => { + const canonical = { + ...base, + parts: [ + { + type: "data-recoup-sdk-observation", + id: "observation", + data: { original: { type: "custom", kind: "provider-part", data: { text: "retained" } } }, + }, + ...base.parts, + ], + }; + expect((await buildContinuationMarker(canonical, "a")).base).toEqual(canonical); +}); +it("retains opaque reserved-name keys inside provider originals and tool output", async () => { + const opaque = { recoupStream: { ordinary: "opaque value" } }; + const canonical = { + ...base, + parts: [ + { + type: "data-recoup-sdk-observation", + id: "observation", + data: { + original: { + type: "custom", + kind: "provider-content", + providerMetadata: { provider: opaque }, + }, + }, + }, + { + type: "tool-example", + toolCallId: "tool", + state: "output-available", + input: {}, + output: opaque, + }, + ], + }; + expect(() => assertMarkerFreeHistory([canonical])).not.toThrow(); + expect((await buildContinuationMarker(canonical, "a")).base).toEqual(canonical); +}); +it("parses only the actual fenced tuple and binds its authority", () => { + const accountId = "11111111-1111-4111-8111-111111111111"; + const run = record(); + delete run.input[0].runId; + const invocation = { + kind: "internal-fenced/v1", + input: { ...run.input[0], accountId }, + fence: { + authority: { + chatId: "chat", + effectiveAccount: accountId, + epoch: 1, + owner: "22222222-2222-4222-8222-222222222222", + }, + attemptId: "33333333-3333-4333-8333-333333333333", + turn: { kind: "same-turn-resume", assistantId: "a" }, + }, + }; + expect( + validateContinuationRun( + { ...run, input: [invocation] }, + { ...scope, accountId }, + "canonical-base-v1", + ), + ).toBe("canonical-base-v1"); + expect(() => + validateContinuationRun( + { ...run, input: { arbitrary: [invocation] } }, + { ...scope, accountId }, + "canonical-base-v1", + ), + ).toThrow(); + invocation.fence.authority.chatId = "other"; + expect(() => + validateContinuationRun( + { ...run, input: [invocation] }, + { ...scope, accountId }, + "canonical-base-v1", + ), + ).toThrow(); +}); diff --git a/lib/chat/continuation/__tests__/readContinuationRun.test.ts b/lib/chat/continuation/__tests__/readContinuationRun.test.ts new file mode 100644 index 000000000..113097ff3 --- /dev/null +++ b/lib/chat/continuation/__tests__/readContinuationRun.test.ts @@ -0,0 +1,121 @@ +import { createRequire } from "node:module"; +import { expect, it, vi } from "vitest"; +import { readContinuationRun } from "../readContinuationRun"; +import { gateStoredContinuation } from "../gateStoredContinuation"; +import { CONTINUATION_WORKFLOW } from "../streamProtocol"; +const require = createRequire(import.meta.url); +const { stringify } = createRequire(require.resolve("@workflow/core/serialization-format"))( + "devalue", +); +const { getWorld } = vi.hoisted(() => ({ getWorld: vi.fn() })); +vi.mock("workflow/runtime", () => ({ getWorld })); +const scope = { runId: "run", accountId: "account", chatId: "chat", sessionId: "session" }; +const input = [ + { + accountId: "account", + chatId: "chat", + sessionId: "session", + messages: [], + modelId: "model", + agentContext: {}, + streamProtocol: "canonical-base-v1", + }, +]; +function fixture(data: unknown = input) { + const world = { + runs: { + get: vi.fn(async () => ({ + runId: "run", + workflowName: CONTINUATION_WORKFLOW, + input: + data instanceof Uint8Array ? data : new TextEncoder().encode("devl" + stringify(data)), + })), + }, + getEncryptionKeyForRun: vi.fn(async () => undefined), + }; + getWorld.mockReturnValue(world); + return world; +} +it("uses exact configured run read and existing hydration without stream access", async () => { + const world = fixture(new TextEncoder().encode('devl[[1],{"chatId":2},"chat"]')); + const result = await readContinuationRun(world as never, "run", new AbortController().signal); + expect(result.input).toEqual([{ chatId: "chat" }]); + expect(world.runs.get).toHaveBeenCalledExactlyOnceWith("run", { resolveData: "all" }); +}); +it.each([ + new Uint8Array(16_777_217), + new TextEncoder().encode("encrno-key"), + new TextEncoder().encode("devlinvalid"), +])("sanitizes oversized, undecryptable and malformed input", async data => { + const world = fixture(data); + await expect( + readContinuationRun(world as never, "run", new AbortController().signal), + ).rejects.toMatchObject({ code: "stream_continuation_evidence_unavailable" }); + expect(world.runs.get).toHaveBeenCalledTimes(1); +}); +it("bounds a stuck read without retrying", async () => { + const world = fixture(); + world.runs.get.mockImplementation(() => new Promise(() => {})); + const controller = new AbortController(); + const result = readContinuationRun(world as never, "run", controller.signal); + controller.abort(); + await expect(result).rejects.toMatchObject({ code: "stream_continuation_evidence_unavailable" }); + expect(world.runs.get.mock.calls.length).toBeLessThanOrEqual(1); +}); +it("sanitizes backend exceptions without exposing input or credentials", async () => { + const world = fixture(); + world.runs.get.mockRejectedValue(new Error("private-token")); + const response = await gateStoredContinuation(new Request("https://test"), scope, "admitted"); + expect(response?.status).toBe(503); + expect(await response?.json()).toEqual({ + status: "error", + error: "stream_continuation_evidence_unavailable", + admission: "admitted", + runId: "run", + }); +}); +it("requires capability for marked runs and does not reclassify from a header", async () => { + fixture(); + expect( + (await gateStoredContinuation(new Request("https://test"), scope, "existing"))?.status, + ).toBe(409); + expect( + await gateStoredContinuation( + new Request("https://test", { + headers: { "X-Recoup-Stream-Continuation": "canonical-base-v1" }, + }), + scope, + "existing", + ), + ).toBeNull(); + fixture([{ ...input[0], streamProtocol: undefined }]); + expect( + ( + await gateStoredContinuation( + new Request("https://test", { + headers: { "X-Recoup-Stream-Continuation": "canonical-base-v1" }, + }), + scope, + "existing", + ) + )?.status, + ).toBe(503); + fixture([{ ...input[0], streamProtocol: "unmarked-v1" }]); + expect(await gateStoredContinuation(new Request("https://test"), scope, "existing")).toBeNull(); +}); +it("rejects initial readback that changes the server-selected requirement", async () => { + fixture([{ ...input[0], streamProtocol: "unmarked-v1" }]); + const response = await gateStoredContinuation( + new Request("https://test", { + headers: { "X-Recoup-Stream-Continuation": "canonical-base-v1" }, + }), + scope, + "admitted", + "canonical-base-v1", + ); + expect(response?.status).toBe(503); + expect(await response?.json()).toMatchObject({ + admission: "admitted", + error: "stream_continuation_evidence_unavailable", + }); +}); diff --git a/lib/chat/continuation/assertBoundedRunData.ts b/lib/chat/continuation/assertBoundedRunData.ts new file mode 100644 index 000000000..c0fd1e0a1 --- /dev/null +++ b/lib/chat/continuation/assertBoundedRunData.ts @@ -0,0 +1,32 @@ +import { ContinuationError } from "./ContinuationError"; +/** Bound serialized World input before hydration, including encrypted binary envelopes. */ +export function assertBoundedRunData(value: unknown) { + let bytes = 0; + let values = 0; + const ancestors = new Set(); + function walk(item: unknown, depth: number) { + if (++values > 250_000 || depth > 64) throw new Error(); + if (typeof item === "string") bytes += Buffer.byteLength(item, "utf8"); + else if (item instanceof Uint8Array) bytes += item.byteLength; + else if (item && typeof item === "object") { + if (ancestors.has(item)) throw new Error(); + ancestors.add(item); + const keys = Reflect.ownKeys(item); + if (keys.length > 250_000 - values) throw new Error(); + for (const key of keys) { + if (typeof key !== "string") throw new Error(); + bytes += Buffer.byteLength(key, "utf8") + 4; + const descriptor = Object.getOwnPropertyDescriptor(item, key)!; + if (!("value" in descriptor)) throw new Error(); + walk(descriptor.value, depth + 1); + } + ancestors.delete(item); + } else bytes += 8; + if (bytes > 16_777_216) throw new Error(); + } + try { + walk(value, 0); + } catch { + throw new ContinuationError("stream_continuation_evidence_unavailable"); + } +} diff --git a/lib/chat/continuation/assertMarkerFreeHistory.ts b/lib/chat/continuation/assertMarkerFreeHistory.ts new file mode 100644 index 000000000..880ea2735 --- /dev/null +++ b/lib/chat/continuation/assertMarkerFreeHistory.ts @@ -0,0 +1,28 @@ +import { encodeBoundedContinuationValue } from "./encodeBoundedContinuationValue"; +import { ContinuationError } from "./ContinuationError"; +/** Controls in message metadata are reserved; opaque part/provider/tool payload keys are data. */ +export function assertMarkerFreeHistory(messages: unknown) { + encodeBoundedContinuationValue(messages, { + maxBytes: 16_777_216, + maxDepth: 64, + maxValues: 250_000, + omitUndefined: true, + }); + if (!Array.isArray(messages)) throw new ContinuationError("stream_continuation_invalid"); + for (const message of messages) { + if (!message || typeof message !== "object") + throw new ContinuationError("stream_continuation_invalid"); + if (Object.hasOwn(message, "recoupStream")) + throw new ContinuationError("stream_continuation_invalid"); + for (const field of ["metadata", "messageMetadata"]) { + if (message[field] !== undefined) + encodeBoundedContinuationValue(message[field], { + rejectMarker: true, + maxBytes: 16_777_216, + maxDepth: 64, + maxValues: 250_000, + omitUndefined: true, + }); + } + } +} diff --git a/lib/chat/continuation/buildContinuationMarker.ts b/lib/chat/continuation/buildContinuationMarker.ts new file mode 100644 index 000000000..727ecb1ee --- /dev/null +++ b/lib/chat/continuation/buildContinuationMarker.ts @@ -0,0 +1,37 @@ +import { assertMarkerFreeHistory } from "./assertMarkerFreeHistory"; +import { validateUIMessages, type UIMessage } from "ai"; +import { z } from "zod"; +import { encodeBoundedContinuationValue } from "./encodeBoundedContinuationValue"; +import { ContinuationError } from "./ContinuationError"; +const schema = z + .object({ + id: z.string().min(1).max(256), + role: z.literal("assistant"), + parts: z.array(z.object({ type: z.string().min(1) }).passthrough()).max(2048), + metadata: z.unknown().optional(), + }) + .strict(); +/** Canonical base only; validation never translates or removes observation payloads. */ +export async function buildContinuationMarker(value: unknown, messageId: string) { + assertMarkerFreeHistory([value]); + const marker = { version: 1 as const, mode: "continuation" as const, base: value }; + // Bounds apply to the complete marker, including its wrapper. + const json = encodeBoundedContinuationValue(marker); + const base = schema.safeParse(value); + if ( + !base.success || + base.data.id !== messageId || + base.data.parts.some(part => + ["custom", "reasoning-file", "tool-approval-request", "tool-approval-response"].includes( + part.type, + ), + ) + ) + throw new ContinuationError("stream_continuation_invalid"); + try { + await validateUIMessages({ messages: [value] }); + } catch { + throw new ContinuationError("stream_continuation_invalid"); + } + return JSON.parse(json) as { version: 1; mode: "continuation"; base: UIMessage }; +} diff --git a/lib/chat/continuation/encodeBoundedContinuationValue.ts b/lib/chat/continuation/encodeBoundedContinuationValue.ts new file mode 100644 index 000000000..f2f617bba --- /dev/null +++ b/lib/chat/continuation/encodeBoundedContinuationValue.ts @@ -0,0 +1,41 @@ +import { encodeStrictJson } from "../fence/encodeStrictJson"; +import { ContinuationError } from "./ContinuationError"; +/** Inspect descriptors before serialization: never invoke getters or toJSON. */ +export function encodeBoundedContinuationValue( + value: unknown, + options: { + maxBytes?: number; + maxDepth?: number; + maxValues?: number; + rejectMarker?: boolean; + omitUndefined?: boolean; + } = {}, +) { + let remaining = options.maxValues ?? 50_000; + const ancestors = new Set(); + function walk(item: unknown, depth: number) { + if (--remaining < 0 || depth > (options.maxDepth ?? 32)) throw new Error("bound"); + if (!item || typeof item !== "object") return; + if (ancestors.has(item)) throw new Error("cycle"); + ancestors.add(item); + const keys = Reflect.ownKeys(item); + if (keys.length > remaining + 1) throw new Error("bound"); + for (const key of keys) { + if (Array.isArray(item) && key === "length") continue; + if (options.rejectMarker && key === "recoupStream") throw new Error("reserved"); + const descriptor = Object.getOwnPropertyDescriptor(item, key)!; + if (!("value" in descriptor)) throw new Error("accessor"); + walk(descriptor.value, depth + 1); + } + ancestors.delete(item); + } + try { + walk(value, 0); + return encodeStrictJson(value, { + maxBytes: options.maxBytes ?? 1_048_576, + omitUndefinedObjectProperties: options.omitUndefined, + }); + } catch { + throw new ContinuationError("stream_continuation_invalid"); + } +} diff --git a/lib/chat/continuation/gateStoredContinuation.ts b/lib/chat/continuation/gateStoredContinuation.ts new file mode 100644 index 000000000..d563c920b --- /dev/null +++ b/lib/chat/continuation/gateStoredContinuation.ts @@ -0,0 +1,33 @@ +import { errorResponse } from "@/lib/networking/errorResponse"; +import { readContinuationRun } from "./readContinuationRun"; +import { validateContinuationRun, type ContinuationScope } from "./validateContinuationRun"; +import { CONTINUATION_HEADER, type StreamProtocol } from "./streamProtocol"; +import { ContinuationError } from "./ContinuationError"; +/** Gate before any reader/tail/terminal response; failure never mutates the admitted run. */ +export async function gateStoredContinuation( + request: Request, + scope: ContinuationScope, + admission: "admitted" | "existing", + expectedProtocol?: StreamProtocol, +) { + try { + const { getWorld } = await import("workflow/runtime"); + const signal = AbortSignal.any([request.signal, AbortSignal.timeout(5_000)]); + const record = await readContinuationRun(getWorld(), scope.runId, signal); + const protocol = validateContinuationRun( + record, + scope, + request.headers.get(CONTINUATION_HEADER), + ); + if (expectedProtocol !== undefined && protocol !== expectedProtocol) + throw new ContinuationError("stream_continuation_evidence_unavailable"); + return null; + } catch (error) { + const code = + error instanceof ContinuationError ? error.code : "stream_continuation_evidence_unavailable"; + return errorResponse(code, code === "stream_continuation_upgrade_required" ? 409 : 503, { + admission, + runId: scope.runId, + }); + } +} diff --git a/lib/chat/continuation/readContinuationRun.ts b/lib/chat/continuation/readContinuationRun.ts new file mode 100644 index 000000000..d22324f79 --- /dev/null +++ b/lib/chat/continuation/readContinuationRun.ts @@ -0,0 +1,34 @@ +import type { getWorld } from "workflow/runtime"; +import { hydrateProjectionEvidence } from "../projection/hydrateProjectionEvidence"; +import { readProjectionEvidence } from "../projection/readProjectionEvidence"; +import { assertBoundedRunData } from "./assertBoundedRunData"; +import { encodeBoundedContinuationValue } from "./encodeBoundedContinuationValue"; +import { ContinuationError } from "./ContinuationError"; +/** Only configured World/key resolution; no stream reads, caller key, fallback or retries. */ +export async function readContinuationRun( + world: Pick, "runs" | "getEncryptionKeyForRun">, + runId: string, + signal: AbortSignal, +) { + try { + const run = await readProjectionEvidence( + () => world.runs.get(runId, { resolveData: "all" }), + signal, + ); + if (run.runId !== runId || run.expiredAt != null) throw new Error(); + assertBoundedRunData(run.input); + const input = await readProjectionEvidence( + () => hydrateProjectionEvidence(run.input, runId, world, signal, run), + signal, + ); + encodeBoundedContinuationValue(input, { + maxBytes: 16_777_216, + maxDepth: 64, + maxValues: 250_000, + omitUndefined: true, + }); + return { runId: run.runId, workflowName: run.workflowName, expiredAt: run.expiredAt, input }; + } catch { + throw new ContinuationError("stream_continuation_evidence_unavailable"); + } +} diff --git a/lib/chat/continuation/selectStreamProtocol.ts b/lib/chat/continuation/selectStreamProtocol.ts new file mode 100644 index 000000000..b38bcc4a9 --- /dev/null +++ b/lib/chat/continuation/selectStreamProtocol.ts @@ -0,0 +1,16 @@ +import type { UIMessage } from "ai"; +import type { StreamProtocol } from "./streamProtocol"; +import { ContinuationError } from "./ContinuationError"; +/** Server-selected reuse behavior; request bodies cannot override this requirement. */ +export function selectStreamProtocol( + messages: UIMessage[], + freshSurface: boolean, + capability: string | null, +): StreamProtocol { + if (!freshSurface && messages.at(-1)?.role === "assistant") { + if (capability !== "canonical-base-v1") + throw new ContinuationError("stream_continuation_upgrade_required"); + return "canonical-base-v1"; + } + return "unmarked-v1"; +} diff --git a/lib/chat/continuation/streamProtocol.ts b/lib/chat/continuation/streamProtocol.ts new file mode 100644 index 000000000..2aa10e13c --- /dev/null +++ b/lib/chat/continuation/streamProtocol.ts @@ -0,0 +1,6 @@ +import { z } from "zod"; +export const streamProtocolSchema = z.enum(["canonical-base-v1", "unmarked-v1"]); +export type StreamProtocol = z.infer; +export const CONTINUATION_HEADER = "X-Recoup-Stream-Continuation"; +export const CONTINUATION_WORKFLOW = + "workflow//./app/lib/workflows/runAgentWorkflow.ts//runAgentWorkflow"; diff --git a/lib/chat/continuation/validateContinuationRun.ts b/lib/chat/continuation/validateContinuationRun.ts new file mode 100644 index 000000000..2b1e53780 --- /dev/null +++ b/lib/chat/continuation/validateContinuationRun.ts @@ -0,0 +1,38 @@ +import { parseProjectionRunAuthority } from "../projection/parseProjectionRunAuthority"; +import { CONTINUATION_WORKFLOW, streamProtocolSchema } from "./streamProtocol"; +import { ContinuationError } from "./ContinuationError"; +export type ContinuationScope = { + runId: string; + accountId: string; + chatId: string; + sessionId: string; +}; +/** A trusted current scope plus a configured-World record, never a nested caller claim. */ +export function validateContinuationRun( + record: { runId: string; workflowName: string; expiredAt?: unknown; input: unknown }, + scope: ContinuationScope, + capability: string | null, +) { + let input; + try { + if ( + record.runId !== scope.runId || + record.workflowName !== CONTINUATION_WORKFLOW || + record.expiredAt != null + ) + throw new Error(); + input = parseProjectionRunAuthority(record.input); + if ( + input.accountId !== scope.accountId || + input.chatId !== scope.chatId || + input.sessionId !== scope.sessionId + ) + throw new Error(); + streamProtocolSchema.parse(input.streamProtocol); + } catch { + throw new ContinuationError("stream_continuation_evidence_unavailable"); + } + if (input.streamProtocol === "canonical-base-v1" && capability !== "canonical-base-v1") + throw new ContinuationError("stream_continuation_upgrade_required"); + return input.streamProtocol; +} diff --git a/lib/chat/fence/__tests__/executionSnapshot.test.ts b/lib/chat/fence/__tests__/executionSnapshot.test.ts index 71b7883fc..e7242aad3 100644 --- a/lib/chat/fence/__tests__/executionSnapshot.test.ts +++ b/lib/chat/fence/__tests__/executionSnapshot.test.ts @@ -140,3 +140,20 @@ it("rejects a bound original whose dispatch history says never attempted", () => }).receipt.bound_run_id, ).toBe("original-run"); }); + +it("binds stream protocol in the execution digest and rejects missing requirement", () => { + const base = { id: "protocol-snapshot", requestId, workflowInput, credentialPolicy: policy }; + const original = buildChatExecutionSnapshot(base); + const changed = buildChatExecutionSnapshot({ + ...base, + workflowInput: { ...workflowInput, streamProtocol: "canonical-base-v1" }, + }); + expect(changed.digest).not.toBe(original.digest); + expect(changed.snapshot.content.streamProtocol).toBe("canonical-base-v1"); + expect(() => + buildChatExecutionSnapshot({ + ...base, + workflowInput: { ...workflowInput, streamProtocol: undefined } as never, + }), + ).toThrow(); +}); diff --git a/lib/chat/fence/__tests__/snapshotFixture.ts b/lib/chat/fence/__tests__/snapshotFixture.ts index 922cc3e0d..4a7d9f03f 100644 --- a/lib/chat/fence/__tests__/snapshotFixture.ts +++ b/lib/chat/fence/__tests__/snapshotFixture.ts @@ -3,6 +3,7 @@ import { canonicalizeChatAdmission } from "../canonicalizeChatAdmission"; export const account = "11111111-1111-4111-8111-111111111111"; export const requestId = "22222222-2222-4222-8222-222222222222"; export const workflowInput = { + streamProtocol: "unmarked-v1" as const, messages: [ { id: "user-1", role: "user" as const, parts: [{ type: "text" as const, text: "hello" }] }, ], diff --git a/lib/chat/fence/buildChatExecutionSnapshot.ts b/lib/chat/fence/buildChatExecutionSnapshot.ts index dad23574e..485100104 100644 --- a/lib/chat/fence/buildChatExecutionSnapshot.ts +++ b/lib/chat/fence/buildChatExecutionSnapshot.ts @@ -1,3 +1,4 @@ +import { assertMarkerFreeHistory } from "../continuation/assertMarkerFreeHistory"; import { createHash } from "node:crypto"; import type { RunAgentWorkflowInput } from "@/app/lib/workflows/runAgentWorkflow"; import { chatExecutionSnapshotSchema } from "./chatExecutionSnapshotSchema"; @@ -15,6 +16,7 @@ export function buildChatExecutionSnapshot({ workflowInput: RunAgentWorkflowInput; credentialPolicy: unknown; }) { + assertMarkerFreeHistory(input.messages); const { sandbox, skills, recoupOrgId } = input.agentContext; const { state } = sandbox; const source = state.source; @@ -26,6 +28,7 @@ export function buildChatExecutionSnapshot({ chatId: input.chatId, sessionId: input.sessionId, content: { + streamProtocol: input.streamProtocol, options: { modelId: input.modelId, artistId: input.artistId ?? null, diff --git a/lib/chat/fence/chatExecutionSnapshotSchema.ts b/lib/chat/fence/chatExecutionSnapshotSchema.ts index 10d5fc067..dc77a22c7 100644 --- a/lib/chat/fence/chatExecutionSnapshotSchema.ts +++ b/lib/chat/fence/chatExecutionSnapshotSchema.ts @@ -1,3 +1,4 @@ +import { streamProtocolSchema } from "../continuation/streamProtocol"; import { z } from "zod"; import { chatAdmissionSchema } from "./chatAdmissionSchema"; const text = z.string().min(1); @@ -45,6 +46,7 @@ export const chatExecutionSnapshotSchema = z content: z .object({ options: chatAdmissionSchema.shape.options, + streamProtocol: streamProtocolSchema, sessionTitle: z.string().nullable(), repoOwner: optionalText, repoName: optionalText, diff --git a/lib/chat/fence/lifecycle/__tests__/lifecycle.test.ts b/lib/chat/fence/lifecycle/__tests__/lifecycle.test.ts index b216efbe8..3a347384e 100644 --- a/lib/chat/fence/lifecycle/__tests__/lifecycle.test.ts +++ b/lib/chat/fence/lifecycle/__tests__/lifecycle.test.ts @@ -1,7 +1,19 @@ +import { NextRequest } from "next/server"; +import { gateStoredContinuation } from "@/lib/chat/continuation/gateStoredContinuation"; +import { validateChatOwnership } from "@/lib/chat/validateChatOwnership"; import { beforeEach, afterEach, expect, it, vi } from "vitest"; import { getRun } from "workflow/api"; import { stopFencedChatWorkflow } from "../stopFencedChatWorkflow"; import { resumeFencedChatStream } from "../resumeFencedChatStream"; +vi.mock("@/lib/chat/continuation/gateStoredContinuation", () => ({ + gateStoredContinuation: vi.fn(async () => null), +})); +vi.mock("@/lib/chat/validateChatOwnership", () => ({ + validateChatOwnership: vi.fn(async () => ({ + auth: { accountId: "11111111-1111-4111-8111-111111111111" }, + chat: { id: "chat", session_id: "session" }, + })), +})); const { rpc } = vi.hoisted(() => ({ rpc: vi.fn() })); vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc } })); vi.mock("workflow/api", () => ({ getRun: vi.fn() })); @@ -20,10 +32,15 @@ const current = { phase: "running", run_id: target.runId, }; -const url = new URL("https://api.test/stream?startIndex=3"); +const url = new NextRequest("https://api.test/stream?startIndex=3"); const cancel = vi.fn(); beforeEach(() => { vi.resetAllMocks(); + vi.mocked(gateStoredContinuation).mockResolvedValue(null); + vi.mocked(validateChatOwnership).mockResolvedValue({ + auth: { accountId: target.effectiveAccount }, + chat: { id: target.chatId, session_id: "session" }, + } as never); vi.useFakeTimers(); rpc.mockImplementation(async (_name, args) => ({ data: args.p_action === "state" ? current : { released: true }, @@ -253,8 +270,25 @@ it.each(["running", "pending"])( ); it("invalid resume index returns400 before lifecycle/SDK effects", async () => { expect( - (await resumeFencedChatStream(target, new URL("https://api.test?startIndex=-1"))).status, + (await resumeFencedChatStream(target, new NextRequest("https://api.test?startIndex=-1"))) + .status, ).toBe(400); expect(rpc).not.toHaveBeenCalled(); expect(getRun).not.toHaveBeenCalled(); }); +it.each(["running", "completed"])( + "requires stored protocol before fenced %s reader or terminal release", + async status => { + vi.mocked(getRun).mockReturnValue({ + status: Promise.resolve(status), + getReadable: vi.fn(), + } as never); + vi.mocked(gateStoredContinuation).mockResolvedValueOnce( + new Response(null, { status: 409 }) as never, + ); + const response = await resumeFencedChatStream(target, url); + expect(response.status).toBe(409); + expect(getRun).not.toHaveBeenCalled(); + expect(rpc.mock.calls.map(([, args]) => args.p_action)).toEqual(["state"]); + }, +); diff --git a/lib/chat/fence/lifecycle/__tests__/sqlLifecycleTrace.test.ts b/lib/chat/fence/lifecycle/__tests__/sqlLifecycleTrace.test.ts index 3e92e0eab..6b504bc95 100644 --- a/lib/chat/fence/lifecycle/__tests__/sqlLifecycleTrace.test.ts +++ b/lib/chat/fence/lifecycle/__tests__/sqlLifecycleTrace.test.ts @@ -1,3 +1,5 @@ +import { NextRequest } from "next/server"; +import { validateChatOwnership } from "@/lib/chat/validateChatOwnership"; import { buildChatExecutionSnapshot } from "../../buildChatExecutionSnapshot"; import { canonicalizeChatAdmission } from "../../canonicalizeChatAdmission"; import { readFileSync, writeFileSync } from "node:fs"; @@ -6,6 +8,15 @@ import { getRun } from "workflow/api"; import { stopFencedChatWorkflow } from "../stopFencedChatWorkflow"; import { resumeFencedChatStream } from "../resumeFencedChatStream"; import { account, requestId, workflowInput, policy } from "../../__tests__/snapshotFixture"; +vi.mock("@/lib/chat/continuation/gateStoredContinuation", () => ({ + gateStoredContinuation: vi.fn(async () => null), +})); +vi.mock("@/lib/chat/validateChatOwnership", () => ({ + validateChatOwnership: vi.fn(async () => ({ + auth: { accountId: "11111111-1111-4111-8111-111111111111" }, + chat: { id: "chat", session_id: "session" }, + })), +})); const { rpc } = vi.hoisted(() => ({ rpc: vi.fn() })); vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc } })); vi.mock("workflow/api", () => ({ getRun: vi.fn() })); @@ -117,8 +128,12 @@ it("records actual adapter RPC commands and synthetic SDK evidence for pinned SQ const input = name.startsWith("pending") ? { ...target, phase: "pending" as const, runId: null } : target; + vi.mocked(validateChatOwnership).mockResolvedValue({ + auth: { accountId: target.effectiveAccount }, + chat: { id: target.chatId, session_id: inputSnapshot.sessionId }, + } as never); const response = name.includes("resume") - ? await resumeFencedChatStream(input, new URL("https://api.test/stream")) + ? await resumeFencedChatStream(input, new NextRequest("https://api.test/stream")) : await stopFencedChatWorkflow(input); const status = name === "pending-close-wins" || name === "stop-success" || name === "resume-terminal" diff --git a/lib/chat/fence/lifecycle/resumeFencedChatStream.ts b/lib/chat/fence/lifecycle/resumeFencedChatStream.ts index 926608191..69ae55600 100644 --- a/lib/chat/fence/lifecycle/resumeFencedChatStream.ts +++ b/lib/chat/fence/lifecycle/resumeFencedChatStream.ts @@ -1,4 +1,6 @@ -import { NextResponse } from "next/server"; +import { validateChatOwnership } from "@/lib/chat/validateChatOwnership"; +import { gateStoredContinuation } from "@/lib/chat/continuation/gateStoredContinuation"; +import { NextRequest, NextResponse } from "next/server"; import { getRun } from "workflow/api"; import { createUIMessageStreamResponse } from "ai"; import { TERMINAL_WORKFLOW_RUN_STATUSES } from "@/lib/const"; @@ -14,9 +16,13 @@ import type { ChatLifecycleTarget } from "./chatLifecycleTargetSchema"; /** Disabled read-only reconnect adapter; disconnect never cancels a workflow. */ export async function resumeFencedChatStream( input: ChatLifecycleTarget, - url: URL, + request: NextRequest, ): Promise { - const startIndex = parseStreamStartIndex(url); + const validated = await validateChatOwnership(request, input.chatId); + if (validated instanceof NextResponse) return validated; + if (validated.auth.accountId !== input.effectiveAccount || validated.chat.id !== input.chatId) + return errorResponse("Forbidden", 403); + const startIndex = parseStreamStartIndex(new URL(request.url)); if (startIndex instanceof NextResponse) return startIndex; const original = await readOriginalChatLifecycle(input); if (original.state === "pending") @@ -27,6 +33,17 @@ export async function resumeFencedChatStream( 503, ); const target = original.target; + const gate = await gateStoredContinuation( + request, + { + runId: target.runId, + accountId: validated.auth.accountId, + chatId: validated.chat.id, + sessionId: validated.chat.session_id, + }, + "existing", + ); + if (gate) return gate; let run, status; try { run = getRun(target.runId); diff --git a/lib/chat/gateChatStreamStart.ts b/lib/chat/gateChatStreamStart.ts index 3c9b5bda0..f046b1679 100644 --- a/lib/chat/gateChatStreamStart.ts +++ b/lib/chat/gateChatStreamStart.ts @@ -20,6 +20,7 @@ export async function gateChatStreamStart( return errorResponse( "A response is already streaming for this chat; reconnect via GET /api/chat/{chatId}/stream before retrying this message", 409, + { admission: "not_admitted" }, ); } if (reconciled.action === "conflict") { diff --git a/lib/chat/handleChatWorkflowStream.ts b/lib/chat/handleChatWorkflowStream.ts index 55c8f8078..ad49688f9 100644 --- a/lib/chat/handleChatWorkflowStream.ts +++ b/lib/chat/handleChatWorkflowStream.ts @@ -1,3 +1,9 @@ +import { selectStreamProtocol } from "./continuation/selectStreamProtocol"; +import { buildContinuationMarker } from "./continuation/buildContinuationMarker"; +import { CONTINUATION_HEADER, type StreamProtocol } from "./continuation/streamProtocol"; +import { gateStoredContinuation } from "./continuation/gateStoredContinuation"; +import { ContinuationError } from "./continuation/ContinuationError"; +import { prepareAuthorizedProjectionHistory } from "./projection/prepareAuthorizedProjectionHistory"; import { DEFAULT_MODEL } from "@/lib/const"; import { NextRequest, NextResponse } from "next/server"; import { createUIMessageStreamResponse } from "ai"; @@ -73,6 +79,34 @@ export async function handleChatWorkflowStream(request: NextRequest): Promise Promise; + readStep: (runId: string, stepId: string, signal: AbortSignal) => Promise; + readReceipt: ( + runId: string, + producerStepId: string, + proofStepName: string, + signal: AbortSignal, + ) => Promise; + readCanonical: (runId: string, signal: AbortSignal) => Promise; +}; +export type ProjectionAuthority = { accountId: string; chatId: string; sessionId: string }; +/** Server-reviewed deployment identities only. Empty means no producer is admitted. */ +export type ProjectionProducer = { + deploymentId: string; + workflowName: string; + stepName: string; + proofStepName: string; +}; diff --git a/lib/chat/projection/README.md b/lib/chat/projection/README.md new file mode 100644 index 000000000..2aca4b9dc --- /dev/null +++ b/lib/chat/projection/README.md @@ -0,0 +1,25 @@ +# SDK 7 canonical projection — integration under review + +Chat ingress, history preparation, fresh producer collection and required persistence are wired in source. No deployments are admitted in `projectionProducers`; projected history or generated observations therefore cannot pass production evidence verification until deployment admission and retention are qualified. This source is not release approval. + +`data-recoup-sdk-observation` carries the exact custom/reasoning-file UI part, origin run and producer step, assistant identity, ordinal and adjacent fallback span. Fallback text says only that this view cannot display content. A namespace, client hash, matching database row or echoed seed is never provenance. + +Interactive ingress verifies current session/chat ownership before proof reads and before claiming a stream or persisting input. The workflow repeats verification after trusted admission/bind and before any user write, same-turn `update_parts`, model conversion or seed. History preparation keeps canonical messages and unrelated tool-answer edits intact; only verified observation/fallback pairs become native parts in model history. Unverified raw custom/reasoning-file and standalone approval parts are rejected. Headless new-chat and room-based paths lack matching origin-chat authority and reject carried observations. The public allowlist is empty, not configurable by request input. + +`runAgentStep` passes only newly yielded SDK chunks to `collectCanonicalProjection`. Seeded canonical observations never enter its fresh proof collection. The collector emits canonical events before durable writes, tracks SDK append/upsert rules for provisional span indexes, then uses the actual installed SDK for final canonical assembly and checks every emitted observation's adjacent span. Native SDK UI output and `responseMessages` remain separate for subsequent model iterations. A successful public writer call is not a storage ACK. + +The workflow awaits the completed model producer, then invokes `recordProjectionProofStep` as a separate deterministic journaled step. It next verifies fresh completed producer/receipt evidence and actual raw canonical readback under configured producer admission before persisting the projected message. Legacy projected writes require an exact returned message row; fenced writes retain their existing required receipts. Unknown write outcomes fail for reconciliation without automatic provider or write re-execution. There is no atomic stream/message commit claim. + +Compatibility generation failures retain known seeded usage/cost before any fresh finish metadata, then replace that observation with the callback's cumulative totals when available; they do not add the seed twice. Current/final usage stays explicitly incomplete in the failure result. Receipt/readback/message failures retain the completed producer result. These failures emit an error finish, bypass new billing and auto-commit, and do not successfully release fenced authority. Unknown usage is not zero. Normal successful projection retains the existing one post-loop charge path. `handleChatCredits` returning void is not settlement proof. Existing unrelated failure finance behavior remains separate. Genuine Stop is distinct from typed compatibility/write failure even with projected history: the collector assembles the accepted canonical prefix and fresh proof candidates, then the workflow requires its usual proof/readback/message ACK before the existing single Stop charge; auto-commit remains skipped. Typed evidence/write errors are never downgraded to Stop merely because cancellation also fired. + +`verifyProjectionObservation` requires current authority and exact server-approved deployment/workflow/producer-step/proof-step identities. It checks strict invocation shape, fresh completed outputs, distinct receipt linkage, original span and raw canonical delivery. Canonical projection pairs must occur after a matching start while that assistant is active. Another assistant, finish, abort or error cannot authorize them. + +`createProjectionEvidencePorts` uses only the configured World and existing SDK hydration/per-run key resolution. Never log run input: it can contain short-lived credentials. Missing keys, decryption failures, expired/unresolved evidence, partial outputs, wrong identities, deadlines and cancellation fail closed. Run metadata `expiredAt` is preserved: past timestamps reject as expired; future timestamps remain unavailable pending configured-World qualification. Installed CLI and Web viewer interpretations differ; future dates are neither admitted nor described as proven expired. Exact SDK expired stubs are independently rejected. + +Bounds: five-second verification deadline, 10,000 canonical chunks/16 MiB, ten receipt pages of 100 records, one MiB per observation, sixteen MiB aggregate receipts and at most 256 fresh observations per producer. The producer's buffered per-iteration canonical assembly uses the same chunk/byte bound. Limits reject; nothing is truncated and labeled lossless. Metadata requests lack transport AbortSignal: caller waits are bounded and late promises observed, without claiming transport cancellation. Canonical readback uses finite raw snapshots with contiguous indexes and exact framing, never live-reader EOF/cancellation as proof. + +Evidence combines actual Gateway/SDK synthetic-wire tests through `runAgentStep`, installed SDK 6/7 canonical assembly, multi-iteration collection and required-failure control tests; compiled local-World collector/receipt/verifier and ingress rejection; and actual compiled workflow/fence/pricing-boundary tests. The standalone fixture supplies Node's real `require` for generated ESM clients with bundled CommonJS dependencies; no production module is mocked there. These are offline tests, not provider execution or hosted deployment acceptance. SDK event-boundary wire splits are not a full App transport reconnect/cursor qualification. Actual App transport, deployment admission, runtime retention and independent OAuth/Packs/Catalog/Recon review remain gates. + +The producer await boundary treats a thrown/missing result as required generation failure for first and later iterations, including fenced runs. It attempts explicit error-finish signalling and preserves the original rejection if signalling/cleanup also fails. A failed signalling write is not claimed delivered. + +Generation, required projected message writes and failure-stream writes require actual WDK `getStepMetadata().attempt === 1` before effects. Missing/invalid metadata or redelivery fails with FatalError for reconciliation, retaining the same step/run IDs. This also conservatively blocks a retry after a pre-effect failure because no qualified effect boundary was recorded. A persisted completed result is replayed by the runtime without reentering these bodies. The compiled synthetic probe distinguishes effect-done/completion-missing, completion-persisted/ACK-lost and pre-effect failure under installed core4.2.4, while direct step-entry tests cover the three actual effect functions. This does not establish hosted exactly-once effects or change model-provider SDK retry behavior. diff --git a/lib/chat/projection/__tests__/collectCanonicalProjection.test.ts b/lib/chat/projection/__tests__/collectCanonicalProjection.test.ts new file mode 100644 index 000000000..0a19c18d0 --- /dev/null +++ b/lib/chat/projection/__tests__/collectCanonicalProjection.test.ts @@ -0,0 +1,58 @@ +import { expect, it } from "vitest"; +import type { UIMessageChunk } from "ai"; +import { collectCanonicalProjection } from "../collectCanonicalProjection"; +async function* fresh(chunks: unknown[]) { + for (const chunk of chunks) yield chunk as UIMessageChunk; +} +it("indexes mixed SDK parts and tool upserts against actual final SDK assembly", async () => { + const chunks = [ + { type: "start-step" }, + { type: "text-start", id: "text" }, + { type: "text-delta", id: "text", delta: "before" }, + { type: "text-end", id: "text" }, + { type: "reasoning-start", id: "r" }, + { type: "reasoning-end", id: "r" }, + { type: "source-url", sourceId: "s", url: "https://example.invalid" }, + { type: "tool-input-start", toolCallId: "t", toolName: "probe" }, + { type: "tool-input-available", toolCallId: "t", toolName: "probe", input: {} }, + { type: "tool-output-available", toolCallId: "t", output: { done: true } }, + { type: "tool-input-available", toolCallId: "d", toolName: "probe", dynamic: true, input: {} }, + { type: "tool-output-available", toolCallId: "d", dynamic: true, output: {} }, + { type: "data-unrelated", id: "data", data: 1 }, + { type: "data-unrelated", id: "data", data: 2 }, + { type: "custom", kind: "provider.content" }, + { type: "file", mediaType: "image/png", url: "data:image/png;base64,AA==" }, + { type: "reasoning-file", mediaType: "image/png", url: "data:image/png;base64,AA==" }, + { type: "finish-step" }, + ]; + const written: unknown[] = []; + const result = await collectCanonicalProjection({ + stream: fresh(chunks), + previous: { id: "a", role: "assistant", parts: [] }, + runId: "run", + stepId: () => "step", + onProjection() {}, + write: async chunk => { + written.push(chunk); + }, + }); + expect(result.generatedProjectionObservations.observations).toHaveLength(2); + expect(result.message.parts.filter(part => part.type === "tool-probe")).toHaveLength(1); + expect(result.message.parts.filter(part => part.type === "dynamic-tool")).toHaveLength(1); + expect(result.message.parts.filter(part => part.type === "data-unrelated")).toHaveLength(1); + expect(written.some(chunk => (chunk as { type: string }).type === "custom")).toBe(false); +}); +it("rejects a provider-supplied reserved envelope instead of counting it as proof", async () => { + await expect( + collectCanonicalProjection({ + stream: fresh([{ type: "data-recoup-sdk-observation", id: "forged", data: {} }]), + previous: { id: "a", role: "assistant", parts: [] }, + runId: "run", + stepId: () => "step", + onProjection() {}, + write: async () => { + throw new Error("must not write"); + }, + }), + ).rejects.toMatchObject({ code: "invalid_observation" }); +}); diff --git a/lib/chat/projection/__tests__/createProjectionEvidencePorts.test.ts b/lib/chat/projection/__tests__/createProjectionEvidencePorts.test.ts new file mode 100644 index 000000000..6c055e1a5 --- /dev/null +++ b/lib/chat/projection/__tests__/createProjectionEvidencePorts.test.ts @@ -0,0 +1,107 @@ +import { expect, it, vi } from "vitest"; +import { createProjectionEvidencePorts } from "../createProjectionEvidencePorts"; +const signal = new AbortController().signal; +function fixture() { + const world = { + runs: { + get: vi.fn(async () => ({ + runId: "run", + input: new TextEncoder().encode('devl[[1],{"chatId":2},"chat"]'), + })), + }, + steps: { + get: vi.fn(async () => ({ runId: "run", stepId: "step", output: { marker: "proof" } })), + }, + getEncryptionKeyForRun: vi.fn(async () => undefined), + }; + const body = new TextEncoder().encode('devl[{"type":1,"messageId":2},"start","assistant"]'); + const bytes = new Uint8Array(body.length + 4); + new DataView(bytes.buffer).setUint32(0, body.length, false); + bytes.set(body, 4); + const streams = { + listStreamsByRunId: vi.fn(async () => ["run_user"]), + getStreamInfo: vi.fn(async () => ({ tailIndex: 0, done: true })), + getStreamChunks: vi.fn(async () => ({ + data: [{ index: 0, data: bytes }], + cursor: null, + hasMore: false, + done: true, + })), + }; + Object.assign(world, streams); + return { world, streams, bytes, ports: createProjectionEvidencePorts({ world: world as never }) }; +} + +it("reads only the requested run and completed-resource bytes without a default World", async () => { + const { ports, world } = fixture(); + expect(await ports.readRun("run", signal)).toMatchObject({ input: [{ chatId: "chat" }] }); + expect(world.runs.get).toHaveBeenCalledWith("run", { resolveData: "all" }); + expect(await ports.readStep("run", "step", signal)).toMatchObject({ + output: { marker: "proof" }, + }); +}); +it("does not fall back to encrypted bytes when the existing World key is unavailable", async () => { + const { ports, world } = fixture(); + world.runs.get.mockResolvedValue({ + runId: "run", + input: new TextEncoder().encode("encrnot-readable"), + } as never); + await expect(ports.readRun("run", signal)).rejects.toMatchObject({ code: "key_unavailable" }); +}); +it("distinguishes expired resolved input", async () => { + const { ports, world } = fixture(); + world.runs.get.mockResolvedValue({ + runId: "run", + input: new TextEncoder().encode('devl[[1],{"expiredAt":2},"2026-01-01"]'), + } as never); + await expect(ports.readRun("run", signal)).rejects.toMatchObject({ code: "evidence_expired" }); +}); +it("reads exact framed stored chunks without opening a live subscription", async () => { + const { ports, streams } = fixture(); + expect(await ports.readCanonical("run", signal)).toEqual([ + { type: "start", messageId: "assistant" }, + ]); + expect(streams.getStreamChunks).toHaveBeenCalledWith("run_user", "run", { + limit: 100, + cursor: undefined, + }); +}); +it("rejects missing stored chunks instead of treating a truncated snapshot as confirmed", async () => { + const { ports, streams } = fixture(); + streams.getStreamChunks.mockResolvedValue({ data: [], cursor: null, hasMore: false, done: true }); + await expect(ports.readCanonical("run", signal)).rejects.toMatchObject({ code: "proof_pending" }); +}); +it("rejects excessive tails before accumulating content", async () => { + const { ports, streams } = fixture(); + streams.getStreamInfo.mockResolvedValue({ tailIndex: 10000, done: false }); + await expect(ports.readCanonical("run", signal)).rejects.toMatchObject({ + code: "evidence_limit", + }); + expect(streams.getStreamChunks).not.toHaveBeenCalled(); +}); +it("rejects trailing partial frame bytes that the SDK decoder can ignore", async () => { + const { ports, streams, bytes } = fixture(); + const malformed = new Uint8Array(bytes.length + 1); + malformed.set(bytes); + streams.getStreamChunks.mockResolvedValue({ + data: [{ index: 0, data: malformed }], + cursor: null, + hasMore: false, + done: true, + }); + await expect(ports.readCanonical("run", signal)).rejects.toMatchObject({ + code: "invalid_evidence", + }); +}); +it("rejects missing or reordered absolute chunk indexes", async () => { + const { ports, streams, bytes } = fixture(); + streams.getStreamChunks.mockResolvedValue({ + data: [{ index: 1, data: bytes }], + cursor: null, + hasMore: false, + done: true, + }); + await expect(ports.readCanonical("run", signal)).rejects.toMatchObject({ + code: "canonical_mismatch", + }); +}); diff --git a/lib/chat/projection/__tests__/prepareProjectionHistory.test.ts b/lib/chat/projection/__tests__/prepareProjectionHistory.test.ts new file mode 100644 index 000000000..8fbf9b189 --- /dev/null +++ b/lib/chat/projection/__tests__/prepareProjectionHistory.test.ts @@ -0,0 +1,77 @@ +import { expect, it, vi } from "vitest"; +import type { UIMessage } from "ai"; +import { prepareProjectionHistory } from "../prepareProjectionHistory"; +import { prepareAuthorizedProjectionHistory } from "../prepareAuthorizedProjectionHistory"; +const observation = { + type: "data-recoup-sdk-observation", + id: "a:projection:0", + data: { fallback: { partIndex: 2 } }, +}; +const tool = { + type: "tool-answer", + toolCallId: "call", + state: "output-available", + output: "user edit", +}; +const message = { + id: "a", + role: "assistant", + metadata: { retained: true }, + parts: [ + tool, + observation, + { type: "text", text: "fallback", state: "done" }, + { type: "text", text: "unrelated" }, + ], +} as UIMessage; +it("restores only the verified span and preserves canonical and tool edits", async () => { + const original = { type: "custom", kind: "provider.content" } as const; + const verify = vi.fn(async () => original); + const input = [structuredClone(message)]; + const result = await prepareProjectionHistory(input, verify); + expect(result.canonical).toBe(input); + expect(result.canonical[0].parts).toEqual(message.parts); + expect(result.native[0].parts).toEqual([tool, original, message.parts[3]]); + expect(result.native[0].metadata).toEqual(message.metadata); + expect(verify).toHaveBeenCalledWith(input[0].parts[1], input[0]); +}); +it("never changes history or accepts fallback on verification failure", async () => { + const input = [structuredClone(message)]; + await expect( + prepareProjectionHistory(input, async () => { + throw new Error("refused"); + }), + ).rejects.toThrow("refused"); + expect(input).toEqual([message]); +}); +it.each(["user", "system"])("rejects reserved observations in %s messages", async role => { + const verify = vi.fn(); + await expect( + prepareProjectionHistory([{ ...message, role } as UIMessage], verify), + ).rejects.toMatchObject({ code: "producer_mismatch" }); + expect(verify).not.toHaveBeenCalled(); +}); +it("rejects unadmitted observations without opening a World", async () => { + await expect( + prepareAuthorizedProjectionHistory( + [message], + { accountId: "a", chatId: "c", sessionId: "s" }, + new AbortController().signal, + ), + ).rejects.toMatchObject({ code: "producer_mismatch" }); +}); +it("rejects a shifted pair before invoking evidence reads", async () => { + const verify = vi.fn(); + await expect( + prepareProjectionHistory([{ ...message, parts: message.parts.slice(1) }], verify), + ).rejects.toMatchObject({ code: "span_mismatch" }); + expect(verify).not.toHaveBeenCalled(); +}); +it.each(["custom", "reasoning-file", "tool-approval-request", "tool-approval-response"])( + "rejects unproven native %s parts from history", + async type => { + await expect( + prepareProjectionHistory([{ ...message, parts: [{ type } as never] }]), + ).rejects.toMatchObject({ code: "invalid_observation" }); + }, +); diff --git a/lib/chat/projection/__tests__/verifyProjectionObservation.test.ts b/lib/chat/projection/__tests__/verifyProjectionObservation.test.ts new file mode 100644 index 000000000..fb4557bdd --- /dev/null +++ b/lib/chat/projection/__tests__/verifyProjectionObservation.test.ts @@ -0,0 +1,410 @@ +import { describe, expect, it, vi } from "vitest"; +import { createProjectionEvidencePorts } from "../createProjectionEvidencePorts"; +import { recordProjectionProofStep } from "@/app/lib/workflows/projection/recordProjectionProofStep"; +import { verifyProjectionObservation } from "../verifyProjectionObservation"; + +const scope = { accountId: "account", chatId: "chat", sessionId: "session" }; +const producer = { + deploymentId: "deployment", + workflowName: "workflow//chat//run", + stepName: "step//chat//runAgentStep", + proofStepName: "step//chat//recordProjectionProofStep", +}; +const baseObservation = { + type: "data-recoup-sdk-observation", + id: "assistant:projection:0", + data: { + version: 1, + originRunId: "run", + originStepId: "step", + assistantMessageId: "assistant", + ordinal: 0, + original: { + type: "custom", + kind: "provider.kind", + providerMetadata: { provider: { opaque: ["retained", 1] } }, + }, + fallback: { + partIndex: 1, + text: "This view cannot display additional model content.", + }, + }, +}; +const baseEvents = [ + baseObservation, + { type: "text-start", id: "assistant:projection:0:fallback" }, + { + type: "text-delta", + id: "assistant:projection:0:fallback", + delta: baseObservation.data.fallback.text, + }, + { type: "text-end", id: "assistant:projection:0:fallback" }, +]; +function fixture() { + const observation = structuredClone(baseObservation); + const events = structuredClone(baseEvents); + const run = { + runId: "run", + ...producer, + input: [{ ...scope, modelId: "model", messages: [], agentContext: {} }], + }; + const step = { + runId: "run", + stepId: "step", + stepName: producer.stepName, + status: "completed", + output: { + generatedProjectionObservations: { + contract: "recoup-sdk-projection/v1", + observations: [{ observation, events, canonicalWrite: "requires-readback" }], + }, + }, + }; + const receipt = { + runId: "run", + stepId: "proof-step", + stepName: producer.proofStepName, + status: "completed", + output: { + contract: "recoup-sdk-projection-proof/v1", + producerStepId: "step", + generatedProjectionObservations: step.output.generatedProjectionObservations, + }, + }; + const ports = { + readRun: vi.fn(async () => run), + readStep: vi.fn(async () => step), + readReceipt: vi.fn(async () => receipt), + readCanonical: vi.fn(async () => [{ type: "start", messageId: "assistant" }, ...events]), + }; + const input = { + observation, + message: { + id: "assistant", + role: "assistant", + parts: [observation, { type: "text", text: observation.data.fallback.text, state: "done" }], + }, + scope, + producers: [producer], + ports, + signal: new AbortController().signal, + }; + return { run, step, receipt, ports, input }; +} +describe("journal-backed projection verification", () => { + it("requires exact fresh proof and canonical pair under server authority", async () => { + const { input } = fixture(); + expect(await verifyProjectionObservation(input)).toEqual(baseObservation.data.original); + }); + it.each(["accountId", "chatId", "sessionId"] as const)( + "rejects wrong recorded %s", + async field => { + const { input, run, ports } = fixture(); + run.input[0][field] = "other"; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "authority_mismatch", + }); + expect(ports.readStep).not.toHaveBeenCalled(); + }, + ); + it.each(["workflowName", "deploymentId"] as const)("rejects unapproved %s", async field => { + const { input, run } = fixture(); + run[field] = "other"; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "producer_mismatch", + }); + }); + it("fails closed with no configured trusted producer", async () => { + const { input, ports } = fixture(); + input.producers = []; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "producer_mismatch", + }); + expect(ports.readRun).not.toHaveBeenCalled(); + }); + it("never accepts an aggregate response seed as generated proof", async () => { + const { input, step } = fixture(); + Object.assign(step.output, { responseMessage: input.message }); + delete (step.output as Record).generatedProjectionObservations; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "proof_missing", + }); + }); + it.each(["runId", "stepId", "stepName"] as const)( + "rejects wrong recorded step %s", + async field => { + const { input, step } = fixture(); + step[field] = "other"; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "producer_mismatch", + }); + }, + ); + it("rejects an incomplete step even with a matching aggregate", async () => { + const { input, step } = fixture(); + step.status = "running"; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "proof_pending", + }); + }); + it("requires actual stored stream equality even when a completed step result matches", async () => { + const { input, ports } = fixture(); + ports.readCanonical.mockResolvedValue([{ type: "start", messageId: "assistant" }]); + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "canonical_mismatch", + }); + }); + it("does not promote partial fallback text", async () => { + const { input } = fixture(); + input.message.parts[1] = { type: "text", text: "Additional", state: "done" }; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "span_mismatch", + }); + }); + it("does not restore from a different assistant", async () => { + const { input } = fixture(); + input.message.id = "other"; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "span_mismatch", + }); + }); + it("rejects expired input without trusting any row", async () => { + const { input, run } = fixture(); + (run as Record).input = [{ expiredAt: "2026-01-01" }]; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "evidence_expired", + }); + }); + it("preserves distinct unavailable evidence failures", async () => { + const { input, ports } = fixture(); + ports.readRun.mockRejectedValue(new Error("private transport details")); + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "evidence_unavailable", + message: "Projection history evidence unavailable", + }); + }); + it("rejects invalid original semantics such as approvals", async () => { + const { input } = fixture(); + (input.observation.data as Record).original = { + type: "tool-approval-response", + approved: true, + }; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "invalid_observation", + }); + }); + it("bounds an uncooperative metadata read and observes cancellation", async () => { + const { input, ports } = fixture(); + const controller = new AbortController(); + input.signal = controller.signal; + ports.readRun.mockImplementation(() => new Promise(() => {})); + const pending = verifyProjectionObservation(input); + controller.abort(); + await expect(pending).rejects.toMatchObject({ code: "cancelled" }); + }); +}); +it("rejects duplicate completed proof entries instead of selecting one", async () => { + const { input, step } = fixture(); + step.output.generatedProjectionObservations.observations.push( + structuredClone(step.output.generatedProjectionObservations.observations[0]), + ); + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "invalid_evidence", + }); +}); +it("requires an approved identity even when caller namespace/version looks valid", async () => { + const { input, run } = fixture(); + (run as Record).deploymentId = undefined; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "producer_mismatch", + }); +}); +it("rejects a second copy in the stream as ambiguous rather than reusing an index", async () => { + const { input, ports } = fixture(); + ports.readCanonical.mockResolvedValue([ + { type: "start", messageId: "assistant" }, + ...baseEvents, + ...baseEvents, + ]); + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "canonical_mismatch", + }); +}); +it("does not accept arbitrarily nested input authority", async () => { + const { input, run } = fixture(); + (run as Record).input = [{ unrelated: { ...scope } }]; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "invalid_evidence", + }); +}); +it("rejects leftover encrypted or unresolved input bytes", async () => { + const { input, run } = fixture(); + (run as Record).input = new Uint8Array([1, 2]); + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "invalid_evidence", + }); +}); +it("requires a separate completed receipt with present output", async () => { + const { input, receipt } = fixture(); + delete (receipt as Record).output; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ code: "proof_missing" }); +}); +it("does not substitute the producer step for the distinct proof step", async () => { + const { input, receipt } = fixture(); + receipt.stepId = "step"; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "producer_mismatch", + }); +}); +it("checks the receipt producer linkage, not just identical observations", async () => { + const { input, receipt } = fixture(); + receipt.output.producerStepId = "other-step"; + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "producer_mismatch", + }); +}); +it("verifies a valid large observation whose duplicated proof exceeds one MiB", async () => { + const { input, step, ports } = fixture(); + input.observation.data.original.providerMetadata.provider.opaque = ["x".repeat(600_000), 1]; + step.output.generatedProjectionObservations.observations[0].events[0] = input.observation; + ports.readCanonical.mockResolvedValue([ + { type: "start", messageId: "assistant" }, + ...step.output.generatedProjectionObservations.observations[0].events, + ]); + await expect(verifyProjectionObservation(input)).resolves.toEqual( + input.observation.data.original, + ); +}); +it("sanitizes an aggregate proof exceeding its separate sixteen MiB budget", async () => { + const { input, step } = fixture(); + const item = step.output.generatedProjectionObservations.observations[0]; + step.output.generatedProjectionObservations.observations = Array.from( + { length: 32 }, + (_, index) => { + const copy = structuredClone(item); + copy.observation.data.ordinal = index; + copy.observation.data.original.providerMetadata.provider.opaque = ["x".repeat(600_000), 1]; + return copy; + }, + ); + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "evidence_limit", + message: "Projection history evidence unavailable", + }); +}); +it("uses the aggregate budget for multiple individually bounded observations", async () => { + const { input, step, receipt, ports } = fixture(); + const first = step.output.generatedProjectionObservations.observations[0]; + first.observation.data.original.providerMetadata.provider.opaque = ["x".repeat(300_000), 1]; + first.events[0] = first.observation; + const second = structuredClone(first); + second.observation.id = "assistant:projection:1"; + second.observation.data.ordinal = 1; + second.observation.data.fallback.partIndex = 3; + second.events = [ + second.observation, + { type: "text-start", id: "assistant:projection:1:fallback" }, + { + type: "text-delta", + id: "assistant:projection:1:fallback", + delta: second.observation.data.fallback.text, + }, + { type: "text-end", id: "assistant:projection:1:fallback" }, + ]; + step.output.generatedProjectionObservations.observations.push(second); + receipt.output.generatedProjectionObservations = structuredClone( + step.output.generatedProjectionObservations, + ); + ports.readCanonical.mockResolvedValue([ + { type: "start", messageId: "assistant" }, + ...first.events, + ...second.events, + ]); + await expect(verifyProjectionObservation(input)).resolves.toEqual( + input.observation.data.original, + ); +}); + +it.each( + [ + [...baseEvents, { type: "start", messageId: "assistant" }], + [ + { type: "start", messageId: "assistant" }, + { type: "start", messageId: "other" }, + ...baseEvents, + ], + [{ type: "start", messageId: "assistant" }, { type: "finish" }, ...baseEvents], + ].map(chunks => ({ chunks })), +)("rejects projection outside the active canonical assistant", async ({ chunks }) => { + const { input, ports } = fixture(); + ports.readCanonical.mockResolvedValue(chunks as never); + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ + code: "canonical_mismatch", + }); +}); +it.each([ + [new Date("2000-01-01"), "evidence_expired"], + [new Date("2999-01-01"), "evidence_unavailable"], + [undefined, undefined], +])( + "preserves and refuses ambiguous or expired World metadata through the real adapter", + async (expiredAt, code) => { + const { input, run, ports } = fixture(); + const world = { + runs: { + get: vi.fn(async () => ({ + ...run, + expiredAt, + input: new TextEncoder().encode( + 'devl[[1],{"accountId":2,"chatId":3,"sessionId":4,"modelId":5,"messages":6,"agentContext":7},"account","chat","session","model",[],{}]', + ), + })), + }, + }; + const adapter = createProjectionEvidencePorts({ world: world as never }); + input.ports.readRun = vi.fn(adapter.readRun); + if (code) { + await expect(verifyProjectionObservation(input)).rejects.toMatchObject({ code }); + expect(ports.readStep).not.toHaveBeenCalled(); + } else { + await expect(verifyProjectionObservation(input)).resolves.toEqual( + input.observation.data.original, + ); + } + }, +); +it("records and verifies the same 600 KB observation budget", async () => { + const { input, step, receipt, ports } = fixture(); + input.observation.data.original.providerMetadata.provider.opaque = ["x".repeat(600_000), 1]; + step.output.generatedProjectionObservations.observations[0].events[0] = input.observation; + receipt.output = (await recordProjectionProofStep( + "step", + step.output.generatedProjectionObservations, + )) as typeof receipt.output; + ports.readCanonical.mockResolvedValue([ + { type: "start", messageId: "assistant" }, + ...step.output.generatedProjectionObservations.observations[0].events, + ]); + await expect(verifyProjectionObservation(input)).resolves.toEqual( + input.observation.data.original, + ); +}); +it("rejects an oversized individual observation at receipt recording with a typed error", async () => { + const { input, step } = fixture(); + input.observation.data.original.providerMetadata.provider.opaque = ["x".repeat(1_048_576), 1]; + await expect( + recordProjectionProofStep("step", step.output.generatedProjectionObservations), + ).rejects.toMatchObject({ + code: "evidence_limit", + message: "Projection history evidence unavailable", + }); +}); +it("rejects oversized aggregate receipts with a typed limit error", async () => { + const { step } = fixture(); + const item = step.output.generatedProjectionObservations.observations[0]; + item.observation.data.original.providerMetadata.provider.opaque = ["x".repeat(600_000), 1]; + step.output.generatedProjectionObservations.observations = Array.from({ length: 32 }, () => item); + await expect( + recordProjectionProofStep("step", step.output.generatedProjectionObservations), + ).rejects.toMatchObject({ code: "evidence_limit" }); +}); diff --git a/lib/chat/projection/__tests__/writeProjectionObservation.test.ts b/lib/chat/projection/__tests__/writeProjectionObservation.test.ts new file mode 100644 index 000000000..b2100298a --- /dev/null +++ b/lib/chat/projection/__tests__/writeProjectionObservation.test.ts @@ -0,0 +1,65 @@ +import { expect, it, vi } from "vitest"; +import { writeProjectionObservation } from "../writeProjectionObservation"; +const input = { + originRunId: "run", + originStepId: "step", + assistantMessageId: "assistant", + ordinal: 2, + partIndex: 4, + original: { + type: "reasoning-file", + mediaType: "image/png", + url: "data:image/png;base64,opaque", + providerMetadata: { provider: { hidden: "exact" } }, + }, +}; +it("retains original fields in a candidate that still requires independent journal and stream readback", async () => { + const chunks: unknown[] = []; + const write = vi.fn(async chunk => { + chunks.push(chunk); + }); + const proof = await writeProjectionObservation(input, write); + expect(proof.observation.data.original).toEqual(input.original); + expect(proof.events).toEqual(chunks); + expect(chunks).toHaveLength(4); + expect(proof.canonicalWrite).toBe("requires-readback"); + expect(proof.observation.data.fallback.text).toBe( + "This view cannot display a reasoning attachment.", + ); +}); +it.each([0, 1, 2, 3])( + "does not mint a complete proof when canonical write %i fails", + async failAt => { + let index = 0; + const write = vi.fn(async () => { + if (index++ === failAt) throw new Error("unknown ACK"); + }); + await expect(writeProjectionObservation(input, write)).rejects.toThrow("unknown ACK"); + expect(write).toHaveBeenCalledTimes(failAt + 1); + }, +); +it("refuses approval semantics instead of minting a projection grant", async () => { + const write = vi.fn(); + await expect( + writeProjectionObservation( + { ...input, original: { type: "tool-approval-response", approved: true } }, + write, + ), + ).rejects.toMatchObject({ code: "invalid_observation" }); + expect(write).not.toHaveBeenCalled(); +}); +it("rejects envelope overhead beyond the observation budget before the first write", async () => { + const original = { + type: "custom", + kind: "provider.kind", + providerMetadata: { provider: { large: "" } }, + }; + original.providerMetadata.provider.large = "x".repeat( + 1_048_576 - Buffer.byteLength(JSON.stringify(original)) - 32, + ); + const write = vi.fn(); + await expect(writeProjectionObservation({ ...input, original }, write)).rejects.toMatchObject({ + code: "invalid_observation", + }); + expect(write).not.toHaveBeenCalled(); +}); diff --git a/lib/chat/projection/collectCanonicalProjection.ts b/lib/chat/projection/collectCanonicalProjection.ts new file mode 100644 index 000000000..1b3807591 --- /dev/null +++ b/lib/chat/projection/collectCanonicalProjection.ts @@ -0,0 +1,149 @@ +import type { UIMessage, UIMessageChunk } from "ai"; +import { encodeProjectionEvidence } from "./encodeProjectionEvidence"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +import { writeProjectionObservation } from "./writeProjectionObservation"; +import type { ProjectionProof } from "./projectionSchemas"; +/** Consume only fresh SDK emissions. Seeded canonical parts are never added to the proof collection. */ +export async function collectCanonicalProjection(input: { + stream: AsyncIterable; + previous: UIMessage; + runId: string; + stepId: () => string; + onProjection: () => void; + isCancellation?: (error: unknown) => Promise; + write: (chunk: UIMessageChunk) => Promise; +}) { + const chunks: UIMessageChunk[] = []; + const proof: ProjectionProof = { contract: "recoup-sdk-projection/v1", observations: [] }; + let partCount = input.previous.parts.length; + let ordinal = 0; + const tools = new Set(); + const dataIds = new Set(); + for (const part of input.previous.parts) { + if ("toolCallId" in part) tools.add(`${part.type === "dynamic-tool"}:${part.toolCallId}`); + if (part.type.startsWith("data-") && "id" in part && part.id != null) + dataIds.add(`${part.type}:${part.id}`); + if (part.type === "data-recoup-sdk-observation") { + const previousOrdinal = (part.data as { ordinal: number }).ordinal; + if (!Number.isSafeInteger(previousOrdinal)) + throw new ProjectionEvidenceError("invalid_observation"); + ordinal = Math.max(ordinal, previousOrdinal + 1); + } + } + let bytes = 2; + const append = async (chunk: UIMessageChunk) => { + bytes += Buffer.byteLength(encodeProjectionEvidence(chunk, 16_777_216), "utf8") + 1; + if (bytes > 16_777_216 || chunks.length >= 10000) + throw new ProjectionEvidenceError("evidence_limit"); + chunks.push(chunk); + try { + await input.write(chunk); + } catch { + // Even an early unknown append outcome must not replay the provider step. + throw new ProjectionEvidenceError("evidence_unavailable"); + } + }; + let cancelled = false; + try { + for await (const chunk of input.stream) { + if (chunk.type === "custom" || chunk.type === "reasoning-file") { + input.onProjection(); + if (proof.observations.length >= 256) throw new ProjectionEvidenceError("evidence_limit"); + const candidate = await writeProjectionObservation( + { + originRunId: input.runId, + originStepId: input.stepId(), + assistantMessageId: input.previous.id, + ordinal: ordinal++, + partIndex: partCount + 1, + original: chunk, + }, + event => append(event as UIMessageChunk), + ); + proof.observations.push(candidate); + encodeProjectionEvidence(proof, 16_777_216); + partCount += 2; + continue; + } + if ( + [ + "data-recoup-sdk-observation", + "tool-approval-request", + "tool-approval-response", + "error", + ].includes(chunk.type) + ) + throw new ProjectionEvidenceError("invalid_observation"); + // These are the installed SDK's append/upsert rules, only for span indexing. + // Final assembly below uses the actual SDK and independently checks every span. + if ( + [ + "text-start", + "reasoning-start", + "file", + "source-url", + "source-document", + "start-step", + ].includes(chunk.type) + ) + partCount++; + else if ( + ["tool-input-start", "tool-input-available", "tool-input-error"].includes(chunk.type) + ) { + const tool = chunk as { toolCallId: string; dynamic?: boolean }; + const key = `${!!tool.dynamic}:${tool.toolCallId}`; + if (!tools.has(key)) { + tools.add(key); + partCount++; + } + } else if (chunk.type.startsWith("data-")) { + const data = chunk as { id?: string; transient?: boolean }; + const key = `${chunk.type}:${data.id}`; + if (!data.transient && (data.id == null || !dataIds.has(key))) { + partCount++; + if (data.id != null) dataIds.add(key); + } + } + await append(chunk); + } + } catch (error) { + if (error instanceof ProjectionEvidenceError || !(await input.isCancellation?.(error))) + throw error; + // Assemble only the canonical prefix already accepted by the writer. The workflow + // still requires proof/readback and message ACK before the existing Stop charge. + cancelled = true; + } + const { readUIMessageStream } = await import("ai"); + let message = structuredClone(input.previous); + try { + for await (const current of readUIMessageStream({ + message, + terminateOnError: true, + stream: new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk); + controller.close(); + }, + }), + })) + message = current; + } catch { + throw new ProjectionEvidenceError("canonical_mismatch"); + } + for (const item of proof.observations) { + const { observation } = item; + const index = observation.data.fallback.partIndex; + if ( + encodeProjectionEvidence(message.parts[index - 1]) !== + encodeProjectionEvidence(observation) || + encodeProjectionEvidence(message.parts[index]) !== + encodeProjectionEvidence({ + type: "text", + text: observation.data.fallback.text, + state: "done", + }) + ) + throw new ProjectionEvidenceError("canonical_mismatch"); + } + return { message, generatedProjectionObservations: proof, cancelled }; +} diff --git a/lib/chat/projection/createProjectionEvidencePorts.ts b/lib/chat/projection/createProjectionEvidencePorts.ts new file mode 100644 index 000000000..da3350cd8 --- /dev/null +++ b/lib/chat/projection/createProjectionEvidencePorts.ts @@ -0,0 +1,99 @@ +import type { getWorld } from "workflow/runtime"; +import { WorkflowRunNotFoundError, RunExpiredError } from "workflow/errors"; +import { hydrateProjectionEvidence } from "./hydrateProjectionEvidence"; +import { readCanonicalProjectionSnapshot } from "./readCanonicalProjectionSnapshot"; +import { readProjectionEvidence } from "./readProjectionEvidence"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +import type { ProjectionEvidencePorts } from "./ProjectionEvidencePorts"; +/** Explicit server dependency injection; importing this module never opens a World or reads keys. */ +export function createProjectionEvidencePorts({ + world, +}: { + world: Pick< + ReturnType, + | "runs" + | "steps" + | "getEncryptionKeyForRun" + | "getStreamInfo" + | "getStreamChunks" + | "listStreamsByRunId" + >; +}): ProjectionEvidencePorts { + async function resource(read: () => Promise, signal: AbortSignal): Promise { + return readProjectionEvidence(async () => { + try { + return await read(); + } catch (error) { + if (WorkflowRunNotFoundError.is(error)) + throw new ProjectionEvidenceError("evidence_missing"); + if (RunExpiredError.is(error)) throw new ProjectionEvidenceError("evidence_expired"); + throw error; + } + }, signal); + } + return { + async readRun(runId, signal) { + const run = await resource(() => world.runs.get(runId, { resolveData: "all" }), signal); + return { + runId: run.runId, + deploymentId: run.deploymentId, + workflowName: run.workflowName, + expiredAt: run.expiredAt, + input: await hydrateProjectionEvidence(run.input, runId, world, signal), + }; + }, + async readStep(runId, stepId, signal) { + const step = await resource( + () => world.steps.get(runId, stepId, { resolveData: "all" }), + signal, + ); + return { + runId: step.runId, + stepId: step.stepId, + stepName: step.stepName, + status: step.status, + output: await hydrateProjectionEvidence(step.output, runId, world, signal), + }; + }, + async readReceipt(runId, producerStepId, proofStepName, signal) { + let cursor: string | undefined; + let found: unknown; + for (let pageCount = 0; pageCount < 10; pageCount++) { + const page = await resource( + () => + world.steps.list({ runId, resolveData: "none", pagination: { limit: 100, cursor } }), + signal, + ); + for (const candidate of page.data) { + if (candidate.stepName !== proofStepName || candidate.status !== "completed") continue; + const step = await resource( + () => world.steps.get(runId, candidate.stepId, { resolveData: "all" }), + signal, + ); + const output = await hydrateProjectionEvidence(step.output, runId, world, signal); + if ( + typeof output !== "object" || + output === null || + !("producerStepId" in output) || + output.producerStepId !== producerStepId + ) + continue; + if (found) throw new ProjectionEvidenceError("invalid_evidence"); + found = { + runId: step.runId, + stepId: step.stepId, + stepName: step.stepName, + status: step.status, + output, + }; + } + if (!page.hasMore) return found; + if (!page.cursor || page.cursor === cursor) + throw new ProjectionEvidenceError("invalid_evidence"); + cursor = page.cursor; + } + throw new ProjectionEvidenceError("evidence_limit"); + }, + readCanonical: (runId, signal) => readCanonicalProjectionSnapshot(world, runId, signal), + }; +} diff --git a/lib/chat/projection/encodeProjectionEvidence.ts b/lib/chat/projection/encodeProjectionEvidence.ts new file mode 100644 index 000000000..471ab8fef --- /dev/null +++ b/lib/chat/projection/encodeProjectionEvidence.ts @@ -0,0 +1,13 @@ +import { encodeStrictJson } from "@/lib/chat/fence/encodeStrictJson"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +export function encodeProjectionEvidence(value: unknown, maxBytes = 1_048_576) { + try { + return encodeStrictJson(value, { omitUndefinedObjectProperties: true, maxBytes }); + } catch (error) { + throw new ProjectionEvidenceError( + error instanceof Error && error.message === "JSON exceeds byte budget" + ? "evidence_limit" + : "invalid_evidence", + ); + } +} diff --git a/lib/chat/projection/hydrateProjectionEvidence.ts b/lib/chat/projection/hydrateProjectionEvidence.ts new file mode 100644 index 000000000..610d7d38d --- /dev/null +++ b/lib/chat/projection/hydrateProjectionEvidence.ts @@ -0,0 +1,48 @@ +import { + hydrateDataWithKey, + isEncryptedData, + isExpiredStub, +} from "@workflow/core/serialization-format"; +import { importKey } from "@workflow/core/encryption"; +import { observabilityRevivers } from "workflow/observability"; +import type { getWorld } from "workflow/runtime"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +import { readProjectionEvidence } from "./readProjectionEvidence"; +type World = Pick, "runs" | "getEncryptionKeyForRun">; +function readResolvedRun(world: World, runId: string) { + return world.runs.get(runId, { resolveData: "all" }); +} +/** Existing configured-World decryption only; never manufacture or accept a caller key. */ +export async function hydrateProjectionEvidence( + value: unknown, + runId: string, + world: World, + signal: AbortSignal, + resolvedRun?: Awaited>, +) { + const encrypted = isEncryptedData(value); + let key; + if (encrypted) { + const run = + resolvedRun ?? (await readProjectionEvidence(() => readResolvedRun(world, runId), signal)); + const rawKey = await readProjectionEvidence( + async () => world.getEncryptionKeyForRun?.(run), + signal, + ); + if (!rawKey) throw new ProjectionEvidenceError("key_unavailable"); + try { + key = await importKey(rawKey); + } catch { + throw new ProjectionEvidenceError("decryption_failed"); + } + } + let hydrated; + try { + hydrated = await hydrateDataWithKey(value, observabilityRevivers, key); + } catch { + throw new ProjectionEvidenceError(encrypted ? "decryption_failed" : "invalid_evidence"); + } + if (isExpiredStub(hydrated)) throw new ProjectionEvidenceError("evidence_expired"); + if (hydrated instanceof Uint8Array) throw new ProjectionEvidenceError("invalid_evidence"); + return hydrated; +} diff --git a/lib/chat/projection/parseProjectionRunAuthority.ts b/lib/chat/projection/parseProjectionRunAuthority.ts new file mode 100644 index 000000000..78a93a68f --- /dev/null +++ b/lib/chat/projection/parseProjectionRunAuthority.ts @@ -0,0 +1,49 @@ +import { z } from "zod"; +import { internalWorkflowFenceSchema } from "@/app/lib/workflows/fence/TrustedFencedWorkflowInput"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +import { streamProtocolSchema } from "../continuation/streamProtocol"; +const id = z.string().min(1); +const inputSchema = z + .object({ + streamProtocol: streamProtocolSchema.optional(), + accountId: id, + chatId: id, + sessionId: id, + messages: z.array(z.unknown()), + modelId: id, + agentContext: z.record(z.string(), z.unknown()), + devCatalogSurface: z.unknown().optional(), + artistId: id.optional(), + reasoningEffort: z.enum(["low", "medium", "high"]).optional(), + interactive: z.boolean().optional(), + sessionTitle: z.string().optional(), + repoOwner: z.string().optional(), + repoName: z.string().optional(), + }) + .strict(); +const argsSchema = z.tuple([ + z.union([ + inputSchema, + z + .object({ + kind: z.literal("internal-fenced/v1"), + input: inputSchema, + fence: internalWorkflowFenceSchema, + }) + .strict(), + ]), +]); +/** Parse only the actual invocation shapes; a matching nested object is never authority. */ +export function parseProjectionRunAuthority(input: unknown) { + const result = argsSchema.safeParse(input); + if (!result.success) throw new ProjectionEvidenceError("invalid_evidence"); + const invocation = result.data[0]; + if (!("kind" in invocation)) return invocation; + const { authority } = invocation.fence; + if ( + authority.chatId !== invocation.input.chatId || + authority.effectiveAccount !== invocation.input.accountId + ) + throw new ProjectionEvidenceError("authority_mismatch"); + return invocation.input; +} diff --git a/lib/chat/projection/prepareAuthorizedProjectionHistory.ts b/lib/chat/projection/prepareAuthorizedProjectionHistory.ts new file mode 100644 index 000000000..5f8023e9a --- /dev/null +++ b/lib/chat/projection/prepareAuthorizedProjectionHistory.ts @@ -0,0 +1,29 @@ +import type { UIMessage } from "ai"; +import { prepareProjectionHistory } from "./prepareProjectionHistory"; +import { projectionProducers } from "./projectionProducers"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +import type { ProjectionAuthority } from "./ProjectionEvidencePorts"; +/** Caller has already authenticated current chat/session ownership; locators are never authority. */ +export async function prepareAuthorizedProjectionHistory( + messages: UIMessage[], + scope: ProjectionAuthority, + signal: AbortSignal, +) { + return prepareProjectionHistory(messages, async (observation, message) => { + if (!projectionProducers.length) throw new ProjectionEvidenceError("producer_mismatch"); + const [{ getWorld }, { createProjectionEvidencePorts }, { verifyProjectionObservation }] = + await Promise.all([ + import("workflow/runtime"), + import("./createProjectionEvidencePorts"), + import("./verifyProjectionObservation"), + ]); + return verifyProjectionObservation({ + observation, + message, + scope, + signal, + producers: projectionProducers, + ports: createProjectionEvidencePorts({ world: getWorld() }), + }); + }); +} diff --git a/lib/chat/projection/prepareProjectionHistory.ts b/lib/chat/projection/prepareProjectionHistory.ts new file mode 100644 index 000000000..1d542ba80 --- /dev/null +++ b/lib/chat/projection/prepareProjectionHistory.ts @@ -0,0 +1,47 @@ +import { assertMarkerFreeHistory } from "../continuation/assertMarkerFreeHistory"; +import type { UIMessage } from "ai"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +import type { ProjectionOriginal } from "./projectionSchemas"; +/** Preserve canonical history and tool edits; restore only independently verified adjacent spans. */ +export async function prepareProjectionHistory( + messages: UIMessage[], + verify?: (observation: unknown, message: UIMessage) => Promise, +): Promise<{ canonical: UIMessage[]; native: UIMessage[] }> { + assertMarkerFreeHistory(messages); + const native: UIMessage[] = []; + for (const message of messages) { + const parts = []; + let changed = false; + const seen = new Set(); + const content = (message as unknown as { content?: unknown }).content; + const inputParts = message.parts ?? (Array.isArray(content) ? content : []); + for (let index = 0; index < inputParts.length; index++) { + const part = inputParts[index]; + if ( + ["custom", "reasoning-file", "tool-approval-request", "tool-approval-response"].includes( + part.type, + ) + ) + throw new ProjectionEvidenceError("invalid_observation"); + if (part.type !== "data-recoup-sdk-observation") { + parts.push(part); + continue; + } + if (message.role !== "assistant" || !verify) + throw new ProjectionEvidenceError("producer_mismatch"); + const observation = part as { id?: string; data?: { fallback?: { partIndex?: number } } }; + if ( + !observation.id || + seen.has(observation.id) || + observation.data?.fallback?.partIndex !== index + 1 + ) + throw new ProjectionEvidenceError("span_mismatch"); + seen.add(observation.id); + parts.push(await verify(part, message)); + index++; // Only the verified adjacent fallback is removed from native history. + changed = true; + } + native.push(changed ? ({ ...message, parts } as UIMessage) : message); + } + return { canonical: messages, native }; +} diff --git a/lib/chat/projection/projectionEvents.ts b/lib/chat/projection/projectionEvents.ts new file mode 100644 index 000000000..680766a1a --- /dev/null +++ b/lib/chat/projection/projectionEvents.ts @@ -0,0 +1,13 @@ +import type { ProjectionObservation, ProjectionProof } from "./projectionSchemas"; +/** Fixed legacy-compatible expansion; identities never come from random values. */ +export function projectionEvents( + observation: ProjectionObservation, +): ProjectionProof["observations"][number]["events"] { + const id = `${observation.id}:fallback`; + return [ + observation, + { type: "text-start", id }, + { type: "text-delta", id, delta: observation.data.fallback.text }, + { type: "text-end", id }, + ]; +} diff --git a/lib/chat/projection/projectionProducers.ts b/lib/chat/projection/projectionProducers.ts new file mode 100644 index 000000000..5136d483b --- /dev/null +++ b/lib/chat/projection/projectionProducers.ts @@ -0,0 +1,3 @@ +import type { ProjectionProducer } from "./ProjectionEvidencePorts"; +/** Release-reviewed server identities only. No deployment is admitted by this source change. */ +export const projectionProducers: readonly ProjectionProducer[] = []; diff --git a/lib/chat/projection/projectionSchemas.ts b/lib/chat/projection/projectionSchemas.ts new file mode 100644 index 000000000..20e255e82 --- /dev/null +++ b/lib/chat/projection/projectionSchemas.ts @@ -0,0 +1,64 @@ +import { z } from "zod"; +const id = z.string().min(1).max(512); +const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER); +const metadata = z.record(z.string(), z.record(z.string(), z.json())).optional(); +export const projectionOriginalSchema = z.discriminatedUnion("type", [ + z + .object({ + type: z.literal("custom"), + kind: z.string().regex(/^.+\..+$/), + providerMetadata: metadata, + }) + .strict(), + z + .object({ + type: z.literal("reasoning-file"), + mediaType: z.string(), + url: z.string(), + providerMetadata: metadata, + }) + .strict(), +]); +export const projectionObservationSchema = z + .object({ + type: z.literal("data-recoup-sdk-observation"), + id, + data: z + .object({ + version: z.literal(1), + originRunId: id, + originStepId: id, + assistantMessageId: id, + ordinal: integer, + original: projectionOriginalSchema, + fallback: z.object({ partIndex: integer.min(1), text: z.string() }).strict(), + }) + .strict(), + }) + .strict(); +export const projectionProofSchema = z + .object({ + contract: z.literal("recoup-sdk-projection/v1"), + observations: z + .array( + z + .object({ + observation: projectionObservationSchema, + events: z.array(z.record(z.string(), z.json())).length(4), + canonicalWrite: z.literal("requires-readback"), + }) + .strict(), + ) + .max(256), + }) + .strict(); +export type ProjectionObservation = z.infer; +export type ProjectionOriginal = z.infer; +export type ProjectionProof = z.infer; +export const projectionReceiptSchema = z + .object({ + contract: z.literal("recoup-sdk-projection-proof/v1"), + producerStepId: id, + generatedProjectionObservations: projectionProofSchema, + }) + .strict(); diff --git a/lib/chat/projection/readCanonicalProjectionSnapshot.ts b/lib/chat/projection/readCanonicalProjectionSnapshot.ts new file mode 100644 index 000000000..e1bd758ba --- /dev/null +++ b/lib/chat/projection/readCanonicalProjectionSnapshot.ts @@ -0,0 +1,57 @@ +import type { getWorld } from "workflow/runtime"; +import { hydrateProjectionEvidence } from "./hydrateProjectionEvidence"; +import { readProjectionEvidence } from "./readProjectionEvidence"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +type World = Pick< + ReturnType, + "runs" | "getEncryptionKeyForRun" | "getStreamInfo" | "getStreamChunks" | "listStreamsByRunId" +>; +/** Validate raw stored frames, not an EOF from the SDK's tolerant stream decoder. */ +export async function readCanonicalProjectionSnapshot( + world: World, + runId: string, + signal: AbortSignal, +): Promise { + signal = AbortSignal.any([signal, AbortSignal.timeout(5000)]); + const read = (operation: () => Promise) => readProjectionEvidence(operation, signal); + // Installed core4.2.4 getWorkflowRunStreamId default-name contract. Confirm + // membership in this run; the compiled installed-SDK fixture guards drift. + const name = `${runId.replace("wrun_", "strm_")}_user`; + const names = await read(() => world.listStreamsByRunId(runId)); + if (!names.includes(name)) throw new ProjectionEvidenceError("evidence_missing"); + const info = await read(() => world.getStreamInfo(name, runId)); + if (!Number.isSafeInteger(info.tailIndex) || info.tailIndex < -1 || info.tailIndex >= 10000) + throw new ProjectionEvidenceError("evidence_limit"); + const chunks: unknown[] = []; + let cursor: string | undefined; + let remaining = 16_777_216; + for (let pageCount = 0; chunks.length <= info.tailIndex && pageCount < 100; pageCount++) { + const page = await read(() => world.getStreamChunks(name, runId, { limit: 100, cursor })); + for (const chunk of page.data) { + if (chunks.length > info.tailIndex) break; + if (chunk.index !== chunks.length) throw new ProjectionEvidenceError("canonical_mismatch"); + const bytes = chunk.data; + if (!(bytes instanceof Uint8Array) || bytes.length < 8) + throw new ProjectionEvidenceError("invalid_evidence"); + remaining -= bytes.length; + if (remaining < 0) throw new ProjectionEvidenceError("evidence_limit"); + const size = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32( + 0, + false, + ); + const prefix = new TextDecoder().decode(bytes.subarray(4, 8)); + // One current-SDK object frame per indexed stored chunk. Do not accept + // trailing bytes, partial frames, legacy unframed data or silent decoder loss. + if (size !== bytes.length - 4 || (prefix !== "devl" && prefix !== "encr")) + throw new ProjectionEvidenceError("invalid_evidence"); + chunks.push(await hydrateProjectionEvidence(bytes.subarray(4), runId, world, signal)); + } + if (chunks.length > info.tailIndex) return chunks; + if (!page.hasMore) throw new ProjectionEvidenceError("proof_pending"); + if (!page.cursor || page.cursor === cursor) + throw new ProjectionEvidenceError("invalid_evidence"); + cursor = page.cursor; + } + if (chunks.length <= info.tailIndex) throw new ProjectionEvidenceError("evidence_limit"); + return chunks; +} diff --git a/lib/chat/projection/readProjectionEvidence.ts b/lib/chat/projection/readProjectionEvidence.ts new file mode 100644 index 000000000..65fd46231 --- /dev/null +++ b/lib/chat/projection/readProjectionEvidence.ts @@ -0,0 +1,21 @@ +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +/** Bound the caller even when an SDK metadata promise ignores cancellation; observe late rejection. */ +export async function readProjectionEvidence( + read: () => Promise, + signal: AbortSignal, +): Promise { + if (signal.aborted) throw new ProjectionEvidenceError("cancelled"); + let abort: () => void = () => {}; + const cancelled = new Promise((_, reject) => { + abort = () => reject(new ProjectionEvidenceError("cancelled")); + signal.addEventListener("abort", abort, { once: true }); + }); + try { + return await Promise.race([Promise.resolve().then(read), cancelled]); + } catch (error) { + if (error instanceof ProjectionEvidenceError) throw error; + throw new ProjectionEvidenceError("evidence_unavailable"); + } finally { + signal.removeEventListener("abort", abort); + } +} diff --git a/lib/chat/projection/verifyProjectionObservation.ts b/lib/chat/projection/verifyProjectionObservation.ts new file mode 100644 index 000000000..fc7d2a4ac --- /dev/null +++ b/lib/chat/projection/verifyProjectionObservation.ts @@ -0,0 +1,182 @@ +import { z } from "zod"; +import { isExpiredStub } from "@workflow/core/serialization-format"; +import { encodeProjectionEvidence as json } from "./encodeProjectionEvidence"; +import { + projectionObservationSchema, + projectionProofSchema, + projectionReceiptSchema, +} from "./projectionSchemas"; +import { projectionEvents } from "./projectionEvents"; +import { parseProjectionRunAuthority } from "./parseProjectionRunAuthority"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +import { readProjectionEvidence } from "./readProjectionEvidence"; +import type { + ProjectionAuthority, + ProjectionEvidencePorts, + ProjectionProducer, +} from "./ProjectionEvidencePorts"; +const record = z.record(z.string(), z.unknown()); +/** Source-only verifier: caller must establish current chat authority; no default admitted deployments. */ +export async function verifyProjectionObservation(input: { + observation: unknown; + message: unknown; + scope: ProjectionAuthority; + producers: readonly ProjectionProducer[]; + ports: ProjectionEvidencePorts; + signal: AbortSignal; +}) { + let observation; + try { + json(input.observation); + observation = projectionObservationSchema.parse(input.observation); + } catch { + throw new ProjectionEvidenceError("invalid_observation"); + } + const { data } = observation; + const expectedText = + data.original.type === "custom" + ? "This view cannot display additional model content." + : "This view cannot display a reasoning attachment."; + if ( + observation.id !== `${data.assistantMessageId}:projection:${data.ordinal}` || + data.fallback.text !== expectedText + ) + throw new ProjectionEvidenceError("invalid_observation"); + const message = z + .object({ id: z.string(), role: z.literal("assistant"), parts: z.array(z.unknown()) }) + .safeParse(input.message); + const span = data.fallback.partIndex; + if ( + !message.success || + message.data.id !== data.assistantMessageId || + json(message.data.parts[span - 1] ?? null) !== json(observation) || + json(message.data.parts[span] ?? null) !== + json({ type: "text", text: expectedText, state: "done" }) + ) + throw new ProjectionEvidenceError("span_mismatch"); + if (!input.producers.length) throw new ProjectionEvidenceError("producer_mismatch"); + const deadline = AbortSignal.timeout(5000); + const signal = AbortSignal.any([input.signal, deadline]); + const read = async (operation: () => Promise) => { + try { + return await readProjectionEvidence(operation, signal); + } catch (error) { + if (deadline.aborted && !input.signal.aborted) + throw new ProjectionEvidenceError("evidence_timeout"); + throw error; + } + }; + const rawRun = await read(() => input.ports.readRun(data.originRunId, signal)); + const run = record.safeParse(rawRun); + if (!run.success) throw new ProjectionEvidenceError("invalid_evidence"); + const producer = input.producers.find( + p => p.deploymentId === run.data.deploymentId && p.workflowName === run.data.workflowName, + ); + if (!producer || run.data.runId !== data.originRunId) + throw new ProjectionEvidenceError("producer_mismatch"); + // SDK consumers disagree on future expiredAt values. Until the configured World + // contract is qualified, refuse those values without asserting they are expired. + if (run.data.expiredAt != null) { + const value = run.data.expiredAt; + const timestamp = + value instanceof Date ? value.getTime() : typeof value === "string" ? Date.parse(value) : NaN; + if (!Number.isFinite(timestamp)) throw new ProjectionEvidenceError("invalid_evidence"); + throw new ProjectionEvidenceError( + timestamp <= Date.now() ? "evidence_expired" : "evidence_unavailable", + ); + } + if (isExpiredStub(run.data.input)) throw new ProjectionEvidenceError("evidence_expired"); + const authority = parseProjectionRunAuthority(run.data.input); + if ( + authority.accountId !== input.scope.accountId || + authority.chatId !== input.scope.chatId || + authority.sessionId !== input.scope.sessionId + ) + throw new ProjectionEvidenceError("authority_mismatch"); + const rawStep = await read(() => + input.ports.readStep(data.originRunId, data.originStepId, signal), + ); + const step = record.safeParse(rawStep); + if (!step.success) throw new ProjectionEvidenceError("invalid_evidence"); + if ( + step.data.runId !== data.originRunId || + step.data.stepId !== data.originStepId || + step.data.stepName !== producer.stepName + ) + throw new ProjectionEvidenceError("producer_mismatch"); + if (step.data.status !== "completed") throw new ProjectionEvidenceError("proof_pending"); + const output = record.safeParse(step.data.output); + if (output.success && output.data.generatedProjectionObservations !== undefined) + json(output.data.generatedProjectionObservations, 16_777_216); + const proof = projectionProofSchema.safeParse( + output.success ? output.data.generatedProjectionObservations : undefined, + ); + if (!proof.success) throw new ProjectionEvidenceError("proof_missing"); + const identities = new Set(); + let previous = -1; + for (const item of proof.data.observations) { + const value = item.observation.data; + if ( + value.originRunId !== data.originRunId || + value.originStepId !== data.originStepId || + value.assistantMessageId !== data.assistantMessageId || + value.ordinal <= previous || + identities.has(item.observation.id) + ) + throw new ProjectionEvidenceError("invalid_evidence"); + previous = value.ordinal; + identities.add(item.observation.id); + } + const rawReceipt = await read(() => + input.ports.readReceipt(data.originRunId, data.originStepId, producer.proofStepName, signal), + ); + const receiptRecord = record.safeParse(rawReceipt); + if (!receiptRecord.success) throw new ProjectionEvidenceError("proof_missing"); + if ( + receiptRecord.data.runId !== data.originRunId || + receiptRecord.data.stepName !== producer.proofStepName || + typeof receiptRecord.data.stepId !== "string" || + receiptRecord.data.stepId === data.originStepId + ) + throw new ProjectionEvidenceError("producer_mismatch"); + if (receiptRecord.data.status !== "completed") throw new ProjectionEvidenceError("proof_pending"); + if (receiptRecord.data.output !== undefined) json(receiptRecord.data.output, 16_777_216); + const receipt = projectionReceiptSchema.safeParse(receiptRecord.data.output); + if (!receipt.success) throw new ProjectionEvidenceError("proof_missing"); + if (receipt.data.producerStepId !== data.originStepId) + throw new ProjectionEvidenceError("producer_mismatch"); + if ( + json(receipt.data.generatedProjectionObservations, 16_777_216) !== json(proof.data, 16_777_216) + ) + throw new ProjectionEvidenceError("proof_missing"); + const matches = proof.data.observations.filter( + item => json(item.observation) === json(observation), + ); + const expectedEvents = projectionEvents(observation); + if ( + matches.length !== 1 || + json(matches[0].events, 16_777_216) !== json(expectedEvents, 16_777_216) + ) + throw new ProjectionEvidenceError("proof_missing"); + const chunks = await read(() => input.ports.readCanonical(data.originRunId, signal)); + if (!Array.isArray(chunks) || chunks.length > 10000) + throw new ProjectionEvidenceError("evidence_limit"); + json(chunks, 16_777_216); + let occurrences = 0; + let activeAssistant: unknown; + const expected = json(expectedEvents, 16_777_216); + for (let index = 0; index < chunks.length; index++) { + const chunk = record.safeParse(chunks[index]); + if (!chunk.success) throw new ProjectionEvidenceError("canonical_mismatch"); + if (chunk.data.type === "start") activeAssistant = chunk.data.messageId; + if (chunk.data.type === "finish" || chunk.data.type === "abort" || chunk.data.type === "error") + activeAssistant = undefined; + if (json(chunks.slice(index, index + expectedEvents.length), 16_777_216) === expected) { + if (activeAssistant !== data.assistantMessageId) + throw new ProjectionEvidenceError("canonical_mismatch"); + occurrences++; + } + } + if (occurrences !== 1) throw new ProjectionEvidenceError("canonical_mismatch"); + return data.original; +} diff --git a/lib/chat/projection/writeProjectionObservation.ts b/lib/chat/projection/writeProjectionObservation.ts new file mode 100644 index 000000000..34db9102e --- /dev/null +++ b/lib/chat/projection/writeProjectionObservation.ts @@ -0,0 +1,55 @@ +import { encodeStrictJson } from "@/lib/chat/fence/encodeStrictJson"; +import { projectionObservationSchema, type ProjectionProof } from "./projectionSchemas"; +import { projectionEvents } from "./projectionEvents"; +import { ProjectionEvidenceError } from "./ProjectionEvidenceError"; +/** + * Fresh native events only. The caller must never supply history/seed parts here. + * Accepted public writes are NOT storage ACKs. This candidate is usable only after + * independent completed-step and canonical-stream readback by the verifier. + */ +export async function writeProjectionObservation( + input: { + originRunId: string; + originStepId: string; + assistantMessageId: string; + ordinal: number; + partIndex: number; + original: unknown; + }, + write: (chunk: unknown) => Promise, +): Promise { + let observation; + try { + const original = JSON.parse( + encodeStrictJson(input.original, { + omitUndefinedObjectProperties: true, + maxBytes: 1_048_576, + }), + ); + observation = projectionObservationSchema.parse({ + type: "data-recoup-sdk-observation", + id: `${input.assistantMessageId}:projection:${input.ordinal}`, + data: { + version: 1, + originRunId: input.originRunId, + originStepId: input.originStepId, + assistantMessageId: input.assistantMessageId, + ordinal: input.ordinal, + original, + fallback: { + partIndex: input.partIndex, + text: + original.type === "custom" + ? "This view cannot display additional model content." + : "This view cannot display a reasoning attachment.", + }, + }, + }); + encodeStrictJson(observation, { omitUndefinedObjectProperties: true, maxBytes: 1_048_576 }); + } catch { + throw new ProjectionEvidenceError("invalid_observation"); + } + const events = projectionEvents(observation); + for (const event of events) await write(event); + return { observation, events, canonicalWrite: "requires-readback" }; +} diff --git a/lib/chat/runs/__tests__/handleStartChatRun.test.ts b/lib/chat/runs/__tests__/handleStartChatRun.test.ts index 422f4d31a..d06bbab9d 100644 --- a/lib/chat/runs/__tests__/handleStartChatRun.test.ts +++ b/lib/chat/runs/__tests__/handleStartChatRun.test.ts @@ -140,7 +140,7 @@ describe("handleStartChatRun", () => { // output live". That route keys on chats.active_stream_id, so a headless run // that never claims the slot is unresumable (chat#1923). it("claims chats.active_stream_id with the run id so the run is resumable", async () => { - await handleStartChatRun({} as never); + await handleStartChatRun({ headers: new Headers() } as never); expect(compareAndSetChatActiveStreamId).toHaveBeenCalledWith("chat-1", null, "wrun_abc"); }); @@ -190,3 +190,15 @@ describe("handleStartChatRun trigger_run_id link (chat#2006 item 4a)", () => { expect(await res.json()).toEqual({ runId: "wrun_abc", chatId: "chat-1", sessionId: "sess-1" }); }); }); + +it("rejects carried projection before provisioning or minting a key", async () => { + vi.clearAllMocks(); + vi.mocked(validateChatRunRequest).mockResolvedValue({ + ...validated, + messages: [{ id: "a", role: "assistant", parts: [{ type: "data-recoup-sdk-observation" }] }], + } as never); + expect((await handleStartChatRun(req())).status).toBe(400); + expect(provisionRunSession).not.toHaveBeenCalled(); + expect(mintEphemeralAccountKey).not.toHaveBeenCalled(); + expect(start).not.toHaveBeenCalled(); +}); diff --git a/lib/chat/runs/handleStartChatRun.ts b/lib/chat/runs/handleStartChatRun.ts index b81fbeb87..d9e214e4f 100644 --- a/lib/chat/runs/handleStartChatRun.ts +++ b/lib/chat/runs/handleStartChatRun.ts @@ -1,3 +1,8 @@ +import { selectStreamProtocol } from "../continuation/selectStreamProtocol"; +import { buildContinuationMarker } from "../continuation/buildContinuationMarker"; +import { CONTINUATION_HEADER, type StreamProtocol } from "../continuation/streamProtocol"; +import { ContinuationError } from "../continuation/ContinuationError"; +import { prepareProjectionHistory } from "@/lib/chat/projection/prepareProjectionHistory"; import { NextRequest, NextResponse } from "next/server"; import { start } from "workflow/api"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; @@ -41,6 +46,30 @@ export async function handleStartChatRun(request: NextRequest): Promise { + await prepareProjectionHistory(body.messages); const decision = await getGeneralAgent(body); const convertedMessages = ( diff --git a/lib/chat/toolChains/__tests__/getPrepareStepResult.test.ts b/lib/chat/toolChains/__tests__/getPrepareStepResult.test.ts index df582c015..50b2456a6 100644 --- a/lib/chat/toolChains/__tests__/getPrepareStepResult.test.ts +++ b/lib/chat/toolChains/__tests__/getPrepareStepResult.test.ts @@ -9,7 +9,7 @@ vi.mock("../toolChains", () => ({ custom_chain: [ { toolName: "custom_step_one", - system: "Custom system prompt for step one", + instructions: "Custom system prompt for step one", }, { toolName: "custom_step_two", @@ -219,7 +219,7 @@ describe("getPrepareStepResult", () => { const result = getPrepareStepResult(options as any); expect(result).toEqual({ toolChoice: { type: "tool", toolName: "custom_step_one" }, - system: "Custom system prompt for step one", + instructions: "Custom system prompt for step one", model: "gpt-4-turbo", }); }); diff --git a/lib/chat/toolChains/__tests__/toolChains.test.ts b/lib/chat/toolChains/__tests__/toolChains.test.ts index eef64a7ae..b3d0c8f6d 100644 --- a/lib/chat/toolChains/__tests__/toolChains.test.ts +++ b/lib/chat/toolChains/__tests__/toolChains.test.ts @@ -13,9 +13,9 @@ describe("toolChains", () => { it("allows tool chain item with system prompt", () => { const item: ToolChainItem = { toolName: "test_tool", - system: "Custom system prompt", + instructions: "Custom system prompt", }; - expect(item.system).toBe("Custom system prompt"); + expect(item.instructions).toBe("Custom system prompt"); }); it("allows tool chain item with messages", () => { @@ -47,12 +47,12 @@ describe("toolChains", () => { const result: PrepareStepResult = { toolChoice: { type: "tool", toolName: "test_tool" }, model: "gemini-2.5-pro" as any, - system: "Custom prompt", + instructions: "Custom prompt", messages: [{ role: "user", content: "Test" }], }; expect(result.toolChoice).toBeDefined(); expect(result.model).toBeDefined(); - expect(result.system).toBeDefined(); + expect(result.instructions).toBeDefined(); expect(result.messages).toBeDefined(); }); }); @@ -81,10 +81,10 @@ describe("toolChains", () => { it("includes update_account_info with custom system prompt", () => { const chain = TOOL_CHAINS.create_new_artist; const updateAccountStep = chain.find( - item => item.toolName === "update_account_info" && item.system, + item => item.toolName === "update_account_info" && item.instructions, ); expect(updateAccountStep).toBeDefined(); - expect(updateAccountStep?.system).toContain("get_spotify_search"); + expect(updateAccountStep?.instructions).toContain("get_spotify_search"); }); it("has expected number of steps", () => { @@ -110,16 +110,18 @@ describe("toolChains", () => { const chain = TOOL_CHAINS.create_new_artist; const generateStep = chain.find(item => item.toolName === "generate_txt_file"); expect(generateStep).toBeDefined(); - expect(generateStep?.system).toBeDefined(); - expect(generateStep?.system).toContain("knowledge base report"); + expect(generateStep?.instructions).toBeDefined(); + expect(generateStep?.instructions).toContain("knowledge base report"); }); it("includes update_account_info step with system prompt to link knowledge base", () => { const chain = TOOL_CHAINS.create_new_artist; const updateSteps = chain.filter(item => item.toolName === "update_account_info"); - const knowledgeLinkStep = updateSteps.find(item => item.system?.includes("knowledges")); + const knowledgeLinkStep = updateSteps.find(item => + item.instructions?.includes("knowledges"), + ); expect(knowledgeLinkStep).toBeDefined(); - expect(knowledgeLinkStep?.system).toContain("txtUrl"); + expect(knowledgeLinkStep?.instructions).toContain("txtUrl"); }); }); @@ -133,7 +135,7 @@ describe("toolChains", () => { const chain = TOOL_CHAINS.create_release_report; const generateStep = chain.find(item => item.toolName === "generate_txt_file"); expect(generateStep).toBeDefined(); - expect(generateStep?.system).toBeDefined(); + expect(generateStep?.instructions).toBeDefined(); }); it("ends with send_email", () => { diff --git a/lib/chat/toolChains/createNewArtistToolChain.ts b/lib/chat/toolChains/createNewArtistToolChain.ts index b1ab3a1a2..479114f9a 100644 --- a/lib/chat/toolChains/createNewArtistToolChain.ts +++ b/lib/chat/toolChains/createNewArtistToolChain.ts @@ -5,12 +5,12 @@ export const createNewArtistToolChain: ToolChainItem[] = [ { toolName: "get_spotify_search" }, { toolName: "update_account_info", - system: + instructions: "From the get_spotify_search results, select the artist whose name best matches the user-provided artist name (prefer exact, case-insensitive match; otherwise choose the closest by name and popularity). Update the account using the update_account_info tool with the artist's basic information: name, image, label, etc.", }, { toolName: "update_artist_socials", - system: + instructions: "Using the matched Spotify artist from the get_spotify_search results, update the artist's socials with the Spotify profile URL (found in external_urls.spotify). Pass the URL in the urls array to update_artist_socials.", }, { toolName: "artist_deep_research" }, @@ -27,13 +27,13 @@ export const createNewArtistToolChain: ToolChainItem[] = [ }, { toolName: "generate_txt_file", - system: + instructions: "Using all the research gathered (from artist_deep_research, spotify_deep_research, search_web results, etc.), generate a comprehensive knowledge base report following the reference template. Include artist biography, discography, social media presence, notable achievements, and any other relevant information. Pass the complete report text to generate_txt_file.", messages: [getKnowledgeBaseReportReferenceMessage()], }, { toolName: "update_account_info", - system: + instructions: "Using the txtUrl returned from generate_txt_file, update the artist's knowledges array to include the new knowledge base entry. Set the knowledge object with: url (the txtUrl), name (e.g., 'Artist Knowledge Base Report'), and type ('text/plain').", }, { toolName: "youtube_login" }, diff --git a/lib/chat/toolChains/create_release_report/createReleaseReportToolChain.ts b/lib/chat/toolChains/create_release_report/createReleaseReportToolChain.ts index afac8c0e8..4e2001060 100644 --- a/lib/chat/toolChains/create_release_report/createReleaseReportToolChain.ts +++ b/lib/chat/toolChains/create_release_report/createReleaseReportToolChain.ts @@ -12,7 +12,7 @@ export const createReleaseReportToolChain: ToolChainItem[] = [ }, { toolName: "generate_txt_file", - system: `Create a Release Report TXT file matching the reference release report. + instructions: `Create a Release Report TXT file matching the reference release report. Do not make up any data. Only use the data that is present in the web_deep_research tool results. The following sections must be included in the report (only if the data is present in the web_deep_research tool results) passed to the contents parameter in the generate_txt_file tool: - {artwork title} Summary @@ -30,7 +30,7 @@ export const createReleaseReportToolChain: ToolChainItem[] = [ }, { toolName: "update_account_info", - system: + instructions: "Attach the newly created release report to the artist's account info as a knowledge base. IMPORTANT: Use the active_artist_account_id from the system prompt as the artistId parameter.", }, { diff --git a/lib/chat/toolChains/getPrepareStepResult.ts b/lib/chat/toolChains/getPrepareStepResult.ts index 4362ea489..6344d0985 100644 --- a/lib/chat/toolChains/getPrepareStepResult.ts +++ b/lib/chat/toolChains/getPrepareStepResult.ts @@ -48,8 +48,8 @@ const getPrepareStepResult = (options: PrepareStepOptions): PrepareStepResult | }; // Add system prompt if available - if (nextToolItem.system) { - result.system = nextToolItem.system; + if (nextToolItem.instructions) { + result.instructions = nextToolItem.instructions; } // Add messages if available diff --git a/lib/chat/toolChains/toolChains.ts b/lib/chat/toolChains/toolChains.ts index 1761d8ba4..4ad2c3108 100644 --- a/lib/chat/toolChains/toolChains.ts +++ b/lib/chat/toolChains/toolChains.ts @@ -4,14 +4,14 @@ import { createNewArtistToolChain } from "./createNewArtistToolChain"; export type ToolChainItem = { toolName: string; - system?: string; + instructions?: string; messages?: ModelMessage[]; }; export type PrepareStepResult = { toolChoice?: { type: "tool"; toolName: string }; model?: LanguageModel; - system?: string; + instructions?: string; messages?: ModelMessage[]; }; diff --git a/lib/chat/types.ts b/lib/chat/types.ts index 83c9d9765..9bf3eae2f 100644 --- a/lib/chat/types.ts +++ b/lib/chat/types.ts @@ -4,11 +4,11 @@ import { type ModelMessage, type ToolSet, type StopCondition, type ToolLoopAgent export interface RoutingDecision { model: string; instructions: string; - agent: ToolLoopAgent; + agent: ToolLoopAgent, never>; stopWhen?: StopCondition> | StopCondition>[] | undefined; } export interface ChatConfig { - agent: ToolLoopAgent; + agent: ToolLoopAgent, never>; messages: ModelMessage[]; } diff --git a/lib/chat/validateChatRequest.ts b/lib/chat/validateChatRequest.ts index 195be434f..cffc8a331 100644 --- a/lib/chat/validateChatRequest.ts +++ b/lib/chat/validateChatRequest.ts @@ -1,3 +1,4 @@ +import { prepareProjectionHistory } from "@/lib/chat/projection/prepareProjectionHistory"; import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; import { z } from "zod"; @@ -117,9 +118,26 @@ export async function validateChatRequest( } // Convert messages to UIMessage format and get the last (newest) message + try { + await prepareProjectionHistory(validatedBody.messages); + } catch { + return NextResponse.json( + { status: "error", message: "Projection history evidence unavailable" }, + { status: 400, headers: getCorsHeaders() }, + ); + } const uiMessages = convertToUiMessages(validatedBody.messages); const { lastMessage } = validateMessages(uiMessages); + try { + await prepareProjectionHistory(uiMessages); + } catch { + return NextResponse.json( + { status: "error", message: "Projection history evidence unavailable" }, + { status: 400, headers: getCorsHeaders() }, + ); + } + // Setup conversation: auto-create room if needed and persist user message // Use the message's original ID to prevent duplicate memory rows on upsert const { roomId: finalRoomId } = await setupConversation({ diff --git a/lib/contracts/__tests__/publishedChatReadFailures.test.ts b/lib/contracts/__tests__/publishedChatReadFailures.test.ts index 711178667..c255a40bd 100644 --- a/lib/contracts/__tests__/publishedChatReadFailures.test.ts +++ b/lib/contracts/__tests__/publishedChatReadFailures.test.ts @@ -1,3 +1,4 @@ +import { gateStoredContinuation } from "@/lib/chat/continuation/gateStoredContinuation"; import Ajv from "ajv"; import { NextRequest } from "next/server"; import { beforeEach, describe, expect, it, vi } from "vitest"; @@ -22,6 +23,9 @@ import { deleteChat } from "@/lib/supabase/chats/deleteChat"; import { upsertChatRead } from "@/lib/supabase/chat_reads/upsertChatRead"; import { start, getRun } from "workflow/api"; import fixture from "../fixtures/published-docs.json"; +vi.mock("@/lib/chat/continuation/gateStoredContinuation", () => ({ + gateStoredContinuation: vi.fn(async () => null), +})); vi.mock("@/lib/supabase/serverClient", () => ({ default: {} })); vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: vi.fn() })); @@ -74,6 +78,7 @@ function request(method: string, path: string, body?: unknown) { } beforeEach(() => { + vi.mocked(gateStoredContinuation).mockResolvedValue(null); vi.clearAllMocks(); vi.mocked(validateAuthContext).mockResolvedValue({ accountId, diff --git a/lib/credits/__tests__/getCreditUsageStepBoundary.test.ts b/lib/credits/__tests__/getCreditUsageStepBoundary.test.ts new file mode 100644 index 000000000..61e2eb620 --- /dev/null +++ b/lib/credits/__tests__/getCreditUsageStepBoundary.test.ts @@ -0,0 +1,31 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { getCreditUsage } from "../getCreditUsage"; +import { getTokenCreditUsageStep } from "../getTokenCreditUsageStep"; + +vi.mock("../getTokenCreditUsageStep", () => ({ getTokenCreditUsageStep: vi.fn(async () => 0.06) })); +// A red test against the old direct lookup must still never access a provider. +vi.mock("@/lib/ai/getModel", () => ({ getModel: vi.fn(async () => undefined) })); +const usage = { + inputTokens: 1000, + outputTokens: 500, + totalTokens: 1500, + inputTokenDetails: { noCacheTokens: 1000, cacheReadTokens: 0, cacheWriteTokens: 0 }, + outputTokenDetails: { textTokens: 500, reasoningTokens: 0 }, +}; +beforeEach(() => vi.clearAllMocks()); + +it("keeps a finite positive gateway cost outside the pricing lookup step", async () => { + expect(await getCreditUsage(usage, "fixture", 0.07)).toBe(0.07); + expect(getTokenCreditUsageStep).not.toHaveBeenCalled(); +}); + +it.each([undefined, 0, -1, NaN, Infinity])( + "routes fallback %s through one serializable pricing step", + async cost => { + expect(await getCreditUsage(usage, "fixture", cost)).toBe(0.06); + expect(getTokenCreditUsageStep).toHaveBeenCalledExactlyOnceWith( + { inputTokens: 1000, outputTokens: 500 }, + "fixture", + ); + }, +); diff --git a/lib/credits/__tests__/handleChatCredits.test.ts b/lib/credits/__tests__/handleChatCredits.test.ts index 34912ae3c..c49bec054 100644 --- a/lib/credits/__tests__/handleChatCredits.test.ts +++ b/lib/credits/__tests__/handleChatCredits.test.ts @@ -18,7 +18,7 @@ const mockRecordCreditDeduction = vi.mocked(recordCreditDeduction); const USAGE = { inputTokens: 1000, outputTokens: 500, - cachedInputTokens: 0, + inputTokenDetails: { cacheReadTokens: 0 }, } as never; describe("handleChatCredits", () => { @@ -31,6 +31,41 @@ describe("handleChatCredits", () => { vi.restoreAllMocks(); }); + it("still charges persisted sparse usage without nested cache details", async () => { + mockGetCreditUsage.mockResolvedValue(0.05); + await handleChatCredits({ + usage: { inputTokens: 1000, outputTokens: 500, totalTokens: 1500 } as never, + model: "fixture-model", + accountId: "account-123", + source: "api", + toolCallCount: 2, + }); + expect(mockRecordCreditDeduction).toHaveBeenCalledWith( + expect.objectContaining({ + accountId: "account-123", + creditsToDeduct: 50_000, + source: "api", + toolCallCount: 2, + cachedInputTokens: undefined, + }), + ); + }); + + it("preserves cached tokens from persisted v6 usage in the audit row", async () => { + mockGetCreditUsage.mockResolvedValue(0.05); + await handleChatCredits({ + usage: { inputTokens: 1000, outputTokens: 500, cachedInputTokens: 125 } as never, + model: "fixture-model", + accountId: "account-123", + }); + expect(mockRecordCreditDeduction).toHaveBeenCalledWith( + expect.objectContaining({ + creditsToDeduct: 50_000, + cachedInputTokens: 125, + }), + ); + }); + describe("credit deduction", () => { it("deducts credits and forwards token detail to the usage_events row", async () => { mockGetCreditUsage.mockResolvedValue(0.05); // $0.05 = 50,000 micro-dollars diff --git a/lib/credits/countToolCallsInMessage.ts b/lib/credits/countToolCallsInMessage.ts index faec8303a..7d1f6a827 100644 --- a/lib/credits/countToolCallsInMessage.ts +++ b/lib/credits/countToolCallsInMessage.ts @@ -1,6 +1,7 @@ -import { isToolUIPart, type UIMessage } from "ai"; +import type { UIMessage } from "ai"; -/** Counts tool UI parts in the accumulated message, regardless of execution state. */ +/** Counts tool UI parts without importing the Node-dependent SDK into durable workflow code. */ export function countToolCallsInMessage(message: UIMessage): number { - return message.parts.filter(isToolUIPart).length; + return message.parts.filter(part => part.type === "dynamic-tool" || part.type.startsWith("tool-")) + .length; } diff --git a/lib/credits/getCreditUsage.ts b/lib/credits/getCreditUsage.ts index e9bd865bc..8603a45a3 100644 --- a/lib/credits/getCreditUsage.ts +++ b/lib/credits/getCreditUsage.ts @@ -1,5 +1,5 @@ -import { getModel } from "@/lib/ai/getModel"; -import { LanguageModelUsage } from "ai"; +import { getTokenCreditUsageStep } from "./getTokenCreditUsageStep"; +import type { LanguageModelUsage } from "ai"; /** * Calculates the total spend in USD for a given language model usage. @@ -28,32 +28,8 @@ export const getCreditUsage = async ( return gatewayCostUsd; } - try { - const model = await getModel(modelId); - if (!model) { - console.error(`Model not found for ID: ${modelId}`); - return 0; - } - - const { inputTokens, outputTokens } = usage; - - if (!inputTokens || !outputTokens) { - console.error("No tokens found in usage"); - return 0; - } - - // Check if model has pricing - if (!model.pricing?.input || !model.pricing?.output) { - return 0; - } - - const inputCost = inputTokens * Number(model.pricing.input); - const outputCost = outputTokens * Number(model.pricing.output); - const totalCost = inputCost + outputCost; - - return totalCost; - } catch (error) { - console.error("Failed to calculate credit usage:", error); - return 0; - } + return getTokenCreditUsageStep( + { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens }, + modelId, + ); }; diff --git a/lib/credits/getTokenCreditUsageStep.ts b/lib/credits/getTokenCreditUsageStep.ts new file mode 100644 index 000000000..f36798ecb --- /dev/null +++ b/lib/credits/getTokenCreditUsageStep.ts @@ -0,0 +1,38 @@ +import { getModel } from "@/lib/ai/getModel"; +import type { LanguageModelUsage } from "ai"; + +/** Resolve the existing token estimate inside a durable step; never performs a debit. */ +export async function getTokenCreditUsageStep( + usage: Pick, + modelId: string, +): Promise { + "use step"; + try { + const model = await getModel(modelId); + if (!model) { + console.error(`Model not found for ID: ${modelId}`); + return 0; + } + + const { inputTokens, outputTokens } = usage; + + if (!inputTokens || !outputTokens) { + console.error("No tokens found in usage"); + return 0; + } + + // Check if model has pricing + if (!model.pricing?.input || !model.pricing?.output) { + return 0; + } + + const inputCost = inputTokens * Number(model.pricing.input); + const outputCost = outputTokens * Number(model.pricing.output); + const totalCost = inputCost + outputCost; + + return totalCost; + } catch (error) { + console.error("Failed to calculate credit usage:", error); + return 0; + } +} diff --git a/lib/credits/handleChatCredits.ts b/lib/credits/handleChatCredits.ts index 0de2f8e8a..9c19b1a46 100644 --- a/lib/credits/handleChatCredits.ts +++ b/lib/credits/handleChatCredits.ts @@ -1,3 +1,4 @@ +import { normalizeLanguageModelUsage } from "@/lib/agent/messageMetadata/normalizeLanguageModelUsage"; import { getCreditUsage } from "./getCreditUsage"; import { usdToCredits } from "@/lib/credits/usdToCredits"; import { recordCreditDeduction } from "./recordCreditDeduction"; @@ -65,7 +66,7 @@ export const handleChatCredits = async ({ modelId: model, inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, - cachedInputTokens: usage.cachedInputTokens, + cachedInputTokens: normalizeLanguageModelUsage(usage).inputTokenDetails.cacheReadTokens, ...(resourceUrl ? { resourceUrl } : {}), ...(toolCallCount !== undefined ? { toolCallCount } : {}), }); diff --git a/lib/evals/scorers/CatalogAvailability.ts b/lib/evals/scorers/CatalogAvailability.ts index f4829ea41..8b5490a96 100644 --- a/lib/evals/scorers/CatalogAvailability.ts +++ b/lib/evals/scorers/CatalogAvailability.ts @@ -19,7 +19,7 @@ export const CatalogAvailability = async ({ const result = await generateObject({ model: DEFAULT_MODEL, - system: `You are a music catalog analyst. Your job is to analyze song recommendations and determine which ones are available in the provided music catalog. + instructions: `You are a music catalog analyst. Your job is to analyze song recommendations and determine which ones are available in the provided music catalog. Instructions: 1. Extract all song recommendations from the output text diff --git a/lib/evals/scorers/QuestionAnswered.ts b/lib/evals/scorers/QuestionAnswered.ts index abe0222cb..ee452a3b4 100644 --- a/lib/evals/scorers/QuestionAnswered.ts +++ b/lib/evals/scorers/QuestionAnswered.ts @@ -18,7 +18,7 @@ export const QuestionAnswered = async ({ try { const result = await generateObject({ model: DEFAULT_MODEL, - system: `You are an AI evaluation expert. Your job is to determine if an AI assistant actually answered the customer's question with a specific answer, or if it deflected, explained why it couldn't answer, or gave generic suggestions without providing the requested information. + instructions: `You are an AI evaluation expert. Your job is to determine if an AI assistant actually answered the customer's question with a specific answer, or if it deflected, explained why it couldn't answer, or gave generic suggestions without providing the requested information. Instructions: 1. Read the customer's question carefully to understand what specific information they're asking for diff --git a/lib/networking/getCorsHeaders.ts b/lib/networking/getCorsHeaders.ts index 517a4be65..cb5ed1f3f 100644 --- a/lib/networking/getCorsHeaders.ts +++ b/lib/networking/getCorsHeaders.ts @@ -3,11 +3,15 @@ * * @returns The CORS headers. */ -export function getCorsHeaders(): Record { +export function getCorsHeaders( + options: { streamContinuation?: boolean } = {}, +): Record { return { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS, PATCH", - "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With, x-api-key", + "Access-Control-Allow-Headers": + "Content-Type, Authorization, X-Requested-With, x-api-key" + + (options.streamContinuation ? ", X-Recoup-Stream-Continuation" : ""), // Browsers hide every non-safelisted response header from cross-origin JS // unless it is named here. Without this `x-workflow-run-id` — documented // as part of the 200 on the chat endpoints since the workflow cutover — diff --git a/lib/organizations/__tests__/canAccessAccount.test.ts b/lib/organizations/__tests__/canAccessAccount.test.ts index 9d7e9f562..b969c7210 100644 --- a/lib/organizations/__tests__/canAccessAccount.test.ts +++ b/lib/organizations/__tests__/canAccessAccount.test.ts @@ -179,3 +179,14 @@ describe("canAccessAccount", () => { }); }); }); +it("does not treat null membership IDs as organization authority", async () => { + vi.mocked(getAccountOrganizations).mockResolvedValue([ + { organization_id: null }, + { organization_id: "org" }, + ] as never); + vi.mocked(selectAccountOrganizationIds).mockResolvedValue([]); + expect(await canAccessAccount({ currentAccountId: "caller", targetAccountId: "target" })).toBe( + false, + ); + expect(selectAccountOrganizationIds).toHaveBeenLastCalledWith("target", ["org"]); +}); diff --git a/lib/organizations/canAccessAccount.ts b/lib/organizations/canAccessAccount.ts index 3576f3054..32ef869f0 100644 --- a/lib/organizations/canAccessAccount.ts +++ b/lib/organizations/canAccessAccount.ts @@ -49,7 +49,7 @@ export async function canAccessAccount(params: CanAccessAccountParams): Promise< return true; } - const orgIds = currentOrgs.map(m => m.organization_id); + const orgIds = currentOrgs.map(m => m.organization_id).filter((id): id is string => id !== null); if (orgIds.includes(targetAccountId)) { params.onAllowed?.({ basis: "organization_membership", organizationId: targetAccountId }); return true; diff --git a/next.config.ts b/next.config.ts index a15dd197d..6d1c9f477 100644 --- a/next.config.ts +++ b/next.config.ts @@ -2,11 +2,18 @@ import type { NextConfig } from "next"; import { withWorkflow } from "workflow/next"; const nextConfig: NextConfig = { - // OAuth model class names are persistent storage keys; bundling renames them. - serverExternalPackages: ["oidc-provider"], env: { RESOURCE_WALLET_ADDRESS: process.env.RESOURCE_WALLET_ADDRESS, }, + // `@vercel/oidc` (pulled in by `@ai-sdk/gateway@4`) does a runtime + // `require('./get-vercel-oidc-token.js')`. If bundled into the Workflow step + // route, that relative require can't resolve at runtime and the build's + // page-data collection throws. Keep the package external so Node resolves it + // (and its internal require) natively. Requires `@vercel/oidc` as a direct + // dependency so it's resolvable, and the webpack builder (Turbopack refuses + // to externalize it). + // Preserve OAuth model class names, which are persistent storage keys. + serverExternalPackages: ["oidc-provider", "@vercel/oidc"], experimental: { optimizePackageImports: ["date-fns", "@ai-sdk/anthropic", "@ai-sdk/openai", "@ai-sdk/google"], }, diff --git a/package.json b/package.json index 8cf4122df..90ee506fc 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "pnpm build:extension && next dev", - "build": "pnpm build:extension && next build && node scripts/mcp-oauth/checkProviderBuild.cjs", + "build": "pnpm build:extension && next build --webpack && node scripts/mcp-oauth/checkProviderBuild.cjs", "start": "next start", "format": "prettier -c .prettierrc --write \"**/*.{ts,js,cjs,json,md}\"", "format:check": "prettier -c .prettierrc --check \"**/*.{ts,js,cjs,json,md}\"", @@ -32,11 +32,11 @@ "test:pack-foundation-workflow": "node --test scripts/pack-foundation-workflow-fixture/__tests__/*.test.mjs && node scripts/pack-foundation-workflow-fixture/run.mjs" }, "dependencies": { - "@ai-sdk/anthropic": "^3.0.78", - "@ai-sdk/gateway": "3.0.119", - "@ai-sdk/google": "^3.0.79", - "@ai-sdk/mcp": "^1.0.43", - "@ai-sdk/openai": "^3.0.65", + "@ai-sdk/anthropic": "4.0.0", + "@ai-sdk/gateway": "4.0.2", + "@ai-sdk/google": "4.0.0", + "@ai-sdk/mcp": "2.0.0", + "@ai-sdk/openai": "4.0.8", "@chat-adapter/github": "^4.15.0", "@chat-adapter/slack": "^4.15.0", "@chat-adapter/state-ioredis": "^4.15.0", @@ -51,9 +51,10 @@ "@supabase/supabase-js": "^2.86.0", "@trigger.dev/sdk": "^4.4.3", "@vercel/blob": "^2.3.1", + "@vercel/oidc": "^3.2.0", "@vercel/sandbox": "2.0.0-beta.11", "@workflow/core": "4.2.4", - "ai": "6.0.190", + "ai": "7.0.2", "ai-evaluation": "npm:ai@7.0.105", "apify-client": "^2.20.0", "autoevals": "^0.0.129", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5501408b1..9cfe45afa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,20 +9,20 @@ importers: .: dependencies: '@ai-sdk/anthropic': - specifier: ^3.0.78 - version: 3.0.78(zod@4.1.13) + specifier: 4.0.0 + version: 4.0.0(zod@4.1.13) '@ai-sdk/gateway': - specifier: 3.0.119 - version: 3.0.119(zod@4.1.13) + specifier: 4.0.2 + version: 4.0.2(zod@4.1.13) '@ai-sdk/google': - specifier: ^3.0.79 - version: 3.0.79(zod@4.1.13) + specifier: 4.0.0 + version: 4.0.0(zod@4.1.13) '@ai-sdk/mcp': - specifier: ^1.0.43 - version: 1.0.43(zod@4.1.13) + specifier: 2.0.0 + version: 2.0.0(zod@4.1.13) '@ai-sdk/openai': - specifier: ^3.0.65 - version: 3.0.65(zod@4.1.13) + specifier: 4.0.8 + version: 4.0.8(zod@4.1.13) '@chat-adapter/github': specifier: ^4.15.0 version: 4.15.0 @@ -46,7 +46,7 @@ importers: version: 0.3.4(ws@8.18.3(bufferutil@4.0.9)(utf-8-validate@5.0.10))(zod@4.1.13) '@composio/vercel': specifier: ^0.3.4 - version: 0.3.4(@composio/core@0.3.4(ws@8.18.3(bufferutil@4.0.9)(utf-8-validate@5.0.10))(zod@4.1.13))(ai@6.0.190(zod@4.1.13)) + version: 0.3.4(@composio/core@0.3.4(ws@8.18.3(bufferutil@4.0.9)(utf-8-validate@5.0.10))(zod@4.1.13))(ai@7.0.2(zod@4.1.13)) '@fal-ai/client': specifier: ^1.9.5 version: 1.9.5 @@ -61,10 +61,13 @@ importers: version: 2.86.0(bufferutil@4.0.9)(utf-8-validate@5.0.10) '@trigger.dev/sdk': specifier: ^4.4.3 - version: 4.4.3(ai@6.0.190(zod@4.1.13))(bufferutil@4.0.9)(utf-8-validate@5.0.10)(zod@4.1.13) + version: 4.4.3(ai@7.0.2(zod@4.1.13))(bufferutil@4.0.9)(utf-8-validate@5.0.10)(zod@4.1.13) '@vercel/blob': specifier: ^2.3.1 version: 2.3.1 + '@vercel/oidc': + specifier: ^3.2.0 + version: 3.4.0 '@vercel/sandbox': specifier: 2.0.0-beta.11 version: 2.0.0-beta.11 @@ -72,8 +75,8 @@ importers: specifier: 4.2.4 version: 4.2.4(@opentelemetry/api@1.9.0) ai: - specifier: 6.0.190 - version: 6.0.190(zod@4.1.13) + specifier: 7.0.2 + version: 7.0.2(zod@4.1.13) ai-evaluation: specifier: npm:ai@7.0.105 version: ai@7.0.105(zod@4.1.13) @@ -264,15 +267,15 @@ packages: '@adraffy/ens-normalize@1.11.1': resolution: {integrity: sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==} - '@ai-sdk/anthropic@3.0.78': - resolution: {integrity: sha512-0OY12G20cUt6iU6htpEA1491Oz++NVxZxlmWGX4B7rSbeZ5pnDmOu6YtW9BKzdZlNx5Gn23i6WMxyZFoMKNcgA==} - engines: {node: '>=18'} + '@ai-sdk/anthropic@4.0.0': + resolution: {integrity: sha512-N0lT1g6/5DEIZvalpkpwYRCdu7n5qb8qPN3PcTem6k4VkPBLC2+T2LAAyx1GS0eNOxavVa0CP7n2kCiye0yyfw==} + engines: {node: '>=22'} peerDependencies: zod: ^3.25.76 || ^4.1.8 - '@ai-sdk/gateway@3.0.119': - resolution: {integrity: sha512-VAhfRWC+JexZakkVfmjaJKaTj00x7/UHdE8kMWL3NhuQAlf8oXtg9r4dfvFZrByXxchGRBvYE3biEUyibkg0xg==} - engines: {node: '>=18'} + '@ai-sdk/gateway@4.0.2': + resolution: {integrity: sha512-Jz1BiiTSvhDsCBJrkFRSqLHDRMVjFtYk9GdbSi3UOqY+/epza+oIESMDzfN4m+YHT/1IYmNEmxaMfjXOvxKDjQ==} + engines: {node: '>=22'} peerDependencies: zod: ^3.25.76 || ^4.1.8 @@ -282,27 +285,27 @@ packages: peerDependencies: zod: ^3.25.76 || ^4.1.8 - '@ai-sdk/google@3.0.79': - resolution: {integrity: sha512-QWVAvYeA7JzEX2wkSyXOWv/I9PD9kvTzdykkSTLi+Eu8RyJ6gA0tdPIGa8esEtOcHE//G5vy6FTB70qQw8l/uw==} - engines: {node: '>=18'} + '@ai-sdk/google@4.0.0': + resolution: {integrity: sha512-UXGGmsYmeJ8VEfFenETFd2SN5tGSU+g2yrLrCuL8uqUkDFpNqV9a9MSKdshh6EXQs8e+2PUELJwqe7qQO3UnSw==} + engines: {node: '>=22'} peerDependencies: zod: ^3.25.76 || ^4.1.8 - '@ai-sdk/mcp@1.0.43': - resolution: {integrity: sha512-HdDMeyCcfIn5tW/P1kJ+BmYP8vfY8vppRn7swbVNRcLeFz/cpwik+B+C49Up4u5scRAcATtRJywOa7/rA4BmIA==} - engines: {node: '>=18'} + '@ai-sdk/mcp@2.0.0': + resolution: {integrity: sha512-+N6gJ1AbcDk3+6asoEsdIojVmgEReKNcvWIT716pDL3AepGI6j7RJVdaRyhQLltwzTj0arwpwU4BBzvhOiCd/g==} + engines: {node: '>=22'} peerDependencies: zod: ^3.25.76 || ^4.1.8 - '@ai-sdk/openai@3.0.65': - resolution: {integrity: sha512-ZlVoWH+zrdiYDiUt6n/xvfCsk33mzsB81TUQkBRVx79rxU1FKZqVH9J/QCtEpSLqx0cUzjvtIw9l9p7EbUv+dw==} - engines: {node: '>=18'} + '@ai-sdk/openai@4.0.8': + resolution: {integrity: sha512-yW2UuS6jlu2LRYCd+cSpVdu/umf+QjypihYAiGvKk5HnpqQf21ffNjFbke9xo9jhT+TBt2YR30Fs5Sy0md/dfA==} + engines: {node: '>=22'} peerDependencies: zod: ^3.25.76 || ^4.1.8 - '@ai-sdk/provider-utils@4.0.27': - resolution: {integrity: sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw==} - engines: {node: '>=18'} + '@ai-sdk/provider-utils@5.0.0': + resolution: {integrity: sha512-zj66M02jc6ASYwIgWZowsooDUwaVngeNZQ3H10GwcPMZ+KR6gHMhcUuKl6tkai+JPXTKDyHY1pnszuxRtw2D4A==} + engines: {node: '>=22'} peerDependencies: zod: ^3.25.76 || ^4.1.8 @@ -312,18 +315,28 @@ packages: peerDependencies: zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/provider-utils@5.0.5': + resolution: {integrity: sha512-oI0t3dvCoqWNV1I8o1Rybi2DXDvHES5r/TrwtJW90tuFLVepgJlftPxrcjh8vaSvjqC2diTuA2vXyjKAyHJm4A==} + engines: {node: '>=22'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/provider@1.1.3': resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==} engines: {node: '>=18'} - '@ai-sdk/provider@3.0.10': - resolution: {integrity: sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw==} - engines: {node: '>=18'} + '@ai-sdk/provider@4.0.0': + resolution: {integrity: sha512-fr9Gs89prDWiuox/T+kCA+i2cJkHpxU5S+tr4megjTzRC27ZsvFhwjU/+XrqqMbvBUlfmXxTOYWy8ng45dsjIg==} + engines: {node: '>=22'} '@ai-sdk/provider@4.0.17': resolution: {integrity: sha512-VYMBxIQdcHqbIf1j+YZlI9Ati6LZ4wJe0GGd4z4a5H/KxTggjeOiyaVYTnfF7LHZK5jMQ+rofmzz4QPqf++NUw==} engines: {node: '>=22'} + '@ai-sdk/provider@4.0.2': + resolution: {integrity: sha512-pfPoy9J1B1xV7cqJ8MYHOsDYrMv5tR3+EMNfI249OhkD2uRakvav3Fo7XpD2luuN/YNCBY7KfEQc7vEV7KEtyw==} + engines: {node: '>=22'} + '@alloc/quick-lru@5.2.0': resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==} engines: {node: '>=10'} @@ -3791,14 +3804,14 @@ packages: resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==} engines: {node: '>= 8.0.0'} - ai@6.0.190: - resolution: {integrity: sha512-T+ixHbWZ6jmHRREpVVJTkFyWJeCekCdzLPan7lp1F32jG5OUw4+odlVYjtMRXVzogU+pWzpMmXdRiHUmdL/q0w==} - engines: {node: '>=18'} + ai@7.0.105: + resolution: {integrity: sha512-gkV3W+tTtWwQ41KNV/KjV8wabBrk+bnbnZ3f0AWp/T9LLyljose8uhFViKleVy7tIdEiR2PiS4BpbNdcExf7rQ==} + engines: {node: '>=22'} peerDependencies: zod: ^3.25.76 || ^4.1.8 - ai@7.0.105: - resolution: {integrity: sha512-gkV3W+tTtWwQ41KNV/KjV8wabBrk+bnbnZ3f0AWp/T9LLyljose8uhFViKleVy7tIdEiR2PiS4BpbNdcExf7rQ==} + ai@7.0.2: + resolution: {integrity: sha512-VMU08jHIDJnnKDrbC9AFa5ZsPpOTfAPRLvTRHtJk4FGAoeldmJROMxvZ2ak5lCjEJ2GP2OLPQbMRyEK8w0+S4A==} engines: {node: '>=22'} peerDependencies: zod: ^3.25.76 || ^4.1.8 @@ -3962,6 +3975,7 @@ packages: axios-retry@4.5.0: resolution: {integrity: sha512-aR99oXhpEDGo0UuAlYcn2iGRds30k366Zfa05XWScR9QaQD4JYiP3/1Qt1u7YlefUOK+cn0CcwoL1oefavQUlQ==} + deprecated: axios-retry is no longer maintained. See https://github.com/softonic/axios-retry for alternatives. peerDependencies: axios: 0.x || 1.x @@ -8334,16 +8348,16 @@ snapshots: '@adraffy/ens-normalize@1.11.1': {} - '@ai-sdk/anthropic@3.0.78(zod@4.1.13)': + '@ai-sdk/anthropic@4.0.0(zod@4.1.13)': dependencies: - '@ai-sdk/provider': 3.0.10 - '@ai-sdk/provider-utils': 4.0.27(zod@4.1.13) + '@ai-sdk/provider': 4.0.0 + '@ai-sdk/provider-utils': 5.0.0(zod@4.1.13) zod: 4.1.13 - '@ai-sdk/gateway@3.0.119(zod@4.1.13)': + '@ai-sdk/gateway@4.0.2(zod@4.1.13)': dependencies: - '@ai-sdk/provider': 3.0.10 - '@ai-sdk/provider-utils': 4.0.27(zod@4.1.13) + '@ai-sdk/provider': 4.0.0 + '@ai-sdk/provider-utils': 5.0.0(zod@4.1.13) '@vercel/oidc': 3.2.0 zod: 4.1.13 @@ -8354,29 +8368,30 @@ snapshots: '@vercel/oidc': 3.2.0 zod: 4.1.13 - '@ai-sdk/google@3.0.79(zod@4.1.13)': + '@ai-sdk/google@4.0.0(zod@4.1.13)': dependencies: - '@ai-sdk/provider': 3.0.10 - '@ai-sdk/provider-utils': 4.0.27(zod@4.1.13) + '@ai-sdk/provider': 4.0.0 + '@ai-sdk/provider-utils': 5.0.0(zod@4.1.13) zod: 4.1.13 - '@ai-sdk/mcp@1.0.43(zod@4.1.13)': + '@ai-sdk/mcp@2.0.0(zod@4.1.13)': dependencies: - '@ai-sdk/provider': 3.0.10 - '@ai-sdk/provider-utils': 4.0.27(zod@4.1.13) + '@ai-sdk/provider': 4.0.0 + '@ai-sdk/provider-utils': 5.0.0(zod@4.1.13) pkce-challenge: 5.0.1 zod: 4.1.13 - '@ai-sdk/openai@3.0.65(zod@4.1.13)': + '@ai-sdk/openai@4.0.8(zod@4.1.13)': dependencies: - '@ai-sdk/provider': 3.0.10 - '@ai-sdk/provider-utils': 4.0.27(zod@4.1.13) + '@ai-sdk/provider': 4.0.2 + '@ai-sdk/provider-utils': 5.0.5(zod@4.1.13) zod: 4.1.13 - '@ai-sdk/provider-utils@4.0.27(zod@4.1.13)': + '@ai-sdk/provider-utils@5.0.0(zod@4.1.13)': dependencies: - '@ai-sdk/provider': 3.0.10 + '@ai-sdk/provider': 4.0.0 '@standard-schema/spec': 1.1.0 + '@workflow/serde': 4.1.0 eventsource-parser: 3.0.8 zod: 4.1.13 @@ -8389,11 +8404,19 @@ snapshots: undici: 7.29.1 zod: 4.1.13 + '@ai-sdk/provider-utils@5.0.5(zod@4.1.13)': + dependencies: + '@ai-sdk/provider': 4.0.2 + '@standard-schema/spec': 1.1.0 + '@workflow/serde': 4.1.0 + eventsource-parser: 3.0.8 + zod: 4.1.13 + '@ai-sdk/provider@1.1.3': dependencies: json-schema: 0.4.0 - '@ai-sdk/provider@3.0.10': + '@ai-sdk/provider@4.0.0': dependencies: json-schema: 0.4.0 @@ -8401,6 +8424,10 @@ snapshots: dependencies: json-schema: 0.4.0 + '@ai-sdk/provider@4.0.2': + dependencies: + json-schema: 0.4.0 + '@alloc/quick-lru@5.2.0': {} '@apify/consts@2.48.0': {} @@ -8855,10 +8882,10 @@ snapshots: dependencies: zod: 4.1.13 - '@composio/vercel@0.3.4(@composio/core@0.3.4(ws@8.18.3(bufferutil@4.0.9)(utf-8-validate@5.0.10))(zod@4.1.13))(ai@6.0.190(zod@4.1.13))': + '@composio/vercel@0.3.4(@composio/core@0.3.4(ws@8.18.3(bufferutil@4.0.9)(utf-8-validate@5.0.10))(zod@4.1.13))(ai@7.0.2(zod@4.1.13))': dependencies: '@composio/core': 0.3.4(ws@8.18.3(bufferutil@4.0.9)(utf-8-validate@5.0.10))(zod@4.1.13) - ai: 6.0.190(zod@4.1.13) + ai: 7.0.2(zod@4.1.13) '@crawlee/types@3.15.3': dependencies: @@ -11967,7 +11994,7 @@ snapshots: - supports-color - utf-8-validate - '@trigger.dev/sdk@4.4.3(ai@6.0.190(zod@4.1.13))(bufferutil@4.0.9)(utf-8-validate@5.0.10)(zod@4.1.13)': + '@trigger.dev/sdk@4.4.3(ai@7.0.2(zod@4.1.13))(bufferutil@4.0.9)(utf-8-validate@5.0.10)(zod@4.1.13)': dependencies: '@opentelemetry/api': 1.9.0 '@opentelemetry/semantic-conventions': 1.36.0 @@ -11983,7 +12010,7 @@ snapshots: ws: 8.18.3(bufferutil@4.0.9)(utf-8-validate@5.0.10) zod: 4.1.13 optionalDependencies: - ai: 6.0.190(zod@4.1.13) + ai: 7.0.2(zod@4.1.13) transitivePeerDependencies: - bufferutil - supports-color @@ -13371,14 +13398,6 @@ snapshots: dependencies: humanize-ms: 1.2.1 - ai@6.0.190(zod@4.1.13): - dependencies: - '@ai-sdk/gateway': 3.0.119(zod@4.1.13) - '@ai-sdk/provider': 3.0.10 - '@ai-sdk/provider-utils': 4.0.27(zod@4.1.13) - '@opentelemetry/api': 1.9.0 - zod: 4.1.13 - ai@7.0.105(zod@4.1.13): dependencies: '@ai-sdk/gateway': 4.0.85(zod@4.1.13) @@ -13386,6 +13405,13 @@ snapshots: '@ai-sdk/provider-utils': 5.0.43(zod@4.1.13) zod: 4.1.13 + ai@7.0.2(zod@4.1.13): + dependencies: + '@ai-sdk/gateway': 4.0.2(zod@4.1.13) + '@ai-sdk/provider': 4.0.0 + '@ai-sdk/provider-utils': 5.0.0(zod@4.1.13) + zod: 4.1.13 + ajv-formats@3.0.1(ajv@8.17.1): optionalDependencies: ajv: 8.17.1 diff --git a/scripts/application-registration-proposal/source-bindings.json b/scripts/application-registration-proposal/source-bindings.json index 6b92a2fcb..6925ddf89 100644 --- a/scripts/application-registration-proposal/source-bindings.json +++ b/scripts/application-registration-proposal/source-bindings.json @@ -6,8 +6,8 @@ "lib/auth/validateAuthContext.ts": "055ac2965db8487c8f67d74c549101d866968ed507d295498ed4485d62867c28", "lib/applications/applicationRegistrationSchema.ts": "5bfb55ded25eae323bea02b535d6fb010eec5b2a767b891a13b86e4c91427a30", "lib/applications/validateApplicationRegistration.ts": "b842cd312e0123a65ec1dd872c54474f77872b337ef5285ecedff1dad96ac0c6", - "package.json": "6129bd1116b3f3b3644c4560484daf2feafb57272e29f68cb5156b22ef1bbd50", - "pnpm-lock.yaml": "59d2629cd37287ad1bfd5e35589d0ed4c15c09d3c1965fff78aaba4a871487ee", + "package.json": "8ecf5abbdc3320c9f18e54a929b0b1ead97cabf5eb0811004bf55c5108a06489", + "pnpm-lock.yaml": "13613be49e4e4c5554dbfcf3ee62876c908b3aac107c707abfdd5349ac88ab4a", "tsconfig.json": "b32629dbc2af272f06db2eb3c5e6bd249183a72cec77481e624b0a4086c10d93", "lib/keys/getApiKeyDetails.ts": "68813ca17af04703ded1efc25d8c6864aaa1f7b9c297ddeadb44c6c10220c644", "lib/mcp/__tests__/verifyApiKeyExpiry.test.ts": "1b4b18f8147217734b9b1d89418a57ae23c968e6046109d072469b7735fdd1bc", diff --git a/scripts/application-registration-proposal/sql-composition/source-bindings.json b/scripts/application-registration-proposal/sql-composition/source-bindings.json index 9dd69f624..c96ac7c86 100644 --- a/scripts/application-registration-proposal/sql-composition/source-bindings.json +++ b/scripts/application-registration-proposal/sql-composition/source-bindings.json @@ -5,8 +5,8 @@ "lib/auth/validateAuthContext.ts": "055ac2965db8487c8f67d74c549101d866968ed507d295498ed4485d62867c28", "lib/applications/applicationRegistrationSchema.ts": "5bfb55ded25eae323bea02b535d6fb010eec5b2a767b891a13b86e4c91427a30", "lib/applications/validateApplicationRegistration.ts": "b842cd312e0123a65ec1dd872c54474f77872b337ef5285ecedff1dad96ac0c6", - "package.json": "6129bd1116b3f3b3644c4560484daf2feafb57272e29f68cb5156b22ef1bbd50", - "pnpm-lock.yaml": "59d2629cd37287ad1bfd5e35589d0ed4c15c09d3c1965fff78aaba4a871487ee", + "package.json": "8ecf5abbdc3320c9f18e54a929b0b1ead97cabf5eb0811004bf55c5108a06489", + "pnpm-lock.yaml": "13613be49e4e4c5554dbfcf3ee62876c908b3aac107c707abfdd5349ac88ab4a", "tsconfig.json": "b32629dbc2af272f06db2eb3c5e6bd249183a72cec77481e624b0a4086c10d93", "lib/keys/getApiKeyDetails.ts": "68813ca17af04703ded1efc25d8c6864aaa1f7b9c297ddeadb44c6c10220c644", "lib/mcp/__tests__/verifyApiKeyExpiry.test.ts": "1b4b18f8147217734b9b1d89418a57ae23c968e6046109d072469b7735fdd1bc", diff --git a/scripts/chat-fence-delete/vectors.json b/scripts/chat-fence-delete/vectors.json index f6c6b0410..45e8b98ef 100644 --- a/scripts/chat-fence-delete/vectors.json +++ b/scripts/chat-fence-delete/vectors.json @@ -4,7 +4,7 @@ { "request_id": "77777777-7777-4777-8777-777777777777", "expected_epoch": 0, - "input_hash": "97b9eec31a031d05f0f9eee3855ea857f342f420f8eca44c26780b7748490ee9", + "input_hash": "48761c5ac30084ff1bfed2979a158eff689470a15ff0f2ac5ea4199d0ea9a277", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -31,7 +31,7 @@ }, "executionSnapshot": { "id": "delete-0", - "digest": "16c3deac8991338626c56e27add73c802ec18f95d326f7e25114208d6324fcf8" + "digest": "2529013cd0e05fae50d0d2b55334a7991e3e74c9610868914b912965ec09f5e2" } }, "execution_snapshot": { @@ -48,6 +48,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -85,13 +86,13 @@ } } }, - "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"16c3deac8991338626c56e27add73c802ec18f95d326f7e25114208d6324fcf8\",\"id\":\"delete-0\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", - "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"delete-0\",\"requestId\":\"77777777-7777-4777-8777-777777777777\",\"sessionId\":\"session\"}" + "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"2529013cd0e05fae50d0d2b55334a7991e3e74c9610868914b912965ec09f5e2\",\"id\":\"delete-0\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", + "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"delete-0\",\"requestId\":\"77777777-7777-4777-8777-777777777777\",\"sessionId\":\"session\"}" }, { "request_id": "88888888-8888-4888-8888-888888888888", "expected_epoch": 2, - "input_hash": "9909a3947574987d0488b13fd5d1254303f8658e2e89b4a04358cecd196837c5", + "input_hash": "365e3f5f13ff3d947a06a8d2742c7856a52ec36fc1089f87f44b6e06b5dd4fa4", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -118,7 +119,7 @@ }, "executionSnapshot": { "id": "delete-1", - "digest": "bd6f23bb371ea634b84519e3515d2f96b18541ea8bc4ef2327c581766e6162dc" + "digest": "24ba279fb7f16b0fc612f2f936502e12524fdf11bf087e25b342000d064f8beb" } }, "execution_snapshot": { @@ -135,6 +136,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -172,8 +174,8 @@ } } }, - "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"bd6f23bb371ea634b84519e3515d2f96b18541ea8bc4ef2327c581766e6162dc\",\"id\":\"delete-1\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", - "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"delete-1\",\"requestId\":\"88888888-8888-4888-8888-888888888888\",\"sessionId\":\"session\"}" + "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"24ba279fb7f16b0fc612f2f936502e12524fdf11bf087e25b342000d064f8beb\",\"id\":\"delete-1\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", + "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"delete-1\",\"requestId\":\"88888888-8888-4888-8888-888888888888\",\"sessionId\":\"session\"}" } ], "commands": { diff --git a/scripts/chat-fence-edit/vectors.json b/scripts/chat-fence-edit/vectors.json index d9cd3954b..fd49ea354 100644 --- a/scripts/chat-fence-edit/vectors.json +++ b/scripts/chat-fence-edit/vectors.json @@ -4,7 +4,7 @@ "initial": { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "71acdefa8e3a92effd0291467252e6572358c4e67870e5c132de325f69841cec", + "input_hash": "db2e9511bb983e896faffdbf8e2366f6b86a6338af44689e32e2c5db6015b49b", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -61,7 +61,7 @@ }, "executionSnapshot": { "id": "original-success", - "digest": "8543a2e837dd8e78d88d642378c661cf7411c5f5d8dcb8e11b50fa86d2b65512" + "digest": "b7b2df2e87bdd789bcaced96661a0d1e5948bc8bb9ea8043e816633a8c49cea0" } }, "execution_snapshot": { @@ -78,6 +78,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -115,20 +116,20 @@ } } }, - "admission_canonical": "{\"chatId\":\"edited-success\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"8543a2e837dd8e78d88d642378c661cf7411c5f5d8dcb8e11b50fa86d2b65512\",\"id\":\"original-success\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"success/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"success/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"success/old-user\",\"parts\":[{\"text\":\"old\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"success/old-assistant\",\"parts\":[{\"text\":\"old answer\",\"type\":\"text\"}],\"role\":\"assistant\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-success\"}", - "execution_canonical": "{\"chatId\":\"edited-success\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"original-success\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-success\"}" + "admission_canonical": "{\"chatId\":\"edited-success\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"b7b2df2e87bdd789bcaced96661a0d1e5948bc8bb9ea8043e816633a8c49cea0\",\"id\":\"original-success\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"success/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"success/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"success/old-user\",\"parts\":[{\"text\":\"old\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"success/old-assistant\",\"parts\":[{\"text\":\"old answer\",\"type\":\"text\"}],\"role\":\"assistant\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-success\"}", + "execution_canonical": "{\"chatId\":\"edited-success\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"original-success\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-success\"}" }, "prepared": { "admission": { "action": "admit", "payload": { - "admission_canonical": "{\"chatId\":\"edited-success\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"90cbf801b236d5cae7ab572293b65a604f77f75edc891eab40b5e0b2829d7019\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"success/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"success/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"success/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"edited\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-success\"}", + "admission_canonical": "{\"chatId\":\"edited-success\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"64c1ff194002dd8ce5fedce22180d1476165710dfd7daa2075fe0339cd71b66f\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"success/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"success/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"success/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"edited\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-success\"}", "admission_envelope": { "chatId": "edited-success", "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", "executionSnapshot": { - "digest": "90cbf801b236d5cae7ab572293b65a604f77f75edc891eab40b5e0b2829d7019", + "digest": "64c1ff194002dd8ce5fedce22180d1476165710dfd7daa2075fe0339cd71b66f", "id": "edited-snapshot" }, "expectedEpoch": 2, @@ -175,7 +176,7 @@ }, "sessionId": "session-success" }, - "execution_canonical": "{\"chatId\":\"edited-success\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-success\"}", + "execution_canonical": "{\"chatId\":\"edited-success\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-success\"}", "execution_snapshot": { "chatId": "edited-success", "content": { @@ -219,7 +220,8 @@ "workingDirectory": "/workspace" }, "sessionTitle": null, - "skills": [] + "skills": [], + "streamProtocol": "unmarked-v1" }, "contractVersion": "chat-execution/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -228,7 +230,7 @@ "sessionId": "session-success" }, "expected_epoch": 2, - "input_hash": "61d8a4c23264639bfd1bb977652e7f191bb0f4d27cd2413e3830796b4b3a8a52", + "input_hash": "0ea37bfb32b621a31d90a414380ad450427ab0ceac98d885197536156107244f", "request_id": "66666666-6666-4666-8666-666666666666" } }, @@ -245,13 +247,13 @@ "admission": { "action": "admit", "payload": { - "admission_canonical": "{\"chatId\":\"edited-success\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"90cbf801b236d5cae7ab572293b65a604f77f75edc891eab40b5e0b2829d7019\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"success/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"success/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"success/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"changed-content-same-identity\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-success\"}", + "admission_canonical": "{\"chatId\":\"edited-success\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"64c1ff194002dd8ce5fedce22180d1476165710dfd7daa2075fe0339cd71b66f\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"success/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"success/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"success/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"changed-content-same-identity\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-success\"}", "admission_envelope": { "chatId": "edited-success", "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", "executionSnapshot": { - "digest": "90cbf801b236d5cae7ab572293b65a604f77f75edc891eab40b5e0b2829d7019", + "digest": "64c1ff194002dd8ce5fedce22180d1476165710dfd7daa2075fe0339cd71b66f", "id": "edited-snapshot" }, "expectedEpoch": 2, @@ -298,7 +300,7 @@ }, "sessionId": "session-success" }, - "execution_canonical": "{\"chatId\":\"edited-success\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-success\"}", + "execution_canonical": "{\"chatId\":\"edited-success\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-success\"}", "execution_snapshot": { "chatId": "edited-success", "content": { @@ -342,7 +344,8 @@ "workingDirectory": "/workspace" }, "sessionTitle": null, - "skills": [] + "skills": [], + "streamProtocol": "unmarked-v1" }, "contractVersion": "chat-execution/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -351,7 +354,7 @@ "sessionId": "session-success" }, "expected_epoch": 2, - "input_hash": "aa50b715562a45a932d575bc6623aad20f7881f67b7b44b85be9b83bac24475d", + "input_hash": "060a6f17985c24d1b7f8bcc78d1b6c470600130409fdaa5eb7053efc4539319c", "request_id": "66666666-6666-4666-8666-666666666666" } }, @@ -387,7 +390,7 @@ "initial": { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "641559616b79385c8f3831ba84b33f78e0ededd9d7605c4e613c00a86c145073", + "input_hash": "00d8cc47ac056924c94a29c0e336c2db2dd897213ee9f3f9969e5a4b8bf55ced", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -444,7 +447,7 @@ }, "executionSnapshot": { "id": "original-newer-owner", - "digest": "c7f434f99fd5b1b9ccb1aac0e874f1726d686572af53940ed6bb34b6522e66d9" + "digest": "20c812c4e12819d19bea2e1604b944d321812c0f694fed0a8152ee98a2c78b1b" } }, "execution_snapshot": { @@ -461,6 +464,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -498,20 +502,20 @@ } } }, - "admission_canonical": "{\"chatId\":\"edited-newer-owner\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"c7f434f99fd5b1b9ccb1aac0e874f1726d686572af53940ed6bb34b6522e66d9\",\"id\":\"original-newer-owner\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"newer-owner/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"newer-owner/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"newer-owner/old-user\",\"parts\":[{\"text\":\"old\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"newer-owner/old-assistant\",\"parts\":[{\"text\":\"old answer\",\"type\":\"text\"}],\"role\":\"assistant\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-newer-owner\"}", - "execution_canonical": "{\"chatId\":\"edited-newer-owner\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"original-newer-owner\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-newer-owner\"}" + "admission_canonical": "{\"chatId\":\"edited-newer-owner\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"20c812c4e12819d19bea2e1604b944d321812c0f694fed0a8152ee98a2c78b1b\",\"id\":\"original-newer-owner\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"newer-owner/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"newer-owner/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"newer-owner/old-user\",\"parts\":[{\"text\":\"old\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"newer-owner/old-assistant\",\"parts\":[{\"text\":\"old answer\",\"type\":\"text\"}],\"role\":\"assistant\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-newer-owner\"}", + "execution_canonical": "{\"chatId\":\"edited-newer-owner\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"original-newer-owner\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-newer-owner\"}" }, "prepared": { "admission": { "action": "admit", "payload": { - "admission_canonical": "{\"chatId\":\"edited-newer-owner\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"17f03111138ef9ef6990b1ca0855f5095bf5dc4ab0a92f2af641b132ac9e9fad\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"newer-owner/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"newer-owner/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"newer-owner/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"edited\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-newer-owner\"}", + "admission_canonical": "{\"chatId\":\"edited-newer-owner\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"e1e57db476a02603517e8c0312732b7ffbe5fcb780783fc20a2ce3ad6411412a\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"newer-owner/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"newer-owner/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"newer-owner/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"edited\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-newer-owner\"}", "admission_envelope": { "chatId": "edited-newer-owner", "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", "executionSnapshot": { - "digest": "17f03111138ef9ef6990b1ca0855f5095bf5dc4ab0a92f2af641b132ac9e9fad", + "digest": "e1e57db476a02603517e8c0312732b7ffbe5fcb780783fc20a2ce3ad6411412a", "id": "edited-snapshot" }, "expectedEpoch": 2, @@ -558,7 +562,7 @@ }, "sessionId": "session-newer-owner" }, - "execution_canonical": "{\"chatId\":\"edited-newer-owner\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-newer-owner\"}", + "execution_canonical": "{\"chatId\":\"edited-newer-owner\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-newer-owner\"}", "execution_snapshot": { "chatId": "edited-newer-owner", "content": { @@ -602,7 +606,8 @@ "workingDirectory": "/workspace" }, "sessionTitle": null, - "skills": [] + "skills": [], + "streamProtocol": "unmarked-v1" }, "contractVersion": "chat-execution/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -611,7 +616,7 @@ "sessionId": "session-newer-owner" }, "expected_epoch": 2, - "input_hash": "23802908f4fd5668406d79e303c5bc31cee6d534673129d0656ab5e81bbc3ec7", + "input_hash": "35499dcd20ac78248b3482c8a3fd3c745076fe220411e946b09ad62dc05444b9", "request_id": "66666666-6666-4666-8666-666666666666" } }, @@ -628,13 +633,13 @@ "admission": { "action": "admit", "payload": { - "admission_canonical": "{\"chatId\":\"edited-newer-owner\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"17f03111138ef9ef6990b1ca0855f5095bf5dc4ab0a92f2af641b132ac9e9fad\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"newer-owner/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"newer-owner/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"newer-owner/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"changed-content-same-identity\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-newer-owner\"}", + "admission_canonical": "{\"chatId\":\"edited-newer-owner\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"e1e57db476a02603517e8c0312732b7ffbe5fcb780783fc20a2ce3ad6411412a\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"newer-owner/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"newer-owner/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"newer-owner/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"changed-content-same-identity\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-newer-owner\"}", "admission_envelope": { "chatId": "edited-newer-owner", "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", "executionSnapshot": { - "digest": "17f03111138ef9ef6990b1ca0855f5095bf5dc4ab0a92f2af641b132ac9e9fad", + "digest": "e1e57db476a02603517e8c0312732b7ffbe5fcb780783fc20a2ce3ad6411412a", "id": "edited-snapshot" }, "expectedEpoch": 2, @@ -681,7 +686,7 @@ }, "sessionId": "session-newer-owner" }, - "execution_canonical": "{\"chatId\":\"edited-newer-owner\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-newer-owner\"}", + "execution_canonical": "{\"chatId\":\"edited-newer-owner\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-newer-owner\"}", "execution_snapshot": { "chatId": "edited-newer-owner", "content": { @@ -725,7 +730,8 @@ "workingDirectory": "/workspace" }, "sessionTitle": null, - "skills": [] + "skills": [], + "streamProtocol": "unmarked-v1" }, "contractVersion": "chat-execution/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -734,7 +740,7 @@ "sessionId": "session-newer-owner" }, "expected_epoch": 2, - "input_hash": "93780ab6180ccb80d1c60913988832158f3e8deb56ff3b39abcca62d61282d05", + "input_hash": "605df57107d127dedf59b28c14a2273be025b8b5da6b702727fc15083e5182f9", "request_id": "66666666-6666-4666-8666-666666666666" } }, @@ -770,7 +776,7 @@ "initial": { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "737ac1bb5d9b7c914776c3a75e60f48e0063c6313a1b185de9af8529def25b77", + "input_hash": "d86e134571806d70ec5470ef4d407213534a1fb291f34329168cc16e3792936a", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -827,7 +833,7 @@ }, "executionSnapshot": { "id": "original-lost-ack", - "digest": "0802593b918330a6791dbce8073caea7de722ef726ea7cf4bd97f5a90548c5de" + "digest": "61940111022aefc55f0aaf6b72c4423428b0a8f5e6e06c50300ad953a74cc7c9" } }, "execution_snapshot": { @@ -844,6 +850,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -881,20 +888,20 @@ } } }, - "admission_canonical": "{\"chatId\":\"edited-lost-ack\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"0802593b918330a6791dbce8073caea7de722ef726ea7cf4bd97f5a90548c5de\",\"id\":\"original-lost-ack\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"lost-ack/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"lost-ack/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"lost-ack/old-user\",\"parts\":[{\"text\":\"old\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"lost-ack/old-assistant\",\"parts\":[{\"text\":\"old answer\",\"type\":\"text\"}],\"role\":\"assistant\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-lost-ack\"}", - "execution_canonical": "{\"chatId\":\"edited-lost-ack\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"original-lost-ack\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-lost-ack\"}" + "admission_canonical": "{\"chatId\":\"edited-lost-ack\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"61940111022aefc55f0aaf6b72c4423428b0a8f5e6e06c50300ad953a74cc7c9\",\"id\":\"original-lost-ack\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"lost-ack/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"lost-ack/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"lost-ack/old-user\",\"parts\":[{\"text\":\"old\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"lost-ack/old-assistant\",\"parts\":[{\"text\":\"old answer\",\"type\":\"text\"}],\"role\":\"assistant\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-lost-ack\"}", + "execution_canonical": "{\"chatId\":\"edited-lost-ack\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"original-lost-ack\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-lost-ack\"}" }, "prepared": { "admission": { "action": "admit", "payload": { - "admission_canonical": "{\"chatId\":\"edited-lost-ack\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"8c9542e8f382396eccabe1d2b43f7af56f4d5f88bcbf05084711fdb02b8fafe3\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"lost-ack/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"lost-ack/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"lost-ack/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"edited\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-lost-ack\"}", + "admission_canonical": "{\"chatId\":\"edited-lost-ack\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"c1949f071bc64158b303f72e252e2dcce43d0d6935a8270064f9caa70f0278cd\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"lost-ack/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"lost-ack/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"lost-ack/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"edited\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-lost-ack\"}", "admission_envelope": { "chatId": "edited-lost-ack", "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", "executionSnapshot": { - "digest": "8c9542e8f382396eccabe1d2b43f7af56f4d5f88bcbf05084711fdb02b8fafe3", + "digest": "c1949f071bc64158b303f72e252e2dcce43d0d6935a8270064f9caa70f0278cd", "id": "edited-snapshot" }, "expectedEpoch": 2, @@ -941,7 +948,7 @@ }, "sessionId": "session-lost-ack" }, - "execution_canonical": "{\"chatId\":\"edited-lost-ack\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-lost-ack\"}", + "execution_canonical": "{\"chatId\":\"edited-lost-ack\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-lost-ack\"}", "execution_snapshot": { "chatId": "edited-lost-ack", "content": { @@ -985,7 +992,8 @@ "workingDirectory": "/workspace" }, "sessionTitle": null, - "skills": [] + "skills": [], + "streamProtocol": "unmarked-v1" }, "contractVersion": "chat-execution/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -994,7 +1002,7 @@ "sessionId": "session-lost-ack" }, "expected_epoch": 2, - "input_hash": "f317c4033bdba0eaa82a94c4f5b517af91c8549c9645993c847720eed4ab7d09", + "input_hash": "71fd0835a500f1904a5d6dd973348fbd9ead9c9b2c4ed4fac9d50958d976831b", "request_id": "66666666-6666-4666-8666-666666666666" } }, @@ -1011,13 +1019,13 @@ "admission": { "action": "admit", "payload": { - "admission_canonical": "{\"chatId\":\"edited-lost-ack\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"8c9542e8f382396eccabe1d2b43f7af56f4d5f88bcbf05084711fdb02b8fafe3\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"lost-ack/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"lost-ack/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"lost-ack/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"changed-content-same-identity\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-lost-ack\"}", + "admission_canonical": "{\"chatId\":\"edited-lost-ack\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"c1949f071bc64158b303f72e252e2dcce43d0d6935a8270064f9caa70f0278cd\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"lost-ack/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"lost-ack/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"lost-ack/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"changed-content-same-identity\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-lost-ack\"}", "admission_envelope": { "chatId": "edited-lost-ack", "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", "executionSnapshot": { - "digest": "8c9542e8f382396eccabe1d2b43f7af56f4d5f88bcbf05084711fdb02b8fafe3", + "digest": "c1949f071bc64158b303f72e252e2dcce43d0d6935a8270064f9caa70f0278cd", "id": "edited-snapshot" }, "expectedEpoch": 2, @@ -1064,7 +1072,7 @@ }, "sessionId": "session-lost-ack" }, - "execution_canonical": "{\"chatId\":\"edited-lost-ack\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-lost-ack\"}", + "execution_canonical": "{\"chatId\":\"edited-lost-ack\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-lost-ack\"}", "execution_snapshot": { "chatId": "edited-lost-ack", "content": { @@ -1108,7 +1116,8 @@ "workingDirectory": "/workspace" }, "sessionTitle": null, - "skills": [] + "skills": [], + "streamProtocol": "unmarked-v1" }, "contractVersion": "chat-execution/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -1117,7 +1126,7 @@ "sessionId": "session-lost-ack" }, "expected_epoch": 2, - "input_hash": "461e888a65ef67ac464797dc001a98ec48102a6f00fa73132c6429462e69c227", + "input_hash": "b8b42a3ed66e6ec31e48f01d4121180c57ccd8c75c4a2813ea51113f7b1af943", "request_id": "66666666-6666-4666-8666-666666666666" } }, @@ -1153,7 +1162,7 @@ "initial": { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "951d2ccb35721bb153d6a8a24bea2394d28e6df9887b6d6b1551074c987b9c1a", + "input_hash": "f389dd6c1bde043f29f50deec07088dd0f9c027788953984cea0106e37b7692c", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -1210,7 +1219,7 @@ }, "executionSnapshot": { "id": "original-unseen-collision", - "digest": "5712e7a7fda12a127761c5f26aee4e1d23ec776d37a463d53d4eb2497846db0c" + "digest": "6f5258277aeeb864c4454c6592e3da9a853e961d49cabced24bece1bc40156d4" } }, "execution_snapshot": { @@ -1227,6 +1236,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -1264,20 +1274,20 @@ } } }, - "admission_canonical": "{\"chatId\":\"edited-unseen-collision\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"5712e7a7fda12a127761c5f26aee4e1d23ec776d37a463d53d4eb2497846db0c\",\"id\":\"original-unseen-collision\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"unseen-collision/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"unseen-collision/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"unseen-collision/old-user\",\"parts\":[{\"text\":\"old\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"unseen-collision/old-assistant\",\"parts\":[{\"text\":\"old answer\",\"type\":\"text\"}],\"role\":\"assistant\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-unseen-collision\"}", - "execution_canonical": "{\"chatId\":\"edited-unseen-collision\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"original-unseen-collision\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-unseen-collision\"}" + "admission_canonical": "{\"chatId\":\"edited-unseen-collision\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"6f5258277aeeb864c4454c6592e3da9a853e961d49cabced24bece1bc40156d4\",\"id\":\"original-unseen-collision\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"unseen-collision/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"unseen-collision/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"unseen-collision/old-user\",\"parts\":[{\"text\":\"old\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"unseen-collision/old-assistant\",\"parts\":[{\"text\":\"old answer\",\"type\":\"text\"}],\"role\":\"assistant\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-unseen-collision\"}", + "execution_canonical": "{\"chatId\":\"edited-unseen-collision\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"original-unseen-collision\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-unseen-collision\"}" }, "prepared": { "admission": { "action": "admit", "payload": { - "admission_canonical": "{\"chatId\":\"edited-unseen-collision\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"5fa55fd399ef2339983587412ed2b22137ff35e168c1e89bb4d6f3f772ec560a\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"unseen-collision/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"unseen-collision/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"unseen-collision/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"edited\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-unseen-collision\"}", + "admission_canonical": "{\"chatId\":\"edited-unseen-collision\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"e4cc763f8d4ff4858537d5521f1d2dde0ac115191a90b251c93f1ef9c7f9df61\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"unseen-collision/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"unseen-collision/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"unseen-collision/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"edited\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-unseen-collision\"}", "admission_envelope": { "chatId": "edited-unseen-collision", "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", "executionSnapshot": { - "digest": "5fa55fd399ef2339983587412ed2b22137ff35e168c1e89bb4d6f3f772ec560a", + "digest": "e4cc763f8d4ff4858537d5521f1d2dde0ac115191a90b251c93f1ef9c7f9df61", "id": "edited-snapshot" }, "expectedEpoch": 2, @@ -1324,7 +1334,7 @@ }, "sessionId": "session-unseen-collision" }, - "execution_canonical": "{\"chatId\":\"edited-unseen-collision\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-unseen-collision\"}", + "execution_canonical": "{\"chatId\":\"edited-unseen-collision\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-unseen-collision\"}", "execution_snapshot": { "chatId": "edited-unseen-collision", "content": { @@ -1368,7 +1378,8 @@ "workingDirectory": "/workspace" }, "sessionTitle": null, - "skills": [] + "skills": [], + "streamProtocol": "unmarked-v1" }, "contractVersion": "chat-execution/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -1377,7 +1388,7 @@ "sessionId": "session-unseen-collision" }, "expected_epoch": 2, - "input_hash": "9815f7bbdeec645017fdb0563d0b1b11d487f4be0a9152f01d471604055e5454", + "input_hash": "9d46791c8f8b9ca9d1a90f8ef928bb658b4128eb2265f6377f3a9b1fcb99a8bb", "request_id": "66666666-6666-4666-8666-666666666666" } }, @@ -1394,13 +1405,13 @@ "admission": { "action": "admit", "payload": { - "admission_canonical": "{\"chatId\":\"edited-unseen-collision\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"5fa55fd399ef2339983587412ed2b22137ff35e168c1e89bb4d6f3f772ec560a\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"unseen-collision/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"unseen-collision/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"unseen-collision/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"changed-content-same-identity\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-unseen-collision\"}", + "admission_canonical": "{\"chatId\":\"edited-unseen-collision\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"e4cc763f8d4ff4858537d5521f1d2dde0ac115191a90b251c93f1ef9c7f9df61\",\"id\":\"edited-snapshot\"},\"expectedEpoch\":2,\"messages\":[{\"id\":\"unseen-collision/prefix-user\",\"parts\":[{\"text\":\"prefix\",\"type\":\"text\"}],\"role\":\"user\"},{\"id\":\"unseen-collision/prefix-assistant\",\"parts\":[{\"text\":\"prefix answer\",\"type\":\"text\"}],\"role\":\"assistant\"},{\"id\":\"unseen-collision/fresh-edited-user\",\"metadata\":{\"origin\":\"edit\"},\"parts\":[{\"text\":\"changed-content-same-identity\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-unseen-collision\"}", "admission_envelope": { "chatId": "edited-unseen-collision", "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", "executionSnapshot": { - "digest": "5fa55fd399ef2339983587412ed2b22137ff35e168c1e89bb4d6f3f772ec560a", + "digest": "e4cc763f8d4ff4858537d5521f1d2dde0ac115191a90b251c93f1ef9c7f9df61", "id": "edited-snapshot" }, "expectedEpoch": 2, @@ -1447,7 +1458,7 @@ }, "sessionId": "session-unseen-collision" }, - "execution_canonical": "{\"chatId\":\"edited-unseen-collision\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-unseen-collision\"}", + "execution_canonical": "{\"chatId\":\"edited-unseen-collision\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"edited-snapshot\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session-unseen-collision\"}", "execution_snapshot": { "chatId": "edited-unseen-collision", "content": { @@ -1491,7 +1502,8 @@ "workingDirectory": "/workspace" }, "sessionTitle": null, - "skills": [] + "skills": [], + "streamProtocol": "unmarked-v1" }, "contractVersion": "chat-execution/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -1500,7 +1512,7 @@ "sessionId": "session-unseen-collision" }, "expected_epoch": 2, - "input_hash": "a65f008b31fc208f5e6275f2a54f859e5e49c4b9bb4a588f12e13fba251012be", + "input_hash": "397bd16cf485b85fe0aad1d062cad8cdb784424390cbb45d914b379c7b6902d6", "request_id": "66666666-6666-4666-8666-666666666666" } }, diff --git a/scripts/chat-fence-fixture/golden-vectors.json b/scripts/chat-fence-fixture/golden-vectors.json index 792725d0a..51845812c 100644 --- a/scripts/chat-fence-fixture/golden-vectors.json +++ b/scripts/chat-fence-fixture/golden-vectors.json @@ -4,7 +4,7 @@ "payload": { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "4131368d94dfc04108e5cb11d9996e2a51e2d0068cdf8c0776843a87dcc9ee73", + "input_hash": "ad81fd714f419856a92b417edc8b45d212c937c1976d97c52ec0b5a3e5cd46a6", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -37,7 +37,7 @@ }, "executionSnapshot": { "id": "snapshot-floats", - "digest": "971bec09a45d71afdcfefdaa555d711020faa93c3155f3373c858edc1dd5b7fd" + "digest": "5b725cd23d3dd48ee0ed521462d5a794b09f3b61acd77ad62852fb96b20e326e" } }, "execution_snapshot": { @@ -54,6 +54,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -91,8 +92,8 @@ } } }, - "admission_canonical": "{\"chatId\":\"golden-floats\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"971bec09a45d71afdcfefdaa555d711020faa93c3155f3373c858edc1dd5b7fd\",\"id\":\"snapshot-floats\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"u1\",\"parts\":[{\"data\":[0.1,1e-7,1.2345678901234567,0,0.000001],\"type\":\"data-synthetic\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-floats\"}", - "execution_canonical": "{\"chatId\":\"golden-floats\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"snapshot-floats\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-floats\"}" + "admission_canonical": "{\"chatId\":\"golden-floats\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"5b725cd23d3dd48ee0ed521462d5a794b09f3b61acd77ad62852fb96b20e326e\",\"id\":\"snapshot-floats\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"u1\",\"parts\":[{\"data\":[0.1,1e-7,1.2345678901234567,0,0.000001],\"type\":\"data-synthetic\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-floats\"}", + "execution_canonical": "{\"chatId\":\"golden-floats\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"snapshot-floats\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-floats\"}" } }, { @@ -100,7 +101,7 @@ "payload": { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "83b05ed944bf812d34b23bc1ef44ca85535b37259f6bffbfc0bbe84957e9ad05", + "input_hash": "c922b5a6aa3573d6ff9aa87e706f49091a4e5924c32e8c8038f6ea77d16e0811", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -131,7 +132,7 @@ }, "executionSnapshot": { "id": "snapshot-numeric-keys", - "digest": "6dade0a26a83dd252d25540589ddac29e7db2c2d52fc0481676c8406c1f12c91" + "digest": "3b1b9fbddc93778a3b468aa268f6214a658ff635ee8e82c2cbff61af244bc5aa" } }, "execution_snapshot": { @@ -148,6 +149,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -185,8 +187,8 @@ } } }, - "admission_canonical": "{\"chatId\":\"golden-numeric-keys\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"6dade0a26a83dd252d25540589ddac29e7db2c2d52fc0481676c8406c1f12c91\",\"id\":\"snapshot-numeric-keys\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"u1\",\"parts\":[{\"data\":{\"1\":\"one\",\"10\":\"ten\",\"2\":\"two\"},\"type\":\"data-synthetic\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-numeric-keys\"}", - "execution_canonical": "{\"chatId\":\"golden-numeric-keys\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"snapshot-numeric-keys\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-numeric-keys\"}" + "admission_canonical": "{\"chatId\":\"golden-numeric-keys\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"3b1b9fbddc93778a3b468aa268f6214a658ff635ee8e82c2cbff61af244bc5aa\",\"id\":\"snapshot-numeric-keys\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"u1\",\"parts\":[{\"data\":{\"1\":\"one\",\"10\":\"ten\",\"2\":\"two\"},\"type\":\"data-synthetic\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-numeric-keys\"}", + "execution_canonical": "{\"chatId\":\"golden-numeric-keys\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"snapshot-numeric-keys\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-numeric-keys\"}" } }, { @@ -194,7 +196,7 @@ "payload": { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "8cec6f8b9d177f2c31614ba65031d1f95e0f108eaa09af3b0f7306170fb863e9", + "input_hash": "ecbee5d289d95a619b0c428754ac2e1df25377323aed1b65d09c81570302c93f", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -224,7 +226,7 @@ }, "executionSnapshot": { "id": "snapshot-utf16-key-order", - "digest": "dbdad73036a3d7605d5b5618e160bafa31dc821b7d2b30818bf1e91d538c5c8b" + "digest": "d0292849e9c7d925c4b8c896920da55d45ad2f0f07ea6507d64dfde9eb9c8783" } }, "execution_snapshot": { @@ -241,6 +243,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -278,8 +281,8 @@ } } }, - "admission_canonical": "{\"chatId\":\"golden-utf16-key-order\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"dbdad73036a3d7605d5b5618e160bafa31dc821b7d2b30818bf1e91d538c5c8b\",\"id\":\"snapshot-utf16-key-order\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"u1\",\"parts\":[{\"data\":{\"😀\":\"non-BMP\",\"\":\"BMP\"},\"type\":\"data-synthetic\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-utf16-key-order\"}", - "execution_canonical": "{\"chatId\":\"golden-utf16-key-order\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"snapshot-utf16-key-order\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-utf16-key-order\"}" + "admission_canonical": "{\"chatId\":\"golden-utf16-key-order\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"d0292849e9c7d925c4b8c896920da55d45ad2f0f07ea6507d64dfde9eb9c8783\",\"id\":\"snapshot-utf16-key-order\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"u1\",\"parts\":[{\"data\":{\"😀\":\"non-BMP\",\"\":\"BMP\"},\"type\":\"data-synthetic\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-utf16-key-order\"}", + "execution_canonical": "{\"chatId\":\"golden-utf16-key-order\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"snapshot-utf16-key-order\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-utf16-key-order\"}" } }, { @@ -287,7 +290,7 @@ "payload": { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "a7fe257e5bef530e95e3ca55dd26455e7a3c689eccfb07eebc7f443dff7b77e0", + "input_hash": "6f834c79b09f302271623f5003a1645f0a29f92fbd80393644ea89a7e9594189", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -318,7 +321,7 @@ }, "executionSnapshot": { "id": "snapshot-normalization", - "digest": "1a2feaeb72ad6b1d8176086436005d689d03e2e3ab2ded7b79581dd3d71d1c2b" + "digest": "90f4626855c312349aefb0a5cf9786e3a5fca08bdaafc2b072e3d707e7689f42" } }, "execution_snapshot": { @@ -335,6 +338,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -372,8 +376,8 @@ } } }, - "admission_canonical": "{\"chatId\":\"golden-normalization\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"1a2feaeb72ad6b1d8176086436005d689d03e2e3ab2ded7b79581dd3d71d1c2b\",\"id\":\"snapshot-normalization\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"u1\",\"parts\":[{\"data\":{\"composed\":\"é\",\"decomposed\":\"é\",\"pair\":\"😀\"},\"type\":\"data-synthetic\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-normalization\"}", - "execution_canonical": "{\"chatId\":\"golden-normalization\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"snapshot-normalization\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-normalization\"}" + "admission_canonical": "{\"chatId\":\"golden-normalization\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"90f4626855c312349aefb0a5cf9786e3a5fca08bdaafc2b072e3d707e7689f42\",\"id\":\"snapshot-normalization\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"u1\",\"parts\":[{\"data\":{\"composed\":\"é\",\"decomposed\":\"é\",\"pair\":\"😀\"},\"type\":\"data-synthetic\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session-normalization\"}", + "execution_canonical": "{\"chatId\":\"golden-normalization\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"snapshot-normalization\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session-normalization\"}" } } ] diff --git a/scripts/chat-fence-fixture/persistence-vectors.json b/scripts/chat-fence-fixture/persistence-vectors.json index da7fca1f0..24208b88f 100644 --- a/scripts/chat-fence-fixture/persistence-vectors.json +++ b/scripts/chat-fence-fixture/persistence-vectors.json @@ -4,7 +4,7 @@ { "request_id": "22222222-2222-4222-8222-222222222222", "expected_epoch": 0, - "input_hash": "6f7b32cc047392658b8d441b97c5bc249a95eba872c844e21c63cd58407a8ab1", + "input_hash": "041dc38b0c784604d6bf1f451ba694f6bc5468aaccd9ba8e2ef5940e7eeb37be", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -31,7 +31,7 @@ }, "executionSnapshot": { "id": "persistence-0", - "digest": "f25dc0ad169a6b40e988dcd6978ff6111732b1f7d2cd9db5da4d6c086d936477" + "digest": "c8df8db0952ebb065ee2f5cea7976e64a8072a7b21f77a755cff4860ff42ba66" } }, "execution_snapshot": { @@ -48,6 +48,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -85,13 +86,13 @@ } } }, - "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"f25dc0ad169a6b40e988dcd6978ff6111732b1f7d2cd9db5da4d6c086d936477\",\"id\":\"persistence-0\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", - "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"persistence-0\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session\"}" + "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"c8df8db0952ebb065ee2f5cea7976e64a8072a7b21f77a755cff4860ff42ba66\",\"id\":\"persistence-0\"},\"expectedEpoch\":0,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", + "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"persistence-0\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"sessionId\":\"session\"}" }, { "request_id": "55555555-5555-4555-8555-555555555555", "expected_epoch": 1, - "input_hash": "25f13b74df873042fa5028031edf9c6e47bcf535f5c314fbe325eaef172bf84c", + "input_hash": "b4711e058050bdb26ef15594ff301960ee8c2c8c2702ca2bee4d7533aa7922eb", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -118,7 +119,7 @@ }, "executionSnapshot": { "id": "persistence-1", - "digest": "a3d2179fa3891637dbb1f931793d39cab35fbf8612d97a10ad48a864af858388" + "digest": "93465975d23085b3d99bf44e73faac8662a385987a922f600b113b9cc7831d95" } }, "execution_snapshot": { @@ -135,6 +136,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -172,13 +174,13 @@ } } }, - "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"a3d2179fa3891637dbb1f931793d39cab35fbf8612d97a10ad48a864af858388\",\"id\":\"persistence-1\"},\"expectedEpoch\":1,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", - "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"persistence-1\",\"requestId\":\"55555555-5555-4555-8555-555555555555\",\"sessionId\":\"session\"}" + "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"93465975d23085b3d99bf44e73faac8662a385987a922f600b113b9cc7831d95\",\"id\":\"persistence-1\"},\"expectedEpoch\":1,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", + "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"persistence-1\",\"requestId\":\"55555555-5555-4555-8555-555555555555\",\"sessionId\":\"session\"}" }, { "request_id": "66666666-6666-4666-8666-666666666666", "expected_epoch": 3, - "input_hash": "de84aae1e7509affaed1d557e934253e59142debc7555d8889b44f3afc0f1c53", + "input_hash": "bc1fa300b7961543d9ea0f8d3a3aa5d0aaa0334ae79ed1f851cde4db289a3e55", "admission_envelope": { "contractVersion": "chat-admission/v1", "effectiveAccountId": "11111111-1111-4111-8111-111111111111", @@ -205,7 +207,7 @@ }, "executionSnapshot": { "id": "persistence-2", - "digest": "eb10183fd115553fe1c73b683f3137285d3ab7527f9f7d8cf3357a593fff1952" + "digest": "6cafef6e067fcf5bf865f0ddb309e6b20ccfbdfaaa47e72aafb67ec9078a1b33" } }, "execution_snapshot": { @@ -222,6 +224,7 @@ "interactive": true, "devSurface": null }, + "streamProtocol": "unmarked-v1", "sessionTitle": null, "repoOwner": null, "repoName": null, @@ -259,8 +262,8 @@ } } }, - "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"eb10183fd115553fe1c73b683f3137285d3ab7527f9f7d8cf3357a593fff1952\",\"id\":\"persistence-2\"},\"expectedEpoch\":3,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", - "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[]},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"persistence-2\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session\"}" + "admission_canonical": "{\"chatId\":\"chat\",\"contractVersion\":\"chat-admission/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"executionSnapshot\":{\"digest\":\"6cafef6e067fcf5bf865f0ddb309e6b20ccfbdfaaa47e72aafb67ec9078a1b33\",\"id\":\"persistence-2\"},\"expectedEpoch\":3,\"messages\":[{\"id\":\"user-1\",\"parts\":[{\"text\":\"hello\",\"type\":\"text\"}],\"role\":\"user\"}],\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"sessionId\":\"session\"}", + "execution_canonical": "{\"chatId\":\"chat\",\"content\":{\"credentialPolicy\":{\"authorization\":{\"basis\":\"self\",\"permissions\":[\"chat:execute\"],\"version\":\"synthetic/v1\"},\"credentialIntentId\":\"33333333-3333-4333-8333-333333333333\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"organizationId\":null,\"policyVersion\":\"chat-credential/v1\",\"principal\":{\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"keyId\":\"44444444-4444-4444-8444-444444444444\",\"mechanism\":\"recoup_api_key\"},\"recovery\":\"reauthenticate_proven_never_dispatched\"},\"options\":{\"artistId\":null,\"devSurface\":null,\"interactive\":true,\"modelId\":\"synthetic-model\"},\"recoupOrgId\":null,\"repoName\":null,\"repoOwner\":null,\"sandbox\":{\"currentBranch\":null,\"state\":{\"expiresAt\":null,\"sandboxId\":null,\"sandboxName\":\"synthetic-sandbox\",\"snapshotId\":null,\"source\":null},\"workingDirectory\":\"/workspace\"},\"sessionTitle\":null,\"skills\":[],\"streamProtocol\":\"unmarked-v1\"},\"contractVersion\":\"chat-execution/v1\",\"effectiveAccountId\":\"11111111-1111-4111-8111-111111111111\",\"id\":\"persistence-2\",\"requestId\":\"66666666-6666-4666-8666-666666666666\",\"sessionId\":\"session\"}" } ], "commands": { diff --git a/scripts/chat-fence-workflow-fixture/run.mjs b/scripts/chat-fence-workflow-fixture/run.mjs index 4960f3592..20c852f8b 100644 --- a/scripts/chat-fence-workflow-fixture/run.mjs +++ b/scripts/chat-fence-workflow-fixture/run.mjs @@ -20,6 +20,10 @@ import tls from "node:tls"; import http from "node:http"; import https from "node:https"; const require = createRequire(import.meta.url); +// Standalone ESM bundle includes installed SDK CommonJS dependencies. +// Same real require bridge as the projection fixture; no validation mocks. +const previousRequire = globalThis.require; +globalThis.require = require; const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); let networkAttempts = 0; const deny = () => { @@ -49,12 +53,19 @@ async function copy(from, to) { bindings.push({ path: from, sha256: createHash("sha256").update(bytes).digest("hex") }); } await copy("app/lib/workflows/runAgentWorkflow.ts", "workflow.ts"); +await mkdir(join(source, "projection")); +for (const name of await readdir(join(root, "app/lib/workflows/projection"))) + if (name.endsWith(".ts")) + await copy(`app/lib/workflows/projection/${name}`, `projection/${name}`); await mkdir(join(source, "fence")); for (const name of await readdir(join(root, "app/lib/workflows/fence"))) if (name.endsWith(".ts")) await copy(`app/lib/workflows/fence/${name}`, `fence/${name}`); await copy("lib/chat/auto-commit/autoCommitChatTurn.ts", "autoCommitChatTurn.ts"); for (const path of [ "lib/chat/fence/encodeStrictJson.ts", + "lib/chat/continuation/buildContinuationMarker.ts", + "lib/chat/continuation/assertMarkerFreeHistory.ts", + "lib/chat/continuation/encodeBoundedContinuationValue.ts", "lib/chat/fence/persistence/createFencedMessageWriter.ts", "lib/supabase/chat_fence/executeChatFenceCommand.ts", "lib/chat/upsertAssistantDataPart.ts", @@ -95,6 +106,9 @@ return {error:null,data:args.p_action==="bind"?{bound:true}:args.p_action==="rel }}; `, ); +// Load the installed SDK natively in the synthetic provider seam. Bundling its +// CJS OIDC dependency into the standalone ESM client breaks native require. +// The real reader and network-denial assertions remain unchanged. const seams = [ [ "@/app/lib/workflows/generateAssistantMessageId", @@ -117,7 +131,7 @@ const seams = [ [ "@/app/lib/workflows/runAgentStep", "runAgentStep", - 'record("provider",{original:args[0].originalMessages}); const {readUIMessageStream}=await import("ai"); const initial=args[0].originalMessages[0]; const stream=new ReadableStream({start(c){c.enqueue({type:"start",messageId:initial.id});c.enqueue({type:"text-start",id:"generated"});c.enqueue({type:"text-delta",id:"generated",delta:"synthetic result"});c.enqueue({type:"text-end",id:"generated"});c.enqueue({type:"finish"});c.close();}}); let responseMessage; for await(const value of readUIMessageStream({message:initial,stream})) responseMessage=value; record("sdk-optional",Object.hasOwn(responseMessage.parts.at(-1),"providerMetadata")); return {finishReason:scenario().fail==="iteration"?"tool-calls":"stop",aborted:false,responseMessages:[],responseMessage};', + 'record("provider",{original:args[0].originalMessages}); const sdkModule="ai"; const {readUIMessageStream}=await import(sdkModule); const initial=args[0].originalMessages[0]; const stream=new ReadableStream({start(c){c.enqueue({type:"start",messageId:initial.id});c.enqueue({type:"text-start",id:"generated"});c.enqueue({type:"text-delta",id:"generated",delta:"synthetic result"});c.enqueue({type:"text-end",id:"generated"});c.enqueue({type:"finish"});c.close();}}); let responseMessage; for await(const value of readUIMessageStream({message:initial,stream})) responseMessage=value; record("sdk-optional",Object.hasOwn(responseMessage.parts.at(-1),"providerMetadata")); return {finishReason:scenario().fail==="iteration"?"tool-calls":"stop",aborted:false,responseMessages:[],responseMessage};', ], [ "@/app/lib/workflows/persistAssistantMessageStep", @@ -214,6 +228,7 @@ try { metadata: { trace: "original" }, }; const input = { + streamProtocol: "canonical-base-v1", chatId: "chat", sessionId: "session", accountId: authority.effectiveAccount, @@ -259,6 +274,9 @@ try { "catalog", "new-object", "resume", + "resume-unmarked", + "resume-malformed", + "resume-oversized", "legacy", ]) { await writeFile(join(effects, "events.jsonl"), ""); @@ -274,17 +292,22 @@ try { }; if (name === "catalog" || name === "catalog-fail") invocation.input.devCatalogSurface = {}; if (name === "iteration") invocation.input.modelId = "synthetic"; - if (name === "new-object" || name === "resume") + if (name === "new-object" || name.startsWith("resume")) invocation.input.messages.push({ id: "historical-assistant", role: "assistant", parts: [{ type: "text", text: "OLD" }], metadata: { trace: "old" }, }); - if (name === "resume") + if (name.startsWith("resume")) invocation.fence.turn = { kind: "same-turn-resume", assistantId: "historical-assistant" }; + if (name === "resume-unmarked") invocation.input.streamProtocol = "unmarked-v1"; + if (name === "resume-malformed") invocation.input.messages.at(-1).parts[0].text = 3; + if (name === "resume-oversized") invocation.input.messages.at(-1).parts = Array.from({ length: 2049 }, () => ({ type: "text", text: "prior" })); const run = await start(runAgentWorkflow, [name === "legacy" ? invocation.input : invocation]); - if ( + if (name.startsWith("resume-")) + await assert.rejects(bounded(run.returnValue), /Continuation/); + else if ( [ "bind", "user", @@ -314,6 +337,13 @@ try { assert.equal(c.p.owner, authority.owner); } if (name === "bind") assert.deepEqual(actions, ["rpc"]); + if (name.startsWith("resume-")) { + assert.deepEqual(commands.map(c => c.p_action), ["bind"]); + assert(!actions.includes("provider")); + assert(!actions.includes("stream-start")); + assert(!actions.includes("credits")); + assert(!actions.includes("commit")); + } if (name === "user") { assert(!actions.includes("routing")); assert(!actions.includes("provider")); @@ -381,6 +411,7 @@ try { sessionId: editPayload.admission_envelope.sessionId, messages: structuredClone(editPayload.admission_envelope.messages), modelId: editPayload.execution_snapshot.content.options.modelId, + streamProtocol: editPayload.execution_snapshot.content.streamProtocol, artistId: editPayload.execution_snapshot.content.options.artistId ?? undefined, interactive: editPayload.execution_snapshot.content.options.interactive, sessionTitle: editPayload.execution_snapshot.content.sessionTitle ?? undefined, @@ -496,6 +527,8 @@ try { ), ); } finally { + if (previousRequire === undefined) delete globalThis.require; + else globalThis.require = previousRequire; await world?.close(); process.chdir(old); await rm(temp, { recursive: true, force: true }); diff --git a/scripts/chat-pricing-durable-compile.mjs b/scripts/chat-pricing-durable-compile.mjs new file mode 100644 index 000000000..804593f5f --- /dev/null +++ b/scripts/chat-pricing-durable-compile.mjs @@ -0,0 +1,118 @@ +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import { pathToFileURL, fileURLToPath } from "node:url"; +import { mkdtemp, realpath, readFile, writeFile, symlink, mkdir, rm } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { runInNewContext } from "node:vm"; +import { createHash } from "node:crypto"; +import { denyNetwork } from "./pack-scheduler-workflow-fixture/denyNetwork.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const output = process.env.CHAT_PRICING_COMPILE_OUTPUT; +const attempts = denyNetwork(); +const require = createRequire(join(root, "package.json")); +const builders = createRequire(require.resolve("workflow/next")); +const { StandaloneBuilder } = await import(pathToFileURL(builders.resolve("@workflow/builders"))); +const temp = await realpath(await mkdtemp(join(tmpdir(), "chat-pricing-boundary-"))); +const source = join(temp, "source"); +const previousDirectory = process.cwd(); +try { + await mkdir(source); + await symlink(join(root, "node_modules"), join(temp, "node_modules"), "dir"); + for (const name of [ + "fence", + "projection", + "prepareCatalogSurfaceStep.ts", + "sendCatalogSurfaceStep.ts", + ]) + await symlink(join(root, "app/lib/workflows", name), join(source, name)); + // Actual orchestration, pricing entrypoint and transitive implementations: no pricing seams. + await writeFile( + join(source, "workflow.ts"), + await readFile(join(root, "app/lib/workflows/runAgentWorkflow.ts")), + ); + await writeFile( + join(source, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { + target: "ES2022", + module: "ESNext", + moduleResolution: "bundler", + paths: { "@/*": [join(root, "*")] }, + }, + }), + ); + process.chdir(source); + await new StandaloneBuilder({ + buildTarget: "standalone", + workingDir: source, + projectRoot: source, + dirs: ["."], + stepsBundlePath: "../generated/steps.cjs", + workflowsBundlePath: "../generated/workflows.cjs", + webhookBundlePath: "../generated/webhook.cjs", + clientBundlePath: join(temp, "generated/client.mjs"), + }).build(); + const bundle = await readFile(join(temp, "generated/workflows.cjs"), "utf8"); + const literal = bundle.match(/var workflowCode = (`(?:\\[\s\S]|[^`])*`);/); + assert(literal, "StandaloneBuilder must expose its actual sandbox source"); + const sandbox = runInNewContext(literal[1], Object.create(null), { timeout: 1000 }); + assert.equal(typeof sandbox, "string"); + assert( + /WORKFLOW_USE_STEP[^\n]+getTokenCreditUsageStep/.test(sandbox), + "Missing pricing step reference", + ); + assert( + /WORKFLOW_USE_STEP[^\n]+recordCreditDeduction/.test(sandbox), + "Missing separate debit step reference", + ); + assert(/await getCreditUsage\(/.test(sandbox), "Real pricing entrypoint must remain wired"); + for (const forbidden of [ + "https://models.dev/api.json", + "async function fetchModelsDevMetadata", + "gateway.getAvailableModels()", + ]) + assert(!sandbox.includes(forbidden), `Pricing network chain escaped its step: ${forbidden}`); + assert.equal(attempts(), 0); + const paths = [ + "app/lib/workflows/runAgentWorkflow.ts", + "lib/credits/handleChatCredits.ts", + "lib/credits/getCreditUsage.ts", + "lib/credits/getTokenCreditUsageStep.ts", + "lib/credits/recordCreditDeduction.ts", + ]; + const bindings = []; + for (const path of paths) + bindings.push({ + path, + sha256: createHash("sha256") + .update(await readFile(join(root, path))) + .digest("hex"), + }); + if (output) + await writeFile( + resolve(previousDirectory, output), + JSON.stringify( + { + runtime: process.version, + networkAttempts: attempts(), + bindings, + sandboxSha256: createHash("sha256").update(sandbox).digest("hex"), + pricingStep: true, + separateDebitStep: true, + pricingNetworkChainAbsent: true, + scope: + "Actual sandbox compile inspection only. No workflow, pricing, provider, or debit executed. No blanket absence claim for unrelated SDK code.", + }, + null, + 2, + ), + ); + console.log( + "PASS actual pricing/debit step boundaries; pricing network chain absent; zero network attempts", + ); +} finally { + process.chdir(previousDirectory); + await rm(temp, { recursive: true, force: true }); +} diff --git a/scripts/chat-pricing-step-fixture.mjs b/scripts/chat-pricing-step-fixture.mjs new file mode 100644 index 000000000..4311d48ad --- /dev/null +++ b/scripts/chat-pricing-step-fixture.mjs @@ -0,0 +1,143 @@ +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { mkdtemp, realpath, mkdir, readFile, writeFile, symlink, rm } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { createHash } from "node:crypto"; +import { denyNetwork } from "./pack-scheduler-workflow-fixture/denyNetwork.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const previousDirectory = process.cwd(); +const output = process.env.CHAT_PRICING_FIXTURE_OUTPUT; +const attempts = denyNetwork(); +const require = createRequire(join(root, "package.json")); +const builders = createRequire(require.resolve("workflow/next")); +const { StandaloneBuilder } = await import(pathToFileURL(builders.resolve("@workflow/builders"))); +const temp = await realpath(await mkdtemp(join(tmpdir(), "chat-pricing-step-"))); +const source = join(temp, "source"); +const lookupLog = join(temp, "lookups.txt"); +let world; +try { + await mkdir(source); + await symlink(join(root, "node_modules"), join(temp, "node_modules"), "dir"); + const bindings = []; + for (const name of ["getCreditUsage.ts", "getTokenCreditUsageStep.ts"]) { + const path = `lib/credits/${name}`; + const bytes = await readFile(join(root, path)); + await writeFile(join(source, name), bytes); + bindings.push({ path, sha256: createHash("sha256").update(bytes).digest("hex") }); + } + await writeFile( + join(source, "model.ts"), + `import { appendFileSync } from "node:fs"; +export async function getModel(id: string) { + appendFileSync(${JSON.stringify(lookupLog)}, id + "\\n"); + if(id === "failure") throw new Error("synthetic pricing failure"); + if(id === "missing") return undefined; + return { id, pricing: { input: "0.00003", output: "0.00006" } }; +}`, + ); + await writeFile( + join(source, "workflow.ts"), + `import { getCreditUsage } from "./getCreditUsage"; +export async function pricingFixture(input: { inputTokens: number; outputTokens: number; modelId: string; gatewayCost?: number }) { + "use workflow"; + return getCreditUsage({inputTokens:input.inputTokens,outputTokens:input.outputTokens} as never, input.modelId, input.gatewayCost); +}`, + ); + await writeFile( + join(source, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { + target: "ES2022", + module: "ESNext", + moduleResolution: "bundler", + paths: { "@/lib/ai/getModel": [join(source, "model.ts")], "@/*": [join(root, "*")] }, + }, + }), + ); + process.chdir(source); + await new StandaloneBuilder({ + buildTarget: "standalone", + workingDir: source, + projectRoot: source, + dirs: ["."], + stepsBundlePath: "../generated/steps.cjs", + workflowsBundlePath: "../generated/workflows.cjs", + webhookBundlePath: "../generated/webhook.cjs", + clientBundlePath: join(temp, "generated/client.mjs"), + }).build(); + const { createLocalWorld } = await import( + pathToFileURL(createRequire(require.resolve("@workflow/core")).resolve("@workflow/world-local")) + ); + const { setWorld } = await import(pathToFileURL(require.resolve("@workflow/core/runtime"))); + const { start } = await import(pathToFileURL(require.resolve("workflow/api"))); + world = createLocalWorld({ dataDir: join(temp, "journal") }); + setWorld(world); + const steps = await import(pathToFileURL(join(temp, "generated/steps.cjs"))); + const workflows = await import(pathToFileURL(join(temp, "generated/workflows.cjs"))); + world.registerHandler("__wkf_step_", steps.POST); + world.registerHandler("__wkf_workflow_", workflows.POST); + await world.start(); + const { pricingFixture } = await import(pathToFileURL(join(temp, "generated/client.mjs"))); + const cases = [ + { name: "positive", gatewayCost: 0.07, expected: 0.07, lookups: 0 }, + ...[undefined, 0, -1, NaN, Infinity].map((gatewayCost, index) => ({ + name: `fallback-${index}`, + gatewayCost, + expected: 0.06, + lookups: 1, + })), + { name: "lookup-failure", modelId: "failure", expected: 0, lookups: 1 }, + { name: "missing-model", modelId: "missing", expected: 0, lookups: 1 }, + { name: "zero-tokens", inputTokens: 0, expected: 0, lookups: 1 }, + ]; + const results = []; + for (const fixture of cases) { + await writeFile(lookupLog, ""); + const run = await start(pricingFixture, [ + { + inputTokens: fixture.inputTokens ?? 1000, + outputTokens: 500, + modelId: fixture.modelId ?? "fixture", + gatewayCost: fixture.gatewayCost, + }, + ]); + let timer; + let value; + try { + value = await Promise.race([ + run.returnValue, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`Pricing fixture deadline: ${fixture.name}`)), + 15000, + ); + }), + ]); + } finally { + clearTimeout(timer); + } + assert(Math.abs(value - fixture.expected) < 1e-12, `Unexpected cost: ${fixture.name}`); + const lookups = (await readFile(lookupLog, "utf8")).split("\n").filter(Boolean).length; + assert.equal(lookups, fixture.lookups, `Lookup count: ${fixture.name}`); + results.push({ name: fixture.name, value, lookups }); + } + assert.equal(attempts(), 0); + const result = { + runtime: process.version, + networkAttempts: attempts(), + bindings, + results, + scope: + "Real copied pricing resolver and durable pricing step, synthetic getModel leaf only. No debit/provider/real catalog lookup. Actual full workflow boundary separately compiled without seams.", + }; + if (output) await writeFile(resolve(previousDirectory, output), JSON.stringify(result, null, 2)); + console.log(JSON.stringify(result, null, 2)); + console.log("PASS nine compiled pricing cases; no debit or network attempts"); +} finally { + await world?.close(); + process.chdir(previousDirectory); + await rm(temp, { recursive: true, force: true }); +} diff --git a/scripts/chat-projection-proof-fixture.mjs b/scripts/chat-projection-proof-fixture.mjs new file mode 100644 index 000000000..565617524 --- /dev/null +++ b/scripts/chat-projection-proof-fixture.mjs @@ -0,0 +1,301 @@ +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import { pathToFileURL, fileURLToPath } from "node:url"; +import { + mkdtemp, + realpath, + mkdir, + writeFile, + symlink, + rm, + readFile, + readdir, +} from "node:fs/promises"; +import { join, dirname } from "node:path"; +import { tmpdir } from "node:os"; +import { createHash } from "node:crypto"; +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const out = process.env.CHAT_PROJECTION_RECEIPT; +const require = createRequire(join(root, "package.json")); +const { denyNetwork } = await import( + pathToFileURL(join(root, "scripts/pack-scheduler-workflow-fixture/denyNetwork.mjs")) +); +const attempts = denyNetwork(); +const builders = createRequire(require.resolve("workflow/next")); +const { StandaloneBuilder } = await import(pathToFileURL(builders.resolve("@workflow/builders"))); +const temp = await realpath(await mkdtemp(join(tmpdir(), "workflow-origin-probe-"))); +const source = join(temp, "source"); +const cwd = process.cwd(); +let world; +// StandaloneBuilder emits an ESM client containing bundled CommonJS SDK dependencies. +// Supply Node's real require for that generated client; no production module is mocked. +const previousRequire = globalThis.require; +globalThis.require = require; +try { + await mkdir(source); + await symlink(join(root, "node_modules"), join(temp, "node_modules"), "dir"); + await writeFile( + join(source, "workflow.ts"), + `import {getWritable,getWorkflowMetadata,getStepMetadata} from 'workflow'; +import {getWorld} from 'workflow/runtime'; +import {getRun} from 'workflow/api'; +import {hydrateResourceIO,observabilityRevivers} from 'workflow/observability'; +import {collectCanonicalProjection} from '@/lib/chat/projection/collectCanonicalProjection'; +import {verifyProjectionObservation} from '@/lib/chat/projection/verifyProjectionObservation'; +import {createProjectionEvidencePorts} from '@/lib/chat/projection/createProjectionEvidencePorts'; +import {recordProjectionProofStep} from '@/app/lib/workflows/projection/recordProjectionProofStep'; +import {prepareProjectionHistoryStep} from '@/app/lib/workflows/projection/prepareProjectionHistoryStep'; +import {assertFirstChatEffectAttempt} from '@/app/lib/workflows/projection/assertFirstChatEffectAttempt'; +async function emit(input:any) { + 'use step'; + const runId=getWorkflowMetadata().workflowRunId; const stepId=getStepMetadata().stepId; + const w=getWritable().getWriter(); + try { + await w.write({type:'start',messageId:'synthetic-assistant'}); + const collected=await collectCanonicalProjection({stream:(async function*(){yield {type:'custom',kind:'provider.synthetic',providerMetadata:{provider:{opaque:'unchanged'}}};})(),previous:{id:'synthetic-assistant',role:'assistant',parts:[]},runId,stepId:()=>stepId,onProjection(){},write:chunk=>w.write(chunk)}); + await w.write({type:'finish'});await w.close(); + return {generatedProjectionObservations:collected.generatedProjectionObservations}; + }finally{w.releaseLock();} +} +export async function originProbe(input:any) { + 'use workflow'; + await prepareProjectionHistoryStep(input.messages,{accountId:input.accountId,chatId:input.chatId,sessionId:input.sessionId}); + const producer = await emit(input); + await recordProjectionProofStep(producer.generatedProjectionObservations.observations[0].observation.data.originStepId,producer.generatedProjectionObservations); + return producer; +} +async function verify(input:any) { + 'use step'; + const world=getWorld(); + const ports=createProjectionEvidencePorts({world}); + return verifyProjectionObservation({...input,ports,signal:new AbortController().signal}); +} +export async function readProbe(input:any) { + 'use workflow'; + return verify(input); +} +async function attemptEffect(input:any) { + 'use step'; + const {appendFileSync}=await import('node:fs'); + const metadata=getStepMetadata(); + appendFileSync(input.log,JSON.stringify({kind:'entry',attempt:metadata.attempt,stepId:metadata.stepId})+'\\n'); + assertFirstChatEffectAttempt('generation'); + if(input.mode==='before-effect') throw new Error('Synthetic failure before effect'); + appendFileSync(input.log,JSON.stringify({kind:'effect',attempt:metadata.attempt,stepId:metadata.stepId})+'\\n'); + return {stepId:metadata.stepId,attempt:metadata.attempt}; +} +export async function attemptProbe(input:any) { + 'use workflow'; + return attemptEffect(input); +} +`, + ); + await writeFile( + join(source, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { + target: "ES2022", + module: "ESNext", + moduleResolution: "bundler", + paths: { "@/*": [join(root, "*")] }, + }, + }), + ); + process.chdir(source); + await new StandaloneBuilder({ + buildTarget: "standalone", + workingDir: source, + projectRoot: source, + dirs: ["."], + stepsBundlePath: "../generated/steps.cjs", + workflowsBundlePath: "../generated/workflows.cjs", + webhookBundlePath: "../generated/webhook.cjs", + clientBundlePath: join(temp, "generated/client.mjs"), + }).build(); + const { createLocalWorld } = await import( + pathToFileURL(createRequire(require.resolve("@workflow/core")).resolve("@workflow/world-local")) + ); + const { setWorld, getWorld } = await import(pathToFileURL(require.resolve("workflow/runtime"))); + const { start, getRun } = await import(pathToFileURL(require.resolve("workflow/api"))); + const { hydrateResourceIO, observabilityRevivers } = await import( + pathToFileURL(require.resolve("workflow/observability")) + ); + world = createLocalWorld({ dataDir: join(temp, "journal") }); + setWorld(world); + world.registerHandler( + "__wkf_step_", + (await import(pathToFileURL(join(temp, "generated/steps.cjs")))).POST, + ); + world.registerHandler( + "__wkf_workflow_", + (await import(pathToFileURL(join(temp, "generated/workflows.cjs")))).POST, + ); + await world.start(); + const { originProbe, readProbe, attemptProbe } = await import( + pathToFileURL(join(temp, "generated/client.mjs")) + ); + const input = { + chatId: "synthetic-chat", + sessionId: "synthetic-session", + accountId: "synthetic-account", + messages: [], + modelId: "synthetic", + agentContext: {}, + }; + const run = await start(originProbe, [input]); + let timer; + const within = async promise => { + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("probe timeout")), 15000); + }), + ]); + } finally { + clearTimeout(timer); + } + }; + const result = await within(run.returnValue); + const observation = result.generatedProjectionObservations.observations[0].observation; + const record = await getWorld().runs.get(run.runId, { resolveData: "all" }); + const steps = await getWorld().steps.get(run.runId, observation.data.originStepId, { + resolveData: "all", + }); + assert.deepEqual(hydrateResourceIO(record, observabilityRevivers).input, [input]); + const recordedSteps = await getWorld().steps.list({ runId: run.runId, resolveData: "none" }); + const proofStep = recordedSteps.data.find(step => + step.stepName.endsWith("//recordProjectionProofStep"), + ); + assert(proofStep && proofStep.status === "completed"); + const portsOps = []; + const chunks = []; + for await (const chunk of getRun(run.runId).getReadable({ ops: portsOps })) chunks.push(chunk); + await Promise.all(portsOps); + const { readUIMessageStream } = await import(pathToFileURL(require.resolve("ai"))); + let message; + for await (const current of readUIMessageStream({ + stream: new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk); + controller.close(); + }, + }), + })) + message = current; + assert.deepEqual(JSON.parse(JSON.stringify(message.parts)), [ + observation, + { type: "text", text: observation.data.fallback.text, state: "done" }, + ]); + const verified = await start(readProbe, [ + { + observation, + message, + scope: { chatId: input.chatId, sessionId: input.sessionId, accountId: input.accountId }, + producers: [ + { + deploymentId: record.deploymentId, + workflowName: record.workflowName, + stepName: steps.stepName, + proofStepName: proofStep.stepName, + }, + ], + }, + ]); + assert.deepEqual(await within(verified.returnValue), observation.data.original); + const refused = await start(originProbe, [ + { + ...input, + messages: [ + { id: "caller", role: "assistant", parts: [{ type: "custom", kind: "caller.unverified" }] }, + ], + }, + ]); + await assert.rejects(within(refused.returnValue), /Projection history evidence unavailable/); + const refusedSteps = await getWorld().steps.list({ runId: refused.runId, resolveData: "none" }); + assert(!refusedSteps.data.some(step => step.stepName.endsWith("//emit"))); + const attemptCases = []; + const createEvent = world.events.create.bind(world.events); + const guardedSteps = new Set(); + let mode, + injected = false; + world.events.create = async (...args) => { + const event = args[1]; + const target = event.eventType === "step_completed" && guardedSteps.has(event.correlationId); + if (target && !injected && mode === "completion-lost") { + injected = true; + throw new Error("Synthetic completion lost before persistence"); + } + const result = await createEvent(...args); + if (event.eventType === "step_started" && result.step?.stepName.endsWith("//attemptEffect")) + guardedSteps.add(result.step.stepId); + if (target && !injected && mode === "ack-lost") { + injected = true; + throw new Error("Synthetic completion persisted but ACK lost"); + } + return result; + }; + for (mode of ["completion-lost", "ack-lost", "before-effect"]) { + injected = false; + const log = join(temp, mode + ".jsonl"); + const probe = await start(attemptProbe, [{ mode, log }]); + if (mode === "ack-lost") assert.equal((await within(probe.returnValue)).attempt, 1); + else await assert.rejects(within(probe.returnValue), /reconciliation/); + const records = (await readFile(log, "utf8")) + .trim() + .split("\n") + .map(line => JSON.parse(line)); + const effects = records.filter(record => record.kind === "effect"); + assert.equal(effects.length, mode === "before-effect" ? 0 : 1); + assert.deepEqual( + records.filter(record => record.kind === "entry").map(record => record.attempt), + mode === "ack-lost" ? [1] : [1, 2], + ); + assert.equal(new Set(records.map(record => record.stepId)).size, 1); + attemptCases.push({ mode, records, injected }); + } + world.events.create = createEvent; + assert.equal(attempts(), 0); + const sourcePaths = [ + "package.json", + "pnpm-lock.yaml", + "app/lib/workflows/projection/recordProjectionProofStep.ts", + "app/lib/workflows/projection/prepareProjectionHistoryStep.ts", + "app/lib/workflows/projection/assertFirstChatEffectAttempt.ts", + "scripts/chat-projection-proof-fixture.mjs", + ...(await readdir(join(root, "lib/chat/projection"))) + .filter(name => name.endsWith(".ts")) + .map(name => "lib/chat/projection/" + name), + ]; + const sourcePins = []; + for (const path of sourcePaths) + sourcePins.push({ + path, + sha256: createHash("sha256") + .update(await readFile(join(root, path))) + .digest("hex"), + }); + const receipt = { + sourcePins, + node: process.version, + workflow: "4.2.4", + networkAttempts: attempts(), + attemptCases, + canonicalReadback: true, + completedProofReadback: true, + separateWorkflowAwaitedProofStep: true, + installedSdkCanonicalAssembly: true, + verifiedInsideJournaledStep: true, + rejectedIngressBeforeProducer: true, + scope: + "Actual production pure proof writer and verifier compiled into synthetic local workflows. Readback required; no write ACK or atomicity claim. No deployment admission, production World/key/provider/DB or activation.", + }; + if (out) await writeFile(out, JSON.stringify(receipt, null, 2) + "\n"); + console.log(JSON.stringify(receipt)); +} finally { + await world?.close(); + if (previousRequire === undefined) delete globalThis.require; + else globalThis.require = previousRequire; + process.chdir(cwd); + await rm(temp, { recursive: true, force: true }); +} diff --git a/tsconfig.ai-sdk-v7.json b/tsconfig.ai-sdk-v7.json new file mode 100644 index 000000000..072e01f56 --- /dev/null +++ b/tsconfig.ai-sdk-v7.json @@ -0,0 +1,24 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "incremental": false + }, + "include": [ + "lib/agent/tools/__tests__/sdkV7Runtime.test.ts", + "lib/agent/tools/__tests__/agentContextSchema.test.ts", + "lib/agents/generalAgent/__tests__/getAnthropicProviderOptions.test.ts", + "lib/agent/contextManagement/__tests__/wrapToolsWithAbortIterable.test.ts", + "lib/agent/tools/__tests__/wrappedTaskSdk.test.ts", + "lib/credits/__tests__/getCreditUsageStepBoundary.test.ts", + "lib/chat/projection/**/*.ts", + "lib/chat/continuation/**/*.ts", + "lib/chat/__tests__/continuationCors.test.ts", + "app/lib/workflows/__tests__/sendStreamStartContinuation.test.ts", + "app/lib/workflows/__tests__/runAgentStepProjection.test.ts", + "app/lib/workflows/__tests__/runAgentWorkflowProjection.test.ts", + "app/lib/workflows/__tests__/persistProjectedAssistantStep.test.ts", + "app/lib/workflows/__tests__/runAgentStepProjectionStop.test.ts", + "app/lib/workflows/__tests__/projectionRedelivery.test.ts" + ], + "exclude": ["node_modules"] +} diff --git a/tsconfig.chat-continuation.json b/tsconfig.chat-continuation.json new file mode 100644 index 000000000..ed877f19b --- /dev/null +++ b/tsconfig.chat-continuation.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { "strict": true, "incremental": false }, + "include": ["lib/chat/continuation/**/*.ts"], + "exclude": ["node_modules"] +}