Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion apps/server/src/cli/thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,13 @@ const threadListCommand = Command.make("list", {
while (cursor !== null) {
const page: OrchestratorMcpThreadListResult = yield* tools.call(
"t3_thread_list",
{ projectId: project.id, includeSubagents: false, limit: 100, cursor },
{
projectId: project.id,
includeSubagents: false,
limit: 100,
cursor,
detail: flags.json,
},
OrchestratorMcpThreadListResult,
);
threads.push(...page.threads);
Expand Down
50 changes: 49 additions & 1 deletion apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ import * as WorktreeMcpService from "./WorktreeMcpService.ts";
import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts";
import * as T4Handlers from "./toolkits/t4/handlers.ts";
import { T4Toolkit } from "./toolkits/t4/tools.ts";
import * as ToolCallLog from "../t4/toolCallLog.ts";
import * as T4Store from "../t4/T4Store.ts";
import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
import * as DeviceHandlers from "./toolkits/device/handlers.ts";
import {
Expand Down Expand Up @@ -1136,6 +1138,50 @@ const withAdvertisedSchemas = Effect.fn("McpHttpServer.withAdvertisedSchemas")(f
return yield* registration.pipe(Effect.provideService(McpServer.McpServer, advertisingServer));
});

/**
* t4 fork: write calls a restart can cut are logged as they start and end, so the restart note
* tells the agent which went through (t4/toolCallLog.ts, AI-93).
*/
const withT4CallLog = Effect.fn("McpHttpServer.withT4CallLog")(function* <A, E, R>(
registration: Effect.Effect<A, E, R>,
) {
const server = yield* McpServer.McpServer;
const store = Option.getOrUndefined(yield* Effect.serviceOption(T4Store.T4Store));
if (store === undefined) return yield* registration;
const loggingServer = McpServer.McpServer.of({
...server,
addTool: Effect.fn("McpServer.addTool")(function (options) {
if (!ToolCallLog.LOGGED_TOOLS.has(options.tool.name)) return server.addTool(options);
return server.addTool({
...options,
handle: (payload) =>
Effect.serviceOption(McpInvocationContext.McpInvocationContext).pipe(
Effect.flatMap((invocation) => {
const threadId = Option.getOrUndefined(invocation)?.thread?.threadId;
return threadId === undefined
? options.handle(payload)
: ToolCallLog.logged(
store,
{ threadId, tool: options.tool.name, args: payload },
options.handle(payload),
(result) =>
result instanceof McpSchema.InputRequired
? "asked for input"
: toolOutcome(result).outcome === "ok"
? "done"
: `failed: ${String(
(result.content[0] as { readonly text?: unknown } | undefined)
?.text ?? "",
).slice(0, 120)}`,
);
}),
),
});
}),
});
return yield* registration.pipe(Effect.provideService(McpServer.McpServer, loggingServer));
});

/** Hands each call the services its registration was built with; the request's own still win. */
const provideRegistrationServices = <Services>() =>
McpServer.middleware<{ provides: Services }>()(
Expand All @@ -1160,7 +1206,9 @@ export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX,
Layer.effectDiscard(
withToolAnalytics(
withToolSpans(
withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
withT4CallLog(
withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
),
),
),
).pipe(
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,9 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn
text,
textTruncated: index < expected.length - 1,
nextTextOffset: index < expected.length - 1 ? textOffset : null,
...(index < expected.length - 1 ? { remainingChars: "a😀bc".length - textOffset } : {}),
});
expect("remainingChars" in result.items[0]!).toBe(index < expected.length - 1);
}
}
}).pipe(Effect.provide(layer), Effect.runPromise);
Expand Down
6 changes: 5 additions & 1 deletion apps/server/src/mcp/OrchestratorMcpService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3591,10 +3591,14 @@ describe("OrchestratorMcpService thread list", () => {
allProjects: true,
projectId: ProjectId.make("project:a"),
snoozed: true,
detail: true,
});
assert.equal(listed.projectId, null);
assert.deepStrictEqual(
listed.threads.map((thread) => [thread.threadId, thread.projectId]),
listed.threads.map((thread): ReadonlyArray<string | undefined> => [
thread.threadId,
thread.projectId,
]),
[
["thread:a-snoozed", "project:a"],
["thread:b-snoozed", "project:b"],
Expand Down
108 changes: 92 additions & 16 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
type OrchestratorMcpRequestSecretInput,
type OrchestratorMcpRequestSecretResult,
type OrchestratorMcpDeleteScheduledTaskResult,
type OrchestratorMcpListScheduledTasksResult,
type OrchestratorMcpScheduledTaskRow,
type OrchestratorMcpScheduledTask,
type OrchestratorMcpScheduleTaskInput,
type OrchestratorMcpScheduleTaskResult,
Expand Down Expand Up @@ -164,7 +164,9 @@ const secretRequestResult = (
const DEFAULT_THREAD_LIST_LIMIT = 50;
const DEFAULT_THREAD_READ_LIMIT = 50;
const DEFAULT_THREAD_RUN_LIMIT = 10;
const DEFAULT_THREAD_ITEM_MAX_CHARS = 20_000;
// t4 fork (AI-93): long items cost agents their context; a cut item says how to read on.
const DEFAULT_THREAD_ITEM_MAX_CHARS = 1_500;
const SCHEDULED_TASK_PROMPT_PREVIEW_CHARS = 120;

interface ResolvedTarget {
readonly modelSelection: ModelSelection;
Expand Down Expand Up @@ -204,7 +206,10 @@ export interface OrchestratorMcpServiceShape {
readonly listScheduledTasks: (
scope: McpInvocationScope,
input: OrchestratorMcpListScheduledTasksInput,
) => Effect.Effect<OrchestratorMcpListScheduledTasksResult, OrchestratorMcpFailure>;
) => Effect.Effect<
{ readonly tasks: ReadonlyArray<OrchestratorMcpScheduledTask> },
OrchestratorMcpFailure
>;
readonly updateScheduledTask: (
scope: McpInvocationScope,
input: OrchestratorMcpUpdateScheduledTaskInput,
Expand Down Expand Up @@ -640,6 +645,7 @@ function pageIncludesTerminalTaskResult(input: {
"thread" | "runs" | "contextTransfers" | "messages" | "turnItems" | "providerTurns"
>;
readonly maxChars: number;
readonly textOffset: number;
}): boolean {
const transfer = taskResultTransfer(input.parentThreadId, input.target, input.task);
if (transfer === undefined) return false;
Expand All @@ -662,7 +668,7 @@ function pageIncludesTerminalTaskResult(input: {
if (!matchesResult) return false;

const text = turnItemText(row.item);
return text !== null && text.length <= textPageEnd(text, 0, input.maxChars);
return text !== null && text.length <= textPageEnd(text, input.textOffset, input.maxChars);
});
}

Expand Down Expand Up @@ -785,7 +791,7 @@ function threadTitle(input: {

function threadSettlement(
thread: Pick<OrchestrationV2ThreadShell, "settledOverride" | "settledAt">,
): Pick<OrchestratorMcpThreadListItem, "settled" | "settledAt"> {
): Pick<OrchestratorMcpThreadDetail, "settled" | "settledAt"> {
const settled = thread.settledOverride === "settled";
return {
settled,
Expand All @@ -796,7 +802,7 @@ function threadSettlement(
function threadSnooze(
thread: Parameters<typeof isSnoozed>[0],
nowMs: number,
): Pick<OrchestratorMcpThreadListItem, "snoozed" | "snoozedUntil"> {
): Pick<OrchestratorMcpThreadDetail, "snoozed" | "snoozedUntil"> {
const snoozed = isSnoozed(thread, nowMs);
return {
snoozed,
Expand Down Expand Up @@ -831,6 +837,62 @@ function threadPullRequest(
};
}

/** t4 fork (AI-93): what agents pick a thread by; `detail: true` gives the full row. */
function compactListItemFromShell(
scope: McpInvocationScope,
shell: OrchestrationV2ThreadShell,
nowMs: number,
): OrchestratorMcpThreadListItem {
return {
threadId: shell.id,
title: shell.title,
link: threadLinkFor(scope, shell.id),
status: shell.activityRunStatus ?? shell.status,
updatedAt: DateTime.formatIso(shell.updatedAt),
...(shell.linkedPullRequest == null ? {} : { linkedPullRequest: shell.linkedPullRequest }),
...(threadSettlement(shell).settled ? { settled: true } : {}),
...(isSnoozed(shell, nowMs) ? { snoozed: true } : {}),
...(shell.lineage.parentThreadId === null
? {}
: { parentThreadId: shell.lineage.parentThreadId }),
};
}

const COMPACT_THREAD_LIST_MORE =
"Compact rows. `detail: true` gives full rows; t3_thread_read gives one thread in full.";

/** t4 fork (AI-93): list rows cut the prompt to a preview; `scheduledTaskId` reads one in full. */
export function scheduledTaskRows(tasks: ReadonlyArray<OrchestratorMcpScheduledTask>): {
readonly tasks: ReadonlyArray<OrchestratorMcpScheduledTaskRow>;
readonly more?: string;
} {
const rows = tasks.map((task): OrchestratorMcpScheduledTaskRow => ({
scheduledTaskId: task.scheduledTaskId,
title: task.title,
enabled: task.enabled,
boundThreadId: task.boundThreadId,
schedule: task.schedule,
nextRunAt: task.nextRunAt,
lastRunStatus: task.lastRunStatus,
promptPreview: task.prompt.slice(
0,
textPageEnd(task.prompt, 0, SCHEDULED_TASK_PROMPT_PREVIEW_CHARS),
),
promptLength: task.prompt.length,
...(task.blockedByPolicy === undefined ? {} : { blockedByPolicy: task.blockedByPolicy }),
}));
const cut = tasks.some(
(task) =>
task.prompt.length > SCHEDULED_TASK_PROMPT_PREVIEW_CHARS || task.webhookUrl !== undefined,
);
return cut
? {
tasks: rows,
more: `Prompts are cut to ${SCHEDULED_TASK_PROMPT_PREVIEW_CHARS} chars (promptLength is the whole). Pass \`scheduledTaskId\` for one task in full, with its webhook URL.`,
}
: { tasks: rows };
}

function listItemFromShell(
scope: McpInvocationScope,
shell: OrchestrationV2ThreadShell,
Expand Down Expand Up @@ -1057,6 +1119,7 @@ function timelineItem(input: {
text: text === null ? null : text.slice(offset, end),
textTruncated,
nextTextOffset: textTruncated ? end : null,
...(textTruncated ? { remainingChars: text.length - end } : {}),
updatedAt: DateTime.formatIso(input.row.item.updatedAt),
};
}
Expand Down Expand Up @@ -2089,10 +2152,20 @@ const make = Effect.gen(function* () {
failure("orchestration_error", `Could not list scheduled tasks: ${error.message}`),
),
);
const wanted = tasks.filter((task) =>
input.scheduledTaskId !== undefined
? task.id === input.scheduledTaskId
: projectId === undefined || task.projectId === projectId,
);
if (input.scheduledTaskId !== undefined && wanted.length === 0) {
return yield* failure(
"task_not_found",
`Scheduled task ${input.scheduledTaskId} was not found.`,
);
}
return {
tasks: yield* Effect.forEach(
tasks.filter((task) => projectId === undefined || task.projectId === projectId),
(task) => summarizeScheduledTask(scope, { parent, limits }, task),
tasks: yield* Effect.forEach(wanted, (task) =>
summarizeScheduledTask(scope, { parent, limits }, task),
),
};
},
Expand Down Expand Up @@ -3054,9 +3127,14 @@ const make = Effect.gen(function* () {
return {
projectId,
currentThreadId: parent?.thread.id ?? null,
threads: page.map((shell) => listItemFromShell(scope, shell, nowMs)),
threads: page.map((shell) =>
input.detail === true
? listItemFromShell(scope, shell, nowMs)
: compactListItemFromShell(scope, shell, nowMs),
),
nextCursor,
total: filtered.length,
...(input.detail === true || page.length === 0 ? {} : { more: COMPACT_THREAD_LIST_MORE }),
} satisfies OrchestratorMcpThreadListResult;
}),
readThread: Effect.fn("OrchestratorMcpService.readThread")(function* (scope, input) {
Expand Down Expand Up @@ -3108,12 +3186,9 @@ const make = Effect.gen(function* () {
target,
returnedRunIds,
);
if (
parent !== undefined &&
scope.thread !== undefined &&
tasks.length > 0 &&
(input.textOffset ?? 0) === 0
) {
// A cut result is delivered once a read reaches its end (itemId + textOffset).
const textOffset = input.itemId === undefined ? 0 : (input.textOffset ?? 0);
if (parent !== undefined && scope.thread !== undefined && tasks.length > 0) {
for (const task of tasks) {
const transfer = taskResultTransfer(parent.thread.id, target, task);
const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;
Expand All @@ -3133,6 +3208,7 @@ const make = Effect.gen(function* () {
task,
target: { ...target, ...resultRecords },
maxChars,
textOffset,
})
) {
yield* readTask(
Expand Down
50 changes: 44 additions & 6 deletions apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
type ModelSelection,
OrchestratorMcpDelegateTaskResult,
OrchestratorMcpThreadInterruptResult,
type OrchestratorMcpThreadReadResult,
OrchestratorMcpThreadSendResult,
ProjectId,
ProviderDriverKind,
Expand Down Expand Up @@ -196,10 +197,22 @@ const layerUnusedScheduledTaskStub = Layer.succeed(

describe("orchestrator MCP toolkit", () => {
it.live.each([
{ label: "distinct", result: queuedFollowupResult, latestSummary: queuedFollowupResult },
{ label: "identical", result: delegatedResult, latestSummary: null },
{ label: "emoji", result: "😀", latestSummary: "😀" },
])("reports $label child results", ({ result, latestSummary }) =>
{
label: "distinct",
result: queuedFollowupResult,
latestSummary: queuedFollowupResult,
pageChars: 20_000,
},
{ label: "identical", result: delegatedResult, latestSummary: null, pageChars: 20_000 },
{ label: "emoji", result: "😀", latestSummary: "😀", pageChars: 1 },
// A result cut across pages is delivered once a read reaches its end.
{
label: "paged",
result: queuedFollowupResult,
latestSummary: queuedFollowupResult,
pageChars: 10,
},
])("reports $label child results", ({ label, result, latestSummary, pageChars }) =>
Effect.scoped(
Effect.gen(function* () {
const cwd = yield* checkpointWorkspace("delegated-task-status");
Expand Down Expand Up @@ -709,7 +722,7 @@ describe("orchestrator MCP toolkit", () => {
{
threadId: delegated.childThreadId,
limit: 100,
maxCharsPerItem: result === "😀" ? 1 : 20_000,
maxCharsPerItem: pageChars,
},
{ ...invocation, thread: undefined },
).pipe(Effect.withTracer(tracer));
Expand All @@ -724,11 +737,36 @@ describe("orchestrator MCP toolkit", () => {
const read = yield* invoke("t3_thread_read", {
threadId: delegated.childThreadId,
limit: 100,
maxCharsPerItem: result === "😀" ? 1 : 20_000,
maxCharsPerItem: pageChars,
}).pipe(Effect.withTracer(tracer));
expect(read.isError).not.toBe(true);
expect(transferReads.length).toBeGreaterThan(0);
expect(read.structuredContent).toEqual(parentlessRead.structuredContent);
let cut = (
read.structuredContent as OrchestratorMcpThreadReadResult | undefined
)?.items.find((item) => item.textTruncated && item.text === result.slice(0, pageChars));
if (label === "paged") {
expect(cut).toMatchObject({
remainingChars: result.length - pageChars,
nextTextOffset: pageChars,
});
}
while (cut !== undefined) {
const afterCut = yield* orchestrator.getThreadProjection(parentThreadId);
expect(
afterCut.subagents.find((task) => task.id === queuedFollowup.taskId)
?.completionDelivery?.state,
).toBe("claimed");
const next = yield* invoke("t3_thread_read", {
threadId: delegated.childThreadId,
itemId: cut.itemId,
textOffset: cut.nextTextOffset,
maxCharsPerItem: pageChars,
}).pipe(Effect.withTracer(tracer));
cut = (next.structuredContent as OrchestratorMcpThreadReadResult).items.find(
(item) => item.textTruncated,
);
}
// The acknowledgement reads the task and its spawning run by id, not the parent's history.
expect(acknowledgementReads.length).toBeGreaterThan(0);
expect(
Expand Down
Loading
Loading