Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 5e0af1cdff test(timeline): page back from an oversized turn into the turn before it
Failing reproduction for the third review finding on #10179. The
frame-budget fallback returns item pages whose start cursor can fall
inside the earlier turn. A whole-turn `before` page from that cursor
extends to the end of the turn that holds it, so it ends at the cursor
instead of the row before it, and the app drops the page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 03:11:22 +00:00
7aa42ea437 fix(timeline): keep halving the fallback limit past a spanned tool call
d016bf0b4 stopped the frame-budget fallback when a reselect returned as
many rows as the previous one. A turn whose spanning tool call completes
a few rows before the end returns the same rows for limits that land
inside the span, but a smaller limit lands after it and fits. The
fallback now halves the limit down to 1 and picks the error from the
row count of that last page.

Co-authored-by: AnalyticETH <hello@analytic.lol>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 02:56:23 +00:00
d016bf0b44 fix(timeline): stop the frame-budget fallback when a page cannot shrink
A tail page starts at the first row of the source span it lands in. When
one tool call starts before an oversized turn and completes after it, its
span covers every row, so a smaller limit returns the same page. The
fallback halved the limit down to 1 and then reported that a single item
was too large. It now stops at the first reselect that does not shrink and
says that one item spans more than the limit.

Document in the SDK reference, the plugin hook docs, and the zh-CN copies
that a whole-turn page over the message limit arrives as an item page that
can start partway through a turn.

Co-authored-by: AnalyticETH <hello@analytic.lol>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 02:44:10 +00:00
b93afb9156 test(server): read a turn larger than the message limit through the daemon
Opening a chat whose newest turn is larger than the 100 MiB message
limit never showed its history. The daemon built one reply for the
complete turn, the outbound transport refused it with "Logical message
too large", and the app waited until its request timed out.

This test fills one turn with about 105 MiB of replies and reads it as
the app does: a whole-turn tail page of 40 items, then older pages
until the start. On main the first request gets no reply within 20 s.
With the frame-budget fallback, every reply arrives and the pages reach
the start of the turn. The test runs in test:integration so CI covers it.

Refs #8458

Co-authored-by: AnalyticETH <hello@analytic.lol>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 02:07:12 +00:00
AnalyticETH b60f3d26aa fix(timeline): fall back to pages when a whole turn exceeds the frame limit 2026-11-18 18:14:05 -05:00
12 changed files with 416 additions and 76 deletions
+7 -3
View File
@@ -65,9 +65,13 @@ Initialization timeouts guard lack of catch-up progress, not the full multi-page
Opening or resuming an agent fetches the latest available turns with a soft target of 40
projected items. Backward pages and prompt-jump windows also include whole turns, including
all currently available rows of an active run. There is no per-turn cap: a large run can
exceed the target. Local history mounting uses the same boundaries so revealing older rows
does not change the collapse state of a turn already displayed.
all currently available rows of an active run. A large run can exceed the target. For a paged
request whose complete-turn reply cannot fit the wire message limit, the daemon falls back to
item pages with continuation cursors so the rest remains reachable. A tail page starts at the first row of
the source span it reaches. When one item's updates span the turn up to its last row and more than
the limit, no smaller tail page exists and the request fails with an error. Local history mounting uses
turn boundaries so revealing older rows does not change the collapse state of a turn already
displayed.
`wholeTurns` is a preference negotiated once at the client fetch boundary. Hosts advertising
`features.wholeTurnTimeline` receive it; other hosts receive the existing item-based request.
+2 -1
View File
@@ -308,7 +308,8 @@ export interface PaseoAgentTimelineRefetchOptions {
projection?: FetchAgentTimelineProjection;
/**
* Extends a `tail` or `before` page back to the start of the oldest turn it touches, so
* `{ direction: "tail", limit: 1, wholeTurns: true }` returns the latest turn.
* `{ direction: "tail", limit: 1, wholeTurns: true }` returns the latest turn. When the complete
* turns do not fit the message limit, the host returns an item page that can start mid-turn.
*/
wholeTurns?: boolean;
requestId?: string;
+2 -1
View File
@@ -109,7 +109,8 @@ export interface PluginHookEvents {
* The payload carries no history. Read the turn with
* `paseo.agents.ref(agent.id).timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })`
* and keep the entries whose `turnId` equals this `turnId`. The result is empty when a newer turn
* started before the read, or when `turnId` is `null`.
* started before the read, or when `turnId` is `null`. A turn larger than the message limit
* arrives as an item page that can start mid-turn; page `before` its `startCursor` for the rest.
*/
outcome: PluginTurnOutcome;
};
+1 -1
View File
@@ -90,7 +90,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/daemon-e2e/oversized-whole-turn.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -5,6 +5,190 @@ import { describe, expect, it } from "vitest";
import { selectReferenceProjectedTimelinePage } from "./test-utils/timeline-page-reference.js";
import type { AgentTimelineItem } from "./agent-sdk-types.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
import { selectTimelineResponseWithinFrameBudget } from "../session/timeline-frame-budget.js";
describe("whole-turn byte budget", () => {
function fixture() {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent", { epoch: "current" });
for (let index = 1; index <= 8; index++) {
store.append(
"agent",
{ type: "assistant_message", messageId: `item-${index}`, text: "\u20ac".repeat(180) },
{ turnId: "one-turn" },
);
}
return store;
}
function request(
store: ReturnType<typeof fixture>,
options: {
maxBytes: number;
limit: number;
direction?: "before" | "after";
cursor?: { epoch: string; seq: number };
},
) {
return selectTimelineResponseWithinFrameBudget({
wholeTurns: true,
limit: options.limit,
maxBytes: options.maxBytes,
select: ({ wholeTurns, limit }) => {
const { rows, ...page } = store.fetch("agent", {
direction: options.direction ?? "tail",
cursor: options.cursor,
wholeTurns,
limit,
});
return { type: "fetch_agent_timeline_response", payload: { ...page, entries: rows } };
},
}).payload;
}
it("keeps complete turns whenever they fit, and leaves explicit full reads unchanged", () => {
const store = fixture();
expect(request(store, { maxBytes: 10000, limit: 2 }).entries.map((row) => row.seq)).toEqual([
1, 2, 3, 4, 5, 6, 7, 8,
]);
expect(request(store, { maxBytes: 500, limit: 0 }).entries).toHaveLength(8);
});
it("splits an oversized turn into adjacent older pages without losing any entries", () => {
const store = fixture();
let page = request(store, { maxBytes: 1300, limit: 2 });
expect(page).toMatchObject({ startSeq: 8, endSeq: 8, hasOlder: true });
const seen = page.entries.map((row) => row.seq);
for (let index = 7; index >= 1; index--) {
page = request(store, {
maxBytes: 1300,
limit: 2,
direction: "before",
cursor: { epoch: page.epoch, seq: page.startSeq! },
});
expect(page).toMatchObject({ startSeq: index, endSeq: index, hasOlder: index > 1 });
seen.unshift(...page.entries.map((row) => row.seq));
}
expect(seen).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
});
it("keeps the forward cursor on the oldest unsent part of an oversized turn", () => {
const store = fixture();
let seq = 1;
for (let expected = 2; expected <= 8; expected++) {
const page = request(store, {
maxBytes: 1300,
limit: 2,
direction: "after",
cursor: { epoch: "current", seq },
});
expect(page).toMatchObject({ startSeq: expected, endSeq: expected, hasNewer: expected < 8 });
seq = page.endSeq!;
}
});
it("reports when even a single row cannot fit", () => {
expect(() => request(fixture(), { maxBytes: 100, limit: 2 })).toThrow(
/timeline item exceeds the response size limit/i,
);
});
function spannedTurn(trailing: number) {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent", { epoch: "current" });
const tool = (callId: string, status: "running" | "completed") =>
({
type: "tool_call",
callId,
name: "shell",
status,
error: null,
detail: { type: "shell", command: "sleep 600" },
}) as AgentTimelineItem;
store.append("agent", tool("background", "running"), { turnId: "one-turn" });
for (let index = 1; index <= 8; index++) {
store.append(
"agent",
{ type: "assistant_message", messageId: `item-${index}`, text: "€".repeat(180) },
{ turnId: "one-turn" },
);
}
store.append("agent", tool("background", "completed"), { turnId: "one-turn" });
for (let index = 1; index <= trailing; index++) {
store.append("agent", tool(`after-${index}`, "completed"), { turnId: "one-turn" });
}
let selects = 0;
const tail = () =>
selectTimelineResponseWithinFrameBudget({
wholeTurns: true,
limit: 40,
maxBytes: 1300,
select: ({ wholeTurns, limit }) => {
selects++;
const { rows, ...page } = store.fetch("agent", { direction: "tail", wholeTurns, limit });
return { type: "fetch_agent_timeline_response", payload: { ...page, entries: rows } };
},
}).payload;
return { tail, selects: () => selects };
}
it("reports when one tool call spans the turn to its last row", () => {
const turn = spannedTurn(0);
expect(turn.tail).toThrow(/one item spans more than the response size limit/i);
expect(turn.selects()).toBe(5);
});
it("reaches the rows after a tool call that spans most of the turn", () => {
for (const trailing of [1, 3, 7]) {
const page = spannedTurn(trailing).tail();
expect(page.hasOlder).toBe(true);
expect(page.entries.length).toBeGreaterThan(0);
expect(
page.entries.every(
(row) => row.item.type === "tool_call" && row.item.callId.startsWith("after-"),
),
).toBe(true);
}
});
});
describe("whole-turn byte budget across turns", () => {
it("pages back from an oversized turn into the turn before it without repeating rows", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent", { epoch: "current" });
store.append("agent", { type: "user_message", text: "first", messageId: "u1" });
for (let index = 1; index <= 5; index++)
store.append("agent", { type: "assistant_message", messageId: `a${index}`, text: "ok" });
store.append("agent", { type: "user_message", text: "second", messageId: "u2" });
for (let index = 1; index <= 8; index++)
store.append("agent", {
type: "assistant_message",
messageId: `b${index}`,
text: "x".repeat(400),
});
const fetch = (direction: "tail" | "before", cursor?: { epoch: string; seq: number }) =>
selectTimelineResponseWithinFrameBudget({
wholeTurns: true,
limit: 4,
maxBytes: 2500,
select: ({ wholeTurns, limit }) => {
const { rows, ...page } = store.fetch("agent", { direction, cursor, wholeTurns, limit });
return { type: "fetch_agent_timeline_response", payload: { ...page, entries: rows } };
},
}).payload;
let page = fetch("tail");
const seen = page.entries.map((row) => row.seqStart);
while (page.hasOlder) {
const cursor = page.startSeq!;
page = fetch("before", { epoch: "current", seq: cursor });
expect(page.endSeq).toBe(cursor - 1);
seen.unshift(...page.entries.map((row) => row.seqStart));
}
expect(seen).toEqual(Array.from({ length: 15 }, (_, index) => index + 1));
});
});
describe("InMemoryAgentTimelineStore", () => {
it("resets stale forward cursors to complete available turns", () => {
@@ -0,0 +1,107 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, test } from "vitest";
import { createDaemonTestContext } from "../test-utils/index.js";
// #8458: a whole-turn page is one logical message, so a turn above the message limit never arrived.
test("reading a turn larger than the message limit returns pages that reach its start", async () => {
const ctx = await createDaemonTestContext();
const cwd = mkdtempSync(path.join(tmpdir(), "oversized-whole-turn-"));
try {
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
const replies = 420;
for (let index = 0; index < replies; index += 1) {
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, {
type: "assistant_message",
messageId: `reply-${index}`,
text: `reply-${index} ${"x".repeat(250 * 1024)}`,
});
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, {
type: "tool_call",
callId: `call-${index}`,
name: "Bash",
status: "completed",
error: null,
detail: { type: "shell", command: `echo ${index}`, output: `${index}` },
});
}
let page = await ctx.client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 40,
wholeTurns: true,
timeout: 20_000,
});
const seen = new Set<string>();
const collect = () => {
for (const entry of page.entries) {
if (entry.item.type === "assistant_message") seen.add(entry.item.text.split(" ")[0]);
}
};
collect();
expect(page.entries.length).toBeGreaterThan(0);
while (page.hasOlder) {
const cursor = page.startCursor;
if (!cursor) throw new Error("page with older history has no start cursor");
page = await ctx.client.fetchAgentTimeline(agent.id, {
direction: "before",
cursor,
limit: 40,
wholeTurns: true,
timeout: 20_000,
});
collect();
}
expect(seen.size).toBe(replies);
const small = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 1 });
expect(small.entries).toHaveLength(1);
} finally {
await ctx.cleanup();
rmSync(cwd, { recursive: true, force: true });
}
}, 180_000);
// A tail page starts at the first row of the source span it lands in. One tool call that starts
// before the oversized turn and completes after it spans every row, so no smaller page exists.
// The daemon answers with an error instead of letting the request time out.
test("reading a turn that one tool call spans past the message limit fails with a reply", async () => {
const ctx = await createDaemonTestContext();
const cwd = mkdtempSync(path.join(tmpdir(), "oversized-spanned-turn-"));
try {
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
const background = (status: "running" | "completed") => ({
type: "tool_call" as const,
callId: "background",
name: "Bash",
status,
error: null,
detail: { type: "shell" as const, command: "sleep 600" },
});
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, background("running"));
for (let index = 0; index < 420; index += 1) {
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, {
type: "assistant_message",
messageId: `reply-${index}`,
text: `reply-${index} ${"x".repeat(250 * 1024)}`,
});
}
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, background("completed"));
await expect(
ctx.client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 40,
wholeTurns: true,
timeout: 20_000,
}),
).rejects.toThrow(/one item spans more than the response size limit/i);
const small = await ctx.client.fetchAgentTimeline(agent.id, { direction: "before", limit: 1 });
expect(small.entries).toHaveLength(1);
} finally {
await ctx.cleanup();
rmSync(cwd, { recursive: true, force: true });
}
}, 180_000);
+49 -66
View File
@@ -213,6 +213,7 @@ import {
type SpeechModelsSessionOptions,
} from "./session/speech/speech-models-session.js";
import { WorkspaceFilesSession } from "./session/files/workspace-files-session.js";
import { selectTimelineResponseWithinFrameBudget } from "./session/timeline-frame-budget.js";
import { AgentConfigSession } from "./session/agent-config/agent-config-session.js";
import { ProjectConfigSession } from "./session/project-config/project-config-session.js";
import { DaemonSession, type DaemonRuntimeConfig } from "./session/daemon/daemon-session.js";
@@ -8458,76 +8459,58 @@ export class Session {
});
const agentPayload = await this.buildAgentPayload(snapshot);
const fetchedControlTimeline = this.agentManager.fetchTimeline(msg.agentId, {
direction,
cursor,
const supportsReasoningMerge = source
? this.supportsForSource(CLIENT_CAPS.reasoningMergeEnum, source)
: this.supports(CLIENT_CAPS.reasoningMergeEnum);
const response = selectTimelineResponseWithinFrameBudget({
limit: msg.limit,
wholeTurns: msg.wholeTurns,
});
const selectedTimeline = {
timeline: fetchedControlTimeline,
entries: fetchedControlTimeline.rows,
startSeq: fetchedControlTimeline.startSeq,
endSeq: fetchedControlTimeline.endSeq,
hasOlder: fetchedControlTimeline.hasOlder,
hasNewer: fetchedControlTimeline.hasNewer,
};
const startCursor =
selectedTimeline.startSeq !== null
? { epoch: selectedTimeline.timeline.epoch, seq: selectedTimeline.startSeq }
: null;
const endCursor =
selectedTimeline.endSeq !== null
? { epoch: selectedTimeline.timeline.epoch, seq: selectedTimeline.endSeq }
: null;
const entries = selectedTimeline.entries.filter((entry) =>
this.supportsTimelineItem(entry.item, source),
);
this.emitForSource(
{
type: "fetch_agent_timeline_response",
payload: {
requestId: msg.requestId,
agentId: msg.agentId,
agent: agentPayload,
select: ({ limit, wholeTurns }) => {
const timeline = this.agentManager.fetchTimeline(msg.agentId, {
direction,
projection,
epoch: selectedTimeline.timeline.epoch,
reset: fetchedControlTimeline.reset,
staleCursor: fetchedControlTimeline.staleCursor,
gap: fetchedControlTimeline.gap,
window: selectedTimeline.timeline.window,
startCursor,
endCursor,
hasOlder: selectedTimeline.hasOlder,
hasNewer: selectedTimeline.hasNewer,
...(msg.mergeWindow === true ? { mergeWindow: true } : {}),
entries: entries.map((entry) => {
const payloadEntry = {
provider: snapshot.provider,
item: entry.item,
timestamp: entry.timestamp,
seqStart: entry.seqStart,
seqEnd: entry.seqEnd,
sourceSeqRanges: entry.sourceSeqRanges,
turnId: undefined as string | undefined,
collapsed: (
source
? this.supportsForSource(CLIENT_CAPS.reasoningMergeEnum, source)
: this.supports(CLIENT_CAPS.reasoningMergeEnum)
)
? entry.collapsed
: entry.collapsed.filter((value) => value !== "reasoning_merge"),
};
payloadEntry.turnId = entry.turnId;
return payloadEntry;
}),
error: null,
},
cursor,
limit,
wholeTurns,
});
const { epoch, startSeq, endSeq } = timeline;
return {
type: "fetch_agent_timeline_response" as const,
payload: {
requestId: msg.requestId,
agentId: msg.agentId,
agent: agentPayload,
direction,
projection,
epoch,
reset: timeline.reset,
staleCursor: timeline.staleCursor,
gap: timeline.gap,
window: timeline.window,
startCursor: startSeq === null ? null : { epoch, seq: startSeq },
endCursor: endSeq === null ? null : { epoch, seq: endSeq },
hasOlder: timeline.hasOlder,
hasNewer: timeline.hasNewer,
...(msg.mergeWindow === true ? { mergeWindow: true } : {}),
entries: timeline.rows
.filter((entry) => this.supportsTimelineItem(entry.item, source))
.map((entry) => ({
provider: snapshot.provider,
item: entry.item,
timestamp: entry.timestamp,
seqStart: entry.seqStart,
seqEnd: entry.seqEnd,
sourceSeqRanges: entry.sourceSeqRanges,
turnId: entry.turnId,
collapsed: supportsReasoningMerge
? entry.collapsed
: entry.collapsed.filter((value) => value !== "reasoning_merge"),
})),
error: null,
},
};
},
source,
);
});
this.emitForSource(response, source);
} catch (error) {
this.sessionLogger.error(
{ err: error, agentId: msg.agentId },
@@ -0,0 +1,60 @@
import { MAX_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
// Routed replies add their own envelope around the session frame.
const TIMELINE_FRAME_BUDGET_BYTES = MAX_WEBSOCKET_MESSAGE_BYTES - 64 * 1024;
interface TimelineRequest {
wholeTurns?: boolean;
limit?: number;
}
interface TimelineResponse {
payload: { entries: readonly unknown[] };
}
function fitsFrameBudget(response: TimelineResponse, maxBytes: number): boolean {
const { entries, ...payload } = response.payload;
// Count bytes without constructing an oversized JSON string for the whole turn.
let bytes = Buffer.byteLength(
JSON.stringify({
type: "session",
message: { ...response, payload: { ...payload, entries: [] } },
}),
);
for (const entry of entries) {
bytes += Buffer.byteLength(JSON.stringify(entry)) + 1;
if (bytes > maxBytes) return false;
}
return bytes <= maxBytes;
}
export function selectTimelineResponseWithinFrameBudget<T extends TimelineResponse>(
options: TimelineRequest & { select: (request: TimelineRequest) => T; maxBytes?: number },
): T {
const { select, wholeTurns, maxBytes = TIMELINE_FRAME_BUDGET_BYTES } = options;
let { limit } = options;
const requested = select({ wholeTurns, limit });
// Preserve whole-turn pages that fit and the existing explicit full-read contract.
if (wholeTurns !== true || limit === 0 || fitsFrameBudget(requested, maxBytes)) return requested;
for (;;) {
// Reselect using the original direction and cursor; slicing the old response
// would keep the wrong fences and hide the skipped entries from scrollback.
const page = select({ wholeTurns: false, limit });
if (fitsFrameBudget(page, maxBytes)) return page;
const count = page.payload.entries.length;
const currentLimit = limit ?? count;
if (currentLimit <= 1) {
// A tail page starts at the first row of the source span it lands in, so
// one item whose updates span the page keeps it larger than the limit.
throw new Error(
count > 1
? "One item spans more than the response size limit, so the timeline page cannot shrink."
: "A timeline item exceeds the response size limit.",
);
}
// A smaller limit can return the same rows while it still lands inside a
// span, so keep halving the limit rather than judging progress by row count.
limit = Math.max(1, Math.floor(Math.min(currentLimit, count) / 2));
}
}
+1 -1
View File
@@ -538,7 +538,7 @@ server.addHook("agent.turn.before", async ({ agent, turnId }) => {
## agent.turn.after
A live turn completes, fails, or is canceled. Receives `{ agent, turnId, outcome }`. `outcome.kind` is `completed`, `failed`, or `canceled`. The payload carries no history. Read the turn from the agent's timeline: `refetch({ direction: "tail", limit: 1, wholeTurns: true })` returns the latest turn whole, as below. Keep the entries whose `turnId` equals `event.turnId`, because a turn that starts before your read, such as a follow-up another plugin sent, replaces this one as the latest. The filtered list is empty in that case, and when `event.turnId` is `null`. Plugins built against an older SDK that read `event.timeline` get an empty array.
A live turn completes, fails, or is canceled. Receives `{ agent, turnId, outcome }`. `outcome.kind` is `completed`, `failed`, or `canceled`. The payload carries no history. Read the turn from the agent's timeline: `refetch({ direction: "tail", limit: 1, wholeTurns: true })` returns the latest turn whole, as below, unless the turn is larger than the message limit ([timeline handle](/docs/sdk/reference#timeline-handle)). Keep the entries whose `turnId` equals `event.turnId`, because a turn that starts before your read, such as a follow-up another plugin sent, replaces this one as the latest. The filtered list is empty in that case, and when `event.turnId` is `null`. Plugins built against an older SDK that read `event.timeline` get an empty array.
### Send a follow-up when a turn ends
+1 -1
View File
@@ -527,7 +527,7 @@ server.addHook("agent.turn.before", async ({ agent, turnId }) => {
## agent.turn.after {#agentturnafter}
实时轮次完成、失败或取消后触发,收到 `{ agent, turnId, outcome }`。`outcome.kind` 为 `completed`、`failed` 或 `canceled`。载荷不含历史。请从 Agent 的时间线读取本轮:`refetch({ direction: "tail", limit: 1, wholeTurns: true })` 会完整返回最近一轮,见下面的示例。只保留 `turnId` 等于 `event.turnId` 的条目:如果在读取前已有新一轮开始(例如另一个插件发送的后续消息),最近一轮就不再是本轮。此时过滤后的列表为空;`event.turnId` 为 `null` 时也为空。基于旧版 SDK 构建、仍读取 `event.timeline` 的插件只会拿到空数组。
实时轮次完成、失败或取消后触发,收到 `{ agent, turnId, outcome }`。`outcome.kind` 为 `completed`、`failed` 或 `canceled`。载荷不含历史。请从 Agent 的时间线读取本轮:`refetch({ direction: "tail", limit: 1, wholeTurns: true })` 会完整返回最近一轮,见下面的示例;超过消息上限的轮次除外(见[时间线句柄](/docs/sdk/reference#timeline-handle))。只保留 `turnId` 等于 `event.turnId` 的条目:如果在读取前已有新一轮开始(例如另一个插件发送的后续消息),最近一轮就不再是本轮。此时过滤后的列表为空;`event.turnId` 为 `null` 时也为空。基于旧版 SDK 构建、仍读取 `event.timeline` 的插件只会拿到空数组。
### 在轮次结束时发送后续消息 {#send-a-follow-up-when-a-turn-ends}
+1 -1
View File
@@ -118,7 +118,7 @@ workspace the call creates is background too. With a `parent` and no value, the
### Timeline handle
`agent.timeline.refetch(options?)` fetches a page. Options are `direction`, `cursor`, `limit`, `projection`, `wholeTurns`, and `requestId`. `wholeTurns: true` extends a `tail` or `before` page back to the start of the oldest turn it reaches, so `{ direction: "tail", limit: 1, wholeTurns: true }` returns the latest turn. It requires `features.wholeTurnTimeline`; older hosts ignore it and return a page of `limit` items.
`agent.timeline.refetch(options?)` fetches a page. Options are `direction`, `cursor`, `limit`, `projection`, `wholeTurns`, and `requestId`. `wholeTurns: true` extends a `tail` or `before` page back to the start of the oldest turn it reaches, so `{ direction: "tail", limit: 1, wholeTurns: true }` returns the latest turn. If the complete turns of a page do not fit the 100 MiB message limit, the host returns a page of items with cursors instead, and that page can start partway through a turn. Use `startCursor` with `direction: "before"` to read the rest. It requires `features.wholeTurnTimeline`; older hosts ignore it and return a page of `limit` items.
`agent.timeline.subscribe(handler)` establishes network demand for this agent and restores it after reconnect. Its unsubscribe function releases that demand; await `unsubscribe.ready` for initial daemon acknowledgement before starting work. Delivery is live-only. Reconnect emits a local `subscription_restored` event; request missed history explicitly with `refetch()`. A live replacement invalidates the previous epoch. See the callback shapes, paging and failure behavior in [timeline events](./events.md#follow-timeline-events).
+1 -1
View File
@@ -114,7 +114,7 @@ nav: API 参考
### 时间线句柄 {#timeline-handle}
`agent.timeline.refetch(options?)` 获取一页时间线。选项有 `direction`、`cursor`、`limit`、`projection`、`wholeTurns` 和 `requestId`。`wholeTurns: true` 会把 `tail` 或 `before` 页向前扩展到它所触及的最早一轮的开头,因此 `{ direction: "tail", limit: 1, wholeTurns: true }` 返回最近一轮。它需要 `features.wholeTurnTimeline`;旧版主机会忽略它,返回 `limit` 条记录。
`agent.timeline.refetch(options?)` 获取一页时间线。选项有 `direction`、`cursor`、`limit`、`projection`、`wholeTurns` 和 `requestId`。`wholeTurns: true` 会把 `tail` 或 `before` 页向前扩展到它所触及的最早一轮的开头,因此 `{ direction: "tail", limit: 1, wholeTurns: true }` 返回最近一轮。如果一页的完整轮次超过 100 MiB 消息上限,主机会改为返回带游标的条目页,这一页可能从某一轮的中间开始。用 `startCursor` 和 `direction: "before"` 读取其余部分。它需要 `features.wholeTurnTimeline`;旧版主机会忽略它,返回 `limit` 条记录。
`agent.timeline.subscribe(handler)` 为该 Agent 建立网络订阅需求,并在重连后恢复它。它返回的取消订阅函数会释放这项需求;开始工作之前,请 await `unsubscribe.ready` 以等待 daemon 的初始确认。投递只包含实时内容。重连时会发出一个本地的 `subscription_restored` 事件;错过的历史请用 `refetch()` 显式请求。实时的替换会使之前的 epoch 失效。回调的形状、分页和失败行为见[时间线事件](./events.md#follow-timeline-events)。