Skip to content
Closed
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
10 changes: 10 additions & 0 deletions apps/server/src/mcp/McpInvocationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const ALL_MCP_CAPABILITIES = [
"device",
"pull-requests",
"issues",
"background-wait",
] as const;
export type McpCapability = (typeof ALL_MCP_CAPABILITIES)[number];

Expand Down Expand Up @@ -192,6 +193,15 @@ export const hiddenFromOutsideClients = (): boolean => {
return scope === undefined || scope.thread !== undefined;
};

/** `hiddenFromOutsideClients`, and hidden from a thread whose provider cannot hold for background work. */
export const hiddenWithoutBackgroundWait = (): boolean => {
const fiber = Fiber.getCurrent();
const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext);
return (
scope === undefined || (scope.thread !== undefined && scope.capabilities.has("background-wait"))
);
};

/** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */
export const hiddenWhileLinksOff = (): boolean => {
const fiber = Fiber.getCurrent();
Expand Down
8 changes: 6 additions & 2 deletions apps/server/src/mcp/McpToolAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,11 @@ const linksUnavailable = new OrchestratorMcpFailure({
* environment, which checks the rest. The handler here never sees
* `environmentId`, so it cannot leak into what it writes.
*/
const THREAD_ONLY = new Set<unknown>([
McpInvocationContext.hiddenFromOutsideClients,
McpInvocationContext.hiddenWithoutBackgroundWait,
]);

const routed = Effect.fn("McpToolAccess.routed")(function* <Tools extends Record<string, Tool.Any>>(
toolkit: Toolkit.Toolkit<Tools>,
declarations: Handlers<Tools>,
Expand All @@ -426,8 +431,7 @@ const routed = Effect.fn("McpToolAccess.routed")(function* <Tools extends Record
const remote = remoteCheckOf(declaration);
if (
remote === undefined &&
Context.getOrUndefined(tool.annotations, McpSchema.EnabledWhen) !==
McpInvocationContext.hiddenFromOutsideClients
!THREAD_ONLY.has(Context.getOrUndefined(tool.annotations, McpSchema.EnabledWhen))
)
return yield* Effect.die(
`${name} acts as its calling thread, so outside clients must not be offered it.`,
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {

const BackgroundWaitTool = Tool.make("t3_background_wait", {
description:
"Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks. Claude/OpenCode only.",
"Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks.",
parameters: Schema.Struct({
taskIds: Schema.Array(TrimmedNonEmptyString).check(
Schema.isMinLength(1),
Expand All @@ -165,7 +165,7 @@ const BackgroundWaitTool = Tool.make("t3_background_wait", {
// Only marks which tasks keep the thread Working; Claude Plan mode blocks tools without this.
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients);
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWithoutBackgroundWait);

const ScheduleTaskTool = Tool.make("schedule_task", {
description:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,7 @@ export const ClaudeProviderCapabilitiesV2 = {
emitsToolOutput: true,
supportsMcpTools: true,
supportsDynamicToolCallbacks: true,
supportsBackgroundWait: true,
},
approvals: {
supportsCommandApproval: true,
Expand Down
7 changes: 7 additions & 0 deletions apps/server/src/orchestration-v2/ProviderSessionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,12 @@ export const layerWithOptions = (
>(["orchestration", "worktree", "pull-requests", "issues"]);
if (browserToolsAvailable) capabilities.add("preview");
if (deviceToolsAvailable) capabilities.add("device");
const backgroundWait = yield* registry.get(providerInstanceId).pipe(
Effect.flatMap((adapter) => adapter.getCapabilities()),
Effect.map((adapter) => adapter.tools.supportsBackgroundWait === true),
Effect.orElseSucceed(() => false),
);
if (backgroundWait) capabilities.add("background-wait");
const subagent = yield* projectionStore.getThread(threadId).pipe(
Effect.map((thread) => thread.lineage.relationshipToParent === "subagent"),
Effect.orElseSucceed(() => false),
Expand All @@ -595,6 +601,7 @@ export const layerWithOptions = (
resolved.thread.providerInstanceId === providerInstanceId &&
resolved.capabilities.has("preview") === browserToolsAvailable &&
resolved.capabilities.has("device") === deviceToolsAvailable &&
resolved.capabilities.has("background-wait") === backgroundWait &&
// A credential issued while the lineage read failed is replaced once it works.
(resolved.thread.subagent === true) === subagent
) {
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/provider/agentContextBudget.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 5930,
"codexAdditionalContextBytes": 7324,
"mcpToolListJsonBytes": 52145
"mcpToolListJsonBytes": 52123
}
2 changes: 1 addition & 1 deletion evals/mcp-tool-use/backgroundWait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export const makeBackgroundWait = Effect.fn("evaluateMcpToolUse.makeBackgroundWa
requestNamespace: "mcp-tool-use-eval",
thread: { threadId, providerSessionId: "mcp-tool-use-eval", providerInstanceId },
client: undefined,
capabilities: new Set<McpInvocationContext.McpCapability>(["orchestration"]),
capabilities: new Set<McpInvocationContext.McpCapability>(["orchestration", "background-wait"]),
issuedAt: 0,
};
const request = McpSchema.McpRequestContext.of({
Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/orchestrationV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,8 @@ export const OrchestrationV2ToolCapabilities = Schema.Struct({
emitsToolOutput: Schema.Boolean,
supportsMcpTools: Schema.Boolean,
supportsDynamicToolCallbacks: Schema.Boolean,
/** The agent can mark background work it resumes from, so the thread holds as waiting. */
supportsBackgroundWait: Schema.optional(Schema.Boolean),
});
export type OrchestrationV2ToolCapabilities = typeof OrchestrationV2ToolCapabilities.Type;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,21 @@ describe("T3 device instructions", () => {
assert.include(laterRun(false), T3_CODE_DEVICE_TOOL_INSTRUCTIONS);
assert.notInclude(laterRun(false), T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim());
assert.equal(laterRun(true), "Check the login screen.");

// A provider's own guidance reaches a conversation that already had the rest.
const providerRun = (providerInstructionsDelivered: boolean) =>
t3OrchestrationPrompt({
prompt: "Check the login screen.",
hasT3Mcp: true,
hasDeviceTools: false,
orchestrationDelivered: true,
deviceInstructionsDelivered: false,
providerInstructions: "Mark awaited shells.",
providerInstructionsDelivered,
});
assert.include(providerRun(false), "Mark awaited shells.");
assert.notInclude(providerRun(false), T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim());
assert.equal(providerRun(true), "Check the login screen.");
});

it("reach ACP agents again when device access changes mid-thread", () => {
Expand Down
23 changes: 14 additions & 9 deletions packages/provider-core/src/server/orchestrationInstructions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,22 @@ export function t3OrchestrationPrompt(input: {
readonly hasDeviceTools: boolean;
readonly orchestrationDelivered: boolean;
readonly deviceInstructionsDelivered: boolean;
/** Guidance for this provider's own tools, sent until `providerInstructionsDelivered`. */
readonly providerInstructions?: string;
readonly providerInstructionsDelivered?: boolean;
}): string {
if (!input.hasT3Mcp) return input.prompt;
if (!input.orchestrationDelivered) {
return prependT3OrchestrationInstructions(
input.prompt,
orchestrationInstructions(input.hasDeviceTools),
);
}
return input.hasDeviceTools && !input.deviceInstructionsDelivered
? prependT3OrchestrationInstructions(input.prompt, T3_CODE_DEVICE_TOOL_INSTRUCTIONS)
: input.prompt;
const instructions = [
!input.orchestrationDelivered
? orchestrationInstructions(input.hasDeviceTools)
: input.hasDeviceTools && !input.deviceInstructionsDelivered
? T3_CODE_DEVICE_TOOL_INSTRUCTIONS
: undefined,
input.providerInstructionsDelivered === true ? undefined : input.providerInstructions,
].flatMap((part) => (part === undefined ? [] : [part.trim()]));
return instructions.length === 0
? input.prompt
: prependT3OrchestrationInstructions(input.prompt, instructions.join("\n\n"));
}

export function t3OrchestrationSystemPrompt(
Expand Down
78 changes: 78 additions & 0 deletions packages/provider-cursor/src/server/CursorAgentSdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ListRunsOptions } from "@cursor/sdk";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -342,6 +343,83 @@ describe("CursorAgentSdkRunner", () => {
}).pipe(Effect.provide(layerTest)),
);

it.effect("keeps an agent's background shells and reports each start and end in order", () =>
Effect.gen(function* () {
const start = (conversationId: string, id: number) => {
let complete: (completion: object) => void = () => {};
const abort = vi.fn();
const kept: unknown = (
Reflect.get(globalThis, Symbol.for("@cursor/sdk.backgroundShell")) as Function
)({
conversationId,
command: "sleep 60",
shell: {
id,
pid: id + 1,
abort,
onComplete: (listener: typeof complete) => (complete = listener),
},
});
return { kept, abort, complete: (completion: object) => complete(completion) };
};
const events: Array<object> = [];
const stops: Array<() => void> = [];
const reported = yield* Deferred.make<void>();
const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
const session = yield* runner.open({
operation: "create",
options: {},
threadId: ThreadId.make("thread-cursor-agent-sdk-background"),
providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-background"),
});
const run = yield* session.send({
message: "watch it",
onBackgroundShell: (event) =>
Effect.gen(function* () {
if (event.type === "started") {
const { stop, ...started } = event;
stops.push(stop);
events.push(started);
return;
}
events.push(event);
if (!event.stopped) yield* Deferred.succeed(reported, undefined);
}),
});
yield* run.wait;

const killed = start("agent-cursor-agent-sdk-test", 10);
const finished = start("agent-cursor-agent-sdk-test", 20);
const foreign = start("agent-someone-else", 30);
killed.complete({ code: null, aborted: true });
finished.complete({ code: 3, aborted: false, outputPath: "/terminals/20.txt" });
yield* Deferred.await(reported);
stops[0]!();

assert.deepStrictEqual([killed.kept, finished.kept, foreign.kept], [true, true, false]);
assert.strictEqual(killed.abort.mock.calls.length, 1);
const shell = (id: string, pid: number) => ({ id, pid, command: "sleep 60" });
assert.deepStrictEqual(events, [
{ ...shell("10", 11), type: "started" },
{ ...shell("20", 21), type: "started" },
{
...shell("10", 11),
type: "ended",
stopped: true,
exitCode: undefined,
outputPath: undefined,
},
{
...shell("20", 21),
type: "ended",
stopped: false,
exitCode: 3,
outputPath: "/terminals/20.txt",
},
]);
}).pipe(Effect.provide(layerTest)),
);

it.effect("forwards Run.steer and reports a missing method as a follow-up", () =>
Effect.gen(function* () {
cursorSdkMock.runSteer.mockClear();
Expand Down
84 changes: 84 additions & 0 deletions packages/provider-cursor/src/server/CursorAgentSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,31 @@ export interface CursorAgentSdkSendInput<Error> {
readonly summarize?: boolean;
/** Runs `agent.resume()`: Cursor's ResumeAction from the latest checkpoint, with no message. */
readonly resume?: boolean;
/**
* Runs, in order, when a background shell this agent starts from now on starts and when it
* ends, which is often long after the run.
*/
readonly onBackgroundShell?: (event: CursorBackgroundShellEvent) => Effect.Effect<void>;
}

interface CursorBackgroundShellRef {
/** The shell id Cursor gave the agent. */
readonly id: string;
readonly pid: number | undefined;
readonly command: string;
}

export type CursorBackgroundShellEvent =
| (CursorBackgroundShellRef & { readonly type: "started"; readonly stop: () => void })
| (CursorBackgroundShellRef & {
readonly type: "ended";
/** Killed by the agent or by `stop`, rather than exiting by itself. */
readonly stopped: boolean;
readonly exitCode: number | undefined;
/** The file Cursor logs the shell's output to. */
readonly outputPath: string | undefined;
});

export interface CursorAgentSdkRun {
readonly runId: string;
readonly agentId: string;
Expand Down Expand Up @@ -426,6 +449,57 @@ function subscribeShellStreamOutput(listener: (output: CursorShellStreamOutput)
};
}

interface CursorBackgroundShell {
readonly conversationId?: unknown;
readonly command?: unknown;
readonly shell: {
readonly id?: unknown;
readonly pid?: unknown;
readonly abort: () => void;
readonly onComplete: (
listener: (completion: {
readonly code?: unknown;
readonly aborted?: unknown;
readonly outputPath?: unknown;
}) => void,
) => void;
};
}

// The SDK kills an agent's background shells when its run ends and reports their exit to no one.
// patches/@cursor__sdk@1.3.1.patch offers each new one to this hook; true keeps it past the run.
const BACKGROUND_SHELL_HOOK = Symbol.for("@cursor/sdk.backgroundShell");
const backgroundShellListeners = new Map<string, (event: CursorBackgroundShellEvent) => void>();

function listenForBackgroundShells(
agentId: string,
listener: (event: CursorBackgroundShellEvent) => void,
) {
const hooks = globalThis as Record<symbol, unknown>;
hooks[BACKGROUND_SHELL_HOOK] ??= ({ conversationId, command, shell }: CursorBackgroundShell) => {
const notify =
typeof conversationId === "string" ? backgroundShellListeners.get(conversationId) : undefined;
if (notify === undefined) return false;
const ref = {
id: String(shell.id),
pid: typeof shell.pid === "number" ? shell.pid : undefined,
command: typeof command === "string" ? command : "",
};
notify({ ...ref, type: "started", stop: () => shell.abort() });
shell.onComplete((completion) =>
notify({
...ref,
type: "ended",
stopped: completion.aborted === true,
exitCode: typeof completion.code === "number" ? completion.code : undefined,
outputPath: typeof completion.outputPath === "string" ? completion.outputPath : undefined,
}),
);
return true;
};
backgroundShellListeners.set(agentId, listener);
}

export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
) {
Expand Down Expand Up @@ -556,6 +630,16 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
payload: { type: "run.start", message: sendInput.message, options },
});

const onBackgroundShell = sendInput.onBackgroundShell;
if (onBackgroundShell !== undefined) {
let delivered = Promise.resolve();
listenForBackgroundShells(agent.agentId, (event) => {
delivered = delivered
.then(() => Effect.runPromiseWith(context)(onBackgroundShell(event)))
.catch(() => undefined);
});
}

let callbacksReady = false;
const pendingUpdates: Array<InteractionUpdate> = [];
let callbackFailure: { readonly cause: unknown } | undefined;
Expand Down
Loading
Loading