The best way to control Claude Code, Codex and more from any computer or phone
fix(server): t3_thread_read returns the newest items and fits in agent context (#33428)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Aviddaram committed
Nov 13, 2026 at 09:08 UTC
59e64eef881632a23f89c4138bcf37f23d92bf93
14 files changed
+318
-73
apps/server/src/mcp/McpHttpServer.test.ts
+3
-3
@@ -696,13 +696,13 @@ it.effect(
696
...thread,
697
limit: 100,
698
runLimit: 50,
699
- maxCharsPerItem: 50_000,
699
+ maxCharsPerItem: 20_000,
700
});
701
yield* callTool("t3_thread_read", { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 });
702
703
expect(calls).toEqual([
704
- { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 },
705
- { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 },
704
+ { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 20_000 },
705
+ { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 20_000 },
706
{ ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 },
707
]);
708
}).pipe(Effect.provide(layerRecordingTools(calls)));
apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
+107
-2
@@ -176,7 +176,8 @@ it("readThread preserves caller access errors and prefers activity-run status ov
176
Layer.provide(
177
Layer.mergeAll(
178
Layer.mock(ThreadManagementService.ThreadManagementService)({
179
- getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
179
+ getTimelinePage: () =>
180
+ Effect.succeed({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }),
181
getThreadRecords: (threadId) =>
182
callerUnavailable
183
? Effect.fail(
@@ -328,6 +329,7 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn
329
) as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"],
330
totalItems: rows.length,
331
hasMore: remaining.length > options.limit,
332
+ hasEarlier: false,
333
});
334
},
335
getThreadRecords: () => Effect.succeed(projection),
@@ -390,6 +392,107 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn
392
}).pipe(Effect.provide(layer), Effect.runPromise);
393
});
394
395
+it("readThread returns the newest items that fit the response budget", async () => {
396
+ const projection = {
397
+ thread: baseThread({
398
+ threadId: parentThreadId,
399
+ title: "Parent",
400
+ instanceId: parentInstanceId,
401
+ model: "gpt-5.4",
402
+ }),
403
+ runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
404
+ visibleTurnItems: [],
405
+ providerTurns: [],
406
+ runtimeRequests: [],
407
+ messages: [],
408
+ contextTransfers: [],
409
+ subagents: [],
410
+ updatedAt: now,
411
+ } as unknown as OrchestrationV2ThreadProjection;
412
+ // A long thread's newest 100 activity items, the read agents make most.
413
+ const rows = Array.from({ length: 100 }, (_, position) => ({
414
+ position,
415
+ visibility: "local",
416
+ sourceThreadId: parentThreadId,
417
+ sourceItemId: TurnItemId.make(`turn-item-mcp-long-${position}`),
418
+ item: {
419
+ type: "reasoning",
420
+ runId: activeRunId,
421
+ status: "completed",
422
+ title: null,
423
+ text: "x".repeat(1_500),
424
+ updatedAt: now,
425
+ },
426
+ }));
427
+ const pageOptions: Array<unknown> = [];
428
+
429
+ const layer = layerOrchestratorService.pipe(
430
+ Layer.provide(
431
+ Layer.mergeAll(
432
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
433
+ getTimelinePage: (_threadId, options) => {
434
+ pageOptions.push(options);
435
+ return Effect.succeed({
436
+ items: rows as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"],
437
+ totalItems: 3_000,
438
+ hasMore: false,
439
+ hasEarlier: true,
440
+ });
441
+ },
442
+ getThreadRecords: () => Effect.succeed(projection),
443
+ getProjectThreadRecords: () => Effect.succeed(projection),
444
+ getThreadShell: () =>
445
+ Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
446
+ } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
447
+ ServerSettings.layerTest(),
448
+ Layer.mock(ProviderRegistry.ProviderRegistry)({
449
+ getProviders: Effect.succeed([]),
450
+ } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
451
+ Layer.mock(ProjectService.ProjectService)({}),
452
+ Layer.mock(SecretRequests.SecretRequests)({}),
453
+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),
454
+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({
455
+ list: () => Effect.succeed({ tasks: [] }),
456
+ } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
457
+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
458
+ list: () => Effect.succeed([]),
459
+ } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
460
+ NodeCrypto.layer,
461
+ ),
462
+ ),
463
+ );
464
+
465
+ await Effect.gen(function* () {
466
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
467
+ const read = {
468
+ threadId: parentThreadId,
469
+ view: "activity" as const,
470
+ limit: 100,
471
+ maxCharsPerItem: 1_500,
472
+ };
473
+ const result = yield* service.readThread(makeScope(), read);
474
+ // Linked environments and the CLI read as clients without a cursor and follow only hasMore.
475
+ const first = yield* service.readThread({ ...makeScope(), thread: undefined }, read);
476
+ const fromStart = yield* service.readThread(makeScope(), { ...read, afterPosition: -1 });
477
+
478
+ expect(pageOptions).toEqual([
479
+ { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" },
480
+ { limit: 100, view: "activity" },
481
+ { afterPosition: -1, limit: 100, view: "activity" },
482
+ ]);
483
+ // Claude Code saves results over ~50k chars of this JSON to a file instead of showing them.
484
+ expect(JSON.stringify(result).length).toBeLessThan(31_000);
485
+ expect(result.items.length).toBeLessThan(100);
486
+ expect(result.items.at(-1)?.position).toBe(99);
487
+ expect(result.earlierPosition).toBe(result.items[0]?.position);
488
+ expect(result.hasMore).toBe(false);
489
+ expect(first.items[0]?.position).toBe(0);
490
+ expect(first.hasMore).toBe(true);
491
+ expect(first.nextPosition).toBe(first.items.at(-1)?.position);
492
+ expect(fromStart.items[0]?.position).toBe(0);
493
+ }).pipe(Effect.provide(layer), Effect.runPromise);
494
+});
495
+
496
it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
497
const parentProjection = {
498
thread: baseThread({
@@ -474,7 +577,8 @@ it("taskStatus returns task.providerInstanceId rather than the driver kind", asy
577
Layer.provide(
578
Layer.mergeAll(
579
Layer.mock(ThreadManagementService.ThreadManagementService)({
477
- getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
580
+ getTimelinePage: () =>
581
+ Effect.succeed({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }),
582
getThreadRecords: (threadId) => {
583
if (threadId === parentThreadId) return Effect.succeed(parentProjection);
584
if (threadId === childThreadId) return Effect.succeed(childProjection);
@@ -595,6 +699,7 @@ it("readThread and sendToThread reach threads in other projects", async () => {
699
items: foreignProjection(threadId).visibleTurnItems,
700
totalItems: 1,
701
hasMore: false,
702
+ hasEarlier: false,
703
}),
704
getProjectThreadRecords: (input) =>
705
input.threadId === foreignThreadId && input.projectId === foreignProjectId
apps/server/src/mcp/OrchestratorMcpService.ts
+52
-26
@@ -146,6 +146,10 @@ const DEFAULT_THREAD_LIST_LIMIT = 10;
146
const DEFAULT_THREAD_READ_LIMIT = 10;
147
const DEFAULT_THREAD_RUN_LIMIT = 10;
148
const DEFAULT_THREAD_ITEM_MAX_CHARS = 500;
149
+// Claude Code saves MCP results over ~25k tokens to a file instead of showing them. Thread JSON
150
+// runs about 2 chars per token, so a read stops adding items here and reports the rest as more.
151
+const THREAD_READ_BUDGET_CHARS = 30_000;
152
+const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
153
154
interface ResolvedTarget {
155
readonly modelSelection: ModelSelection;
@@ -3061,20 +3065,25 @@ const make = Effect.gen(function* () {
3065
readThread: Effect.fn("OrchestratorMcpService.readThread")(function* (scope, input) {
3066
const { parent, target, shell } = yield* loadReadableThread(scope, input.threadId);
3067
const view = input.view ?? "messages";
3064
- const afterPosition = input.afterPosition ?? -1;
3068
const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;
3069
const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;
3070
+ // Client callers (the CLI, older linked environments) page forward from a cursorless read.
3071
+ const newestFirst =
3072
+ input.beforePosition !== undefined ||
3073
+ (input.afterPosition === undefined && scope.thread !== undefined);
3074
const timeline = yield* threadManagement
3075
.getTimelinePage(input.threadId, {
3069
- afterPosition,
3076
+ ...(input.afterPosition === undefined ? {} : { afterPosition: input.afterPosition }),
3077
+ ...(newestFirst
3078
+ ? { beforePosition: input.beforePosition ?? Number.POSITIVE_INFINITY }
3079
+ : {}),
3080
limit,
3081
view,
3082
...(input.itemId === undefined ? {} : { itemId: input.itemId }),
3083
})
3084
.pipe(Effect.mapError(threadManagementFailure));
3075
- const page = timeline.items;
3085
const messageIdsByThread = new Map<ThreadId, Array<MessageId>>();
3077
- for (const row of page) {
3086
+ for (const row of timeline.items) {
3087
if (row.item.type !== "user_message" && row.item.type !== "assistant_message") continue;
3088
const ids = messageIdsByThread.get(row.sourceThreadId) ?? [];
3089
ids.push(row.item.messageId);
@@ -3090,6 +3099,39 @@ const make = Effect.gen(function* () {
3099
{ concurrency: 1 },
3100
);
3101
const messagesByThreadId = new Map(sourceMessages);
3102
+ const thread = threadDetail(
3103
+ scope,
3104
+ target,
3105
+ timeline.totalItems,
3106
+ shell,
3107
+ yield* Clock.currentTimeMillis,
3108
+ input.afterPosition === undefined &&
3109
+ input.beforePosition === undefined &&
3110
+ input.itemId === undefined,
3111
+ );
3112
+ const recentRuns = target.runs
3113
+ .toSorted((left, right) => right.ordinal - left.ordinal)
3114
+ .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)
3115
+ .map((run) => threadRun(target, run));
3116
+ const allItems = timeline.items.map((row) =>
3117
+ timelineItem({
3118
+ row,
3119
+ maxChars,
3120
+ messagesByThreadId,
3121
+ ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }),
3122
+ }),
3123
+ );
3124
+ // Keep the end of the page the caller is reading toward, and at least one item.
3125
+ let size = encodeJsonText({ thread, recentRuns }).length;
3126
+ let kept = 0;
3127
+ for (const item of newestFirst ? allItems.toReversed() : allItems) {
3128
+ size += encodeJsonText(item).length + 1;
3129
+ if (kept > 0 && size > THREAD_READ_BUDGET_CHARS) break;
3130
+ kept++;
3131
+ }
3132
+ const start = newestFirst ? allItems.length - kept : 0;
3133
+ const items = allItems.slice(start, start + kept);
3134
+ const page = timeline.items.slice(start, start + kept);
3135
const returnedRunIds = new Set(
3136
page.filter((row) => row.sourceThreadId === target.thread.id).map((row) => row.item.runId),
3137
);
@@ -3141,28 +3183,12 @@ const make = Effect.gen(function* () {
3183
}
3184
}
3185
return {
3144
- thread: threadDetail(
3145
- scope,
3146
- target,
3147
- timeline.totalItems,
3148
- shell,
3149
- yield* Clock.currentTimeMillis,
3150
- input.afterPosition === undefined && input.itemId === undefined,
3151
- ),
3152
- recentRuns: target.runs
3153
- .toSorted((left, right) => right.ordinal - left.ordinal)
3154
- .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)
3155
- .map((run) => threadRun(target, run)),
3156
- items: page.map((row) =>
3157
- timelineItem({
3158
- row,
3159
- maxChars,
3160
- messagesByThreadId,
3161
- ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }),
3162
- }),
3163
- ),
3164
- nextPosition: page.at(-1)?.position ?? null,
3165
- hasMore: timeline.hasMore,
3186
+ thread,
3187
+ recentRuns,
3188
+ items,
3189
+ nextPosition: items.at(-1)?.position ?? null,
3190
+ hasMore: timeline.hasMore || (!newestFirst && kept < allItems.length),
3191
+ earlierPosition: timeline.hasEarlier || start > 0 ? (items[0]?.position ?? null) : null,
3192
} satisfies OrchestratorMcpThreadReadResult;
3193
}),
3194
sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) {
apps/server/src/mcp/toolkits/core.test.ts
+2
-1
@@ -1114,7 +1114,8 @@ it.effect("discovers workflow stop targets and requires orchestration capability
1114
getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)),
1115
getProjectThreadRecords: () =>
1116
Effect.succeed(McpToolAccessTestkit.idleThreadProjection(shell)),
1117
- getTimelinePage: () => Effect.succeed({ items: [row], totalItems: 1, hasMore: false }),
1117
+ getTimelinePage: () =>
1118
+ Effect.succeed({ items: [row], totalItems: 1, hasMore: false, hasEarlier: false }),
1119
stopWorkflow: (input) =>
1120
Effect.sync(() => {
1121
stopped.push(input);
apps/server/src/mcp/toolkits/orchestrator/tools.test.ts
+1
-1
@@ -11,7 +11,7 @@ it("states t3_thread_read page size limits in the parameter descriptions", () =>
11
const schema = Tool.getJsonSchema(OrchestratorToolkit.tools.t3_thread_read) as {
12
readonly properties: Readonly<Record<string, { readonly description?: string }>>;
13
};
14
- const limits = { limit: "100", runLimit: "50", maxCharsPerItem: "50000" };
14
+ const limits = { limit: "100", runLimit: "50", maxCharsPerItem: "20000" };
15
for (const [name, maximum] of Object.entries(limits)) {
16
expect(schema.properties[name]?.description, name).toContain(maximum);
17
}
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+1
-1
@@ -245,7 +245,7 @@ const ThreadListTool = Tool.make("t3_thread_list", {
245
246
const ThreadReadTool = Tool.make("t3_thread_read", {
247
description:
248
- "Read any thread by id. `messages` (default): user and assistant messages and plans. `activity`: all timeline items. Keep reads small: low `limit` and `maxCharsPerItem`. Page with `afterPosition=nextPosition`. Cut-off text: `itemId` with `textOffset=nextTextOffset`. Reading a child's final result marks it delivered. In your reply, name it as its `link` verbatim.",
248
+ "Read any thread by id. View `messages` (default) or `activity` (all items). Newest first; older: `beforePosition=earlierPosition`; from the start: `afterPosition=-1`, then `nextPosition`. Cut-off text: `itemId`, `textOffset=nextTextOffset`. Reading a child's final result marks it delivered. In your reply, name it as its `link` verbatim.",
249
parameters: OrchestratorMcpThreadReadInput,
250
success: OrchestratorMcpThreadReadResult,
251
failure: OrchestratorMcpFailure,
apps/server/src/orchestration-v2/ContextHandoffDelivery.ts
+1
-1
@@ -44,7 +44,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
44
(handoff) =>
45
`Context handoff (${handoff.strategy === "fork_delta_summary" ? "merge_back / fork_delta_summary" : handoff.strategy}):\n${
46
handoff.history?.coverage ??
47
- `From thread ${handoff.threadId}, runs ${handoff.coveredRunOrdinals.from}-${handoff.coveredRunOrdinals.to}. Recover history with t3_thread_read, view=activity; paginate with afterPosition, and use itemId/textOffset for long items.`
47
+ `From thread ${handoff.threadId}, runs ${handoff.coveredRunOrdinals.from}-${handoff.coveredRunOrdinals.to}. Recover history with t3_thread_read, view=activity, afterPosition=-1; paginate with afterPosition=nextPosition, and use itemId/textOffset for long items.`
48
}`,
49
)
50
.join("\n");
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+24
@@ -6104,6 +6104,13 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
6104
for (const view of ["messages", "activity"] as const) {
6105
for (const afterPosition of [-1, Math.floor(totalItems / 3), totalItems - 5])
6106
yield* windowed(timeline({ view, afterPosition, limit: 20 }));
6107
+ for (const beforePosition of [
6108
+ Number.POSITIVE_INFINITY,
6109
+ Math.floor(totalItems / 3),
6110
+ totalItems - 5,
6111
+ ])
6112
+ yield* windowed(timeline({ view, beforePosition, limit: 20 }));
6113
+ yield* windowed(timeline({ view, afterPosition: 3, beforePosition: 40, limit: 20 }));
6114
}
6115
for (const itemId of [newest.sourceItemId, ...tiedWithHidden])
6116
yield* windowed(timeline({ itemId, limit: 1 }));
@@ -9834,6 +9841,23 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
9841
});
9842
assert.deepEqual(followingPage.items, targetAfterRollback.visibleTurnItems.slice(2));
9843
assert.isFalse(followingPage.hasMore);
9844
+ assert.isTrue(followingPage.hasEarlier);
9845
+ const newestPage = yield* projectionStore.getTimelinePage(targetThreadId, {
9846
+ view: "activity",
9847
+ limit: 2,
9848
+ beforePosition: Number.POSITIVE_INFINITY,
9849
+ });
9850
+ assert.deepEqual(newestPage.items, targetAfterRollback.visibleTurnItems.slice(-2));
9851
+ assert.isFalse(newestPage.hasMore);
9852
+ assert.isTrue(newestPage.hasEarlier);
9853
+ const earlierPage = yield* projectionStore.getTimelinePage(targetThreadId, {
9854
+ view: "activity",
9855
+ limit: 10,
9856
+ beforePosition: newestPage.items[0]!.position,
9857
+ });
9858
+ assert.deepEqual(earlierPage.items, targetAfterRollback.visibleTurnItems.slice(0, -2));
9859
+ assert.isTrue(earlierPage.hasMore);
9860
+ assert.isFalse(earlierPage.hasEarlier);
9861
const tracedTimelinePage = (limit: number) =>
9862
Effect.gen(function* () {
9863
const { statements, tracer } = traceSqlStatements();
apps/server/src/orchestration-v2/ProjectionStore.ts
+106
-25
@@ -422,8 +422,13 @@ export type ProjectionRecords<K extends ProjectionRecordField> = Pick<
422
"thread" | K
423
>;
424
425
+/**
426
+ * A page holds the oldest matches after `afterPosition`, or with `beforePosition`,
427
+ * the newest matches before it. `itemId` ignores both bounds.
428
+ */
429
export interface ProjectionTimelinePageOptions {
430
readonly afterPosition?: number;
431
+ readonly beforePosition?: number;
432
readonly itemId?: TurnItemId;
433
readonly attachmentId?: string;
434
readonly view?: "messages" | "activity";
@@ -432,7 +437,10 @@ export interface ProjectionTimelinePageOptions {
437
export interface ProjectionTimelinePage {
438
readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
439
readonly totalItems: number;
440
+ /** Matches exist after the page. */
441
readonly hasMore: boolean;
442
+ /** Matches exist before the page. */
443
+ readonly hasEarlier: boolean;
444
}
445
446
export interface ShellSnapshotOptions {
@@ -7183,12 +7191,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7191
const matchLocalTimelineRows = Effect.fn("ProjectionStore.matchLocalTimelineRows")(function* (
7192
local: LocalTimeline,
7193
options: ProjectionTimelinePageOptions,
7194
+ totalItems: number,
7195
) {
7196
const threadId = local.records.thread.id;
7188
- const totals = yield* sql<{ count: number }>`
7189
- SELECT COUNT(*) AS count FROM orchestration_v2_projection_turn_items
7190
- WHERE thread_id = ${threadId}`;
7191
- const totalItems = (totals[0]?.count ?? 0) - local.hidden.length;
7197
if (options.itemId !== undefined) {
7198
const found = (yield* local.read(sql`AND item.turn_item_id = ${options.itemId}`)).filter(
7199
local.isVisible,
@@ -7198,7 +7203,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7203
.visibleBefore(item.ordinal, item.id)
7204
.pipe(Effect.map((position) => ({ ...localTimelineRow(item), position }))),
7205
);
7201
- return { matching, totalItems };
7206
+ return { matching, totalItems, hasEarlier: false };
7207
}
7208
const afterPosition = options.afterPosition ?? -1;
7209
const firstPosition = Math.max(afterPosition + 1, 0);
@@ -7209,7 +7214,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7214
WHERE thread_id = ${threadId}
7215
ORDER BY ordinal ASC, turn_item_id ASC LIMIT 1 OFFSET ${firstPosition}`;
7216
const start = starts[0]?.ordinal;
7212
- if (start === undefined) return { matching: [], totalItems };
7217
+ if (start === undefined) return { matching: [], totalItems, hasEarlier: false };
7218
const base = yield* local.visibleBefore(start);
7219
const hiddenAfter = local.hidden.filter((row) => row.ordinal >= start).length;
7220
const messagesOnly = options.view !== "activity";
@@ -7233,13 +7238,69 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7238
positions.set(row.turn_item_id, base + positions.size);
7239
}
7240
}
7236
- const matching = candidates
7237
- .map((item, offset) => ({
7238
- ...localTimelineRow(item),
7239
- position: messagesOnly ? (positions.get(item.id) ?? -1) : base + offset,
7240
- }))
7241
- .filter((row) => row.position > afterPosition);
7242
- return { matching, totalItems };
7241
+ const rows = candidates.map((item, offset) => ({
7242
+ ...localTimelineRow(item),
7243
+ position: messagesOnly ? (positions.get(item.id) ?? -1) : base + offset,
7244
+ }));
7245
+ const matching = rows.filter((row) => row.position > afterPosition);
7246
+ // At most `hidden.length` of the first matches before the start are hidden.
7247
+ const hasEarlier =
7248
+ matching.length < rows.length ||
7249
+ (base > 0 &&
7250
+ (!messagesOnly ||
7251
+ (yield* local.read(
7252
+ sql`AND item.ordinal < ${start}
7253
+ AND item.type IN ('user_message', 'assistant_message', 'proposed_plan')`,
7254
+ sql`LIMIT ${local.hidden.length + 1}`,
7255
+ )).some(local.isVisible)));
7256
+ return { matching, totalItems, hasEarlier };
7257
+ });
7258
+
7259
+ /**
7260
+ * A `getTimelinePage` page from `matchLocalTimelineRows`. A backward page reads forward from
7261
+ * ever earlier starts until it holds `limit` matches or reaches `afterPosition`.
7262
+ */
7263
+ const readLocalTimelinePage = Effect.fn("ProjectionStore.readLocalTimelinePage")(function* (
7264
+ local: LocalTimeline,
7265
+ options: ProjectionTimelinePageOptions,
7266
+ ) {
7267
+ const totals = yield* sql<{ count: number }>`
7268
+ SELECT COUNT(*) AS count FROM orchestration_v2_projection_turn_items
7269
+ WHERE thread_id = ${local.records.thread.id}`;
7270
+ const totalItems = (totals[0]?.count ?? 0) - local.hidden.length;
7271
+ if (options.beforePosition === undefined || options.itemId !== undefined) {
7272
+ const { matching, hasEarlier } = yield* matchLocalTimelineRows(local, options, totalItems);
7273
+ return {
7274
+ page: matching.slice(0, options.limit),
7275
+ totalItems,
7276
+ hasMore: matching.length > options.limit,
7277
+ hasEarlier,
7278
+ };
7279
+ }
7280
+ const afterPosition = options.afterPosition ?? -1;
7281
+ const end = Math.min(options.beforePosition, totalItems);
7282
+ let span = Math.max(options.limit, 1);
7283
+ while (true) {
7284
+ // The `span` positions before `end` hold at most `span` matches, so a forward read of
7285
+ // `span + 1` from the start holds all of them and shows whether any follow.
7286
+ const from = Math.max(afterPosition, end - span - 1);
7287
+ const read = yield* matchLocalTimelineRows(
7288
+ local,
7289
+ { ...options, afterPosition: from, limit: span },
7290
+ totalItems,
7291
+ );
7292
+ const before = read.matching.filter((row) => row.position < end);
7293
+ if (before.length >= options.limit || from === afterPosition) {
7294
+ const page = before.slice(Math.max(0, before.length - options.limit));
7295
+ return {
7296
+ page,
7297
+ totalItems,
7298
+ hasMore: read.matching.length > before.length,
7299
+ hasEarlier: read.hasEarlier || before.length > page.length,
7300
+ };
7301
+ }
7302
+ span *= 2;
7303
+ }
7304
});
7305
7306
const getTimelinePage: ProjectionStoreV2Shape["getTimelinePage"] = (threadId, options) =>
@@ -7250,7 +7311,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7311
options.attachmentId === undefined &&
7312
Number.isSafeInteger(options.limit) &&
7313
options.limit >= 0 &&
7253
- Number.isSafeInteger(options.afterPosition ?? -1)
7314
+ Number.isSafeInteger(options.afterPosition ?? -1) &&
7315
+ (options.beforePosition === undefined ||
7316
+ options.beforePosition === Number.POSITIVE_INFINITY ||
7317
+ Number.isSafeInteger(options.beforePosition))
7318
? yield* openLocalTimeline(threadId)
7319
: null;
7320
const whole = Effect.gen(function* () {
@@ -7269,26 +7333,43 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7333
(row) => `${row.thread_id}:${row.turn_item_id}`,
7334
),
7335
);
7272
- const matching = index.visible
7336
+ const inView = index.visible
7337
.map((row, position) => ({ ...row, position }))
7338
.filter((row) =>
7339
options.itemId === undefined
7276
- ? row.position > (options.afterPosition ?? -1) &&
7277
- (options.view === "activity" ||
7278
- ["user_message", "assistant_message", "proposed_plan"].includes(
7279
- row.item.type,
7280
- ))
7340
+ ? options.view === "activity" ||
7341
+ ["user_message", "assistant_message", "proposed_plan"].includes(row.item.type)
7342
: row.sourceItemId === options.itemId,
7343
)
7344
.filter(
7345
(row) =>
7346
attachmentOwners?.has(`${row.sourceThreadId}:${row.sourceItemId}`) ?? true,
7347
);
7287
- return { matching, totalItems: index.visible.length };
7348
+ const before = options.beforePosition ?? Number.POSITIVE_INFINITY;
7349
+ const matching =
7350
+ options.itemId === undefined
7351
+ ? inView.filter(
7352
+ (row) =>
7353
+ row.position > (options.afterPosition ?? -1) && row.position < before,
7354
+ )
7355
+ : inView;
7356
+ const page =
7357
+ options.beforePosition === undefined
7358
+ ? matching.slice(0, options.limit)
7359
+ : matching.slice(Math.max(0, matching.length - options.limit));
7360
+ const pageStart = page[0]?.position ?? (options.afterPosition ?? -1) + 1;
7361
+ return {
7362
+ page,
7363
+ totalItems: index.visible.length,
7364
+ hasMore:
7365
+ options.beforePosition === undefined
7366
+ ? matching.length > page.length
7367
+ : (inView.at(-1)?.position ?? -1) >= before,
7368
+ hasEarlier: (inView[0]?.position ?? Number.POSITIVE_INFINITY) < pageStart,
7369
+ };
7370
});
7289
- const { matching, totalItems } =
7290
- local === null ? yield* whole : yield* matchLocalTimelineRows(local, options);
7291
- const page = matching.slice(0, options.limit);
7371
+ const { page, totalItems, hasMore, hasEarlier } =
7372
+ local === null ? yield* whole : yield* readLocalTimelinePage(local, options);
7373
const sources = yield* encodeTimelineSources(
7374
page
7375
.filter((row) => row.synthetic === undefined)
@@ -7337,7 +7418,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7418
};
7419
}),
7420
);
7340
- return { items, totalItems, hasMore: matching.length > page.length };
7421
+ return { items, totalItems, hasMore, hasEarlier };
7422
}),
7423
)
7424
.pipe(
apps/server/src/peer/RemoteDelegation.test.ts
+1
@@ -469,6 +469,7 @@ const boxToolkitLayer = (thread: BoxThread) => {
469
options.itemId === undefined &&
470
matching.length > 0 &&
471
visible.some((entry) => entry.position > matching.at(-1)!.position),
472
+ hasEarlier: false,
473
};
474
}),
475
interruptThread: (input) =>
apps/server/src/peer/RemoteDelegation.ts
+1
-1
@@ -639,7 +639,7 @@ const make = Effect.gen(function* () {
639
threadId: remote.threadId,
640
itemId: reply.itemId,
641
textOffset,
642
- maxCharsPerItem: 50_000,
642
+ maxCharsPerItem: 20_000,
643
});
644
const part = rest.items[0];
645
if (part === undefined) break;
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 5597,
3
"codexAdditionalContextBytes": 7327,
4
- "mcpToolListJsonBytes": 48126
4
+ "mcpToolListJsonBytes": 48099
5
}
docs/orchestration-v2/orchestrator-mcp-server.md
+10
-2
@@ -400,8 +400,16 @@ the environment by thread ID. A deleted thread returns `thread_not_found`. The
400
default `messages` view returns user messages, assistant
401
messages, and proposed plans. The `activity` view also returns summarized tool,
402
reasoning, checkpoint, handoff, and runtime-request items. Large item text is
403
-bounded and reports whether it was truncated. `afterPosition` and
404
-`nextPosition` support incremental reads.
403
+bounded and reports whether it was truncated. An agent in a T3 thread that
404
+reads without a cursor gets the newest items, and `beforePosition=earlierPosition`
405
+reads older ones. Client callers (the CLI, linked environments, outside MCP
406
+clients) start at the oldest item instead, because the CLI and linked
407
+environments on older versions read that way and follow only `hasMore`.
408
+`afterPosition=-1` starts any read at the oldest item, and
409
+`afterPosition=nextPosition` reads newer items. The server stops adding items once the result reaches about 30,000 characters and
410
+reports the rest through `earlierPosition` or `hasMore`. Claude Code saves MCP
411
+results over its token limit to a file instead of showing them, so a read has
412
+to fit whatever `limit` an agent asks for.
413
414
Thread and message results include required `createdBy` and `creationSource`
415
provenance. MCP-created threads and user-role messages use `createdBy: "agent"`
packages/contracts/src/orchestratorMcp.ts
+8
-9
@@ -436,15 +436,12 @@ export const OrchestratorMcpThreadReadInput = Schema.Struct({
436
itemId: Schema.optional(TurnItemId),
437
textOffset: Schema.optional(NonNegativeInt),
438
view: Schema.optional(Schema.Literals(["messages", "activity"])),
439
- afterPosition: Schema.optional(NonNegativeInt),
440
- limit: Schema.optional(clampedPositiveInt(100)).annotate({
441
- description: "Max items, 1 to 100.",
442
- }),
443
- runLimit: Schema.optional(clampedPositiveInt(50)).annotate({
444
- description: "Max recent runs, 1 to 50.",
445
- }),
446
- maxCharsPerItem: Schema.optional(clampedPositiveInt(50_000)).annotate({
447
- description: "Max chars per item, 1 to 50000.",
439
+ afterPosition: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(-1))),
440
+ beforePosition: Schema.optional(NonNegativeInt),
441
+ limit: Schema.optional(clampedPositiveInt(100)).annotate({ description: "Max 100." }),
442
+ runLimit: Schema.optional(clampedPositiveInt(50)).annotate({ description: "Max 50." }),
443
+ maxCharsPerItem: Schema.optional(clampedPositiveInt(20_000)).annotate({
444
+ description: "Max 20000.",
445
}),
446
});
447
export type OrchestratorMcpThreadReadInput = typeof OrchestratorMcpThreadReadInput.Type;
@@ -530,6 +527,8 @@ export const OrchestratorMcpThreadReadResult = Schema.Struct({
527
items: Schema.Array(OrchestratorMcpThreadTimelineItem),
528
nextPosition: Schema.NullOr(NonNegativeInt),
529
hasMore: Schema.Boolean,
530
+ /** null when nothing is older than the page. Missing from peers that only read forward. */
531
+ earlierPosition: Schema.optional(Schema.NullOr(NonNegativeInt)),
532
});
533
export type OrchestratorMcpThreadReadResult = typeof OrchestratorMcpThreadReadResult.Type;
534