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
7 changes: 6 additions & 1 deletion apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import {
latestProviderTurnForAttempt,
resolveProjectProviderInstanceEnabled,
SECRET_REQUEST_UNSAVED_NOTE,
agentLaunchInboxError,
agentLaunchInboxRouting,
} from "@t3tools/contracts";
import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
Expand Down Expand Up @@ -989,7 +990,7 @@ function threadDetail(
const latest = ThreadManagementService.latestRun(projection);
const active = ThreadManagementService.latestActiveRun(projection);
return {
...(projection.thread.inbox === undefined ? {} : { inbox: projection.thread.inbox }),
...(shell.inbox === undefined ? {} : { inbox: shell.inbox }),
threadId: projection.thread.id,
projectId: projection.thread.projectId,
title: projection.thread.title,
Expand Down Expand Up @@ -3124,6 +3125,10 @@ const make = Effect.gen(function* () {
createThreads: Effect.fn("OrchestratorMcpService.createThreads")(
function* (callerScope, input) {
const { scope, parent } = yield* loadThreadCaller(callerScope, "create_threads");
for (const request of input.threads) {
const inboxError = agentLaunchInboxError(request);
if (inboxError !== null) return yield* failure("invalid_request", inboxError);
}
// Each thread shares this thread's checkout, so another environment cannot take it.
for (const request of input.threads) {
yield* admitPlacement(
Expand Down
25 changes: 25 additions & 0 deletions apps/server/src/mcp/ThreadMetadataMcpService.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import {
agentInboxRoutingError,
CommandId,
makeThreadInbox,
OrchestratorMcpFailure,
type OrchestrationV2AppThread,
type OrchestrationV2Command,
type ThreadMetadataMcpAction,
type ThreadMetadataMcpUpdateInput,
type ThreadMetadataMcpUpdateResult,
ThreadId,
routeThreadInbox,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
Expand Down Expand Up @@ -86,6 +89,20 @@ function metadataCommand(input: {
threadId: input.threadId,
regenerateTitle: true,
};
case "request_decision":
return {
type: "thread.metadata.update",
commandId: input.commandId,
threadId: input.threadId,
decisionRequest: input.update.decision!,
};
case "resolve_decision":
return {
type: "thread.metadata.update",
commandId: input.commandId,
threadId: input.threadId,
decisionRequest: null,
};
}
}

Expand Down Expand Up @@ -157,6 +174,14 @@ const make = Effect.gen(function* () {
`Thread ${threadId} was not found.`,
);
}
const inboxError =
input.inboxRouting === undefined
? null
: agentInboxRoutingError(
routeThreadInbox(shell.inbox ?? makeThreadInbox({ actor: null }), input.inboxRouting),
input.inboxRouting,
);
if (inboxError !== null) return yield* failure("invalid_request", inboxError);
const requestKey =
input.clientRequestId === undefined ? yield* random.uuidV4() : input.clientRequestId;
const updateCommandId = commandId({
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", {

const ThreadUpdateTool = Tool.make("t3_thread_update", {
description:
"Route a thread with action:'route' and inboxRouting (owner, assignee, audience, attentionKind), or rename a thread (`action:'rename'` with `title`) or regenerate its title. Omit `threadId` for this thread. Workspace and branch cannot change here.",
"Update a thread; omit `threadId` for this one. When a founder must decide, review or approve, use `action:'request_decision'` with `decision`: the thread shows in their inbox until they reply there, `resolve_decision`, or settle. `action:'route'` refiles it with `inboxRouting`; a founder's or the shared inbox needs `inboxRouting.reason`. `rename` takes `title`; `regenerate_title`. Workspace and branch cannot change here.",
// Keeps the input's action/field check, which rebuilding the struct would drop.
parameters: ThreadMetadataMcpUpdateInput.mapFields(
Struct.assign({ environmentId: OrchestratorMcpEnvironmentTarget }),
Expand Down
28 changes: 22 additions & 6 deletions apps/server/src/mcp/toolkits/project/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ it.effect("a launch with a model its provider does not advertise creates no thre
}),
);

it.effect("a launch is filed in Agents unless the agent picks an inbox", () =>
it.effect("a launch is filed in Agents unless the agent picks an inbox with a reason", () =>
Effect.gen(function* () {
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
const { projectId, dependencies } = clientLaunchHarness({
Expand All @@ -428,24 +428,40 @@ it.effect("a launch is filed in Agents unless the agent picks an inbox", () =>
McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
),
);
const launch = (inbox?: "kameron" | "shared") =>
const launch = (inbox?: "kameron" | "shared", reason?: "conversation") =>
toolkit
.handle("t3_thread_launch", {
title: "Fix",
projectId,
...(inbox === undefined ? {} : { inbox }),
...(reason === undefined ? {} : { inboxRouting: { reason } }),
})
.pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
.pipe(
Stream.unwrap,
Stream.runCollect,
Effect.map((result) => result.at(-1)?.result),
Effect.provide(dependencies),
);

yield* launch();
yield* launch("kameron");
yield* launch("shared");
for (const inbox of ["kameron", "shared"] as const) {
expect(yield* launch(inbox)).toMatchObject({
_tag: "OrchestratorMcpFailure",
code: "invalid_request",
message: expect.stringContaining("inboxRouting.reason"),
});
}
yield* launch("kameron", "conversation");
yield* launch("shared", "conversation");
expect(launched.map((input) => input.inboxRouting?.audience)).toEqual([
"agent-only",
"kameron",
"shared",
]);
expect(launched[1]?.inboxRouting?.assignee).toEqual({ kind: "human", id: "kameron" });
expect(launched[1]?.inboxRouting).toMatchObject({
assignee: { kind: "human", id: "kameron" },
reason: "conversation",
});
}),
);

Expand Down
7 changes: 7 additions & 0 deletions apps/server/src/mcp/toolkits/project/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
agentLaunchInboxError,
agentLaunchInboxRouting,
CommandId,
type EnvironmentId,
Expand Down Expand Up @@ -270,6 +271,12 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
const threadId = ThreadId.make(commandId);
const messageId = MessageId.make(commandId);
const attachments = input.attachments ?? [];
const inboxError = agentLaunchInboxError(input);
if (inboxError !== null)
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message: inboxError,
});
if (attachments.some((attachment) => !Claims.attachmentIsPendingUpload(attachment)))
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
CommandId,
MessageId,
EventId,
founderInboxLane,
inboxRoutingFor,
NodeId,
type OrchestrationV2DomainEvent,
PlanId,
Expand Down Expand Up @@ -462,6 +464,84 @@ it.effect("marks a never-visited thread's first completion unread", () =>
}).pipe(Effect.provide(layerTest)),
);

it.effect("a founder decision request holds an agent thread in their inbox until they answer", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threadId = ThreadId.make("thread:decision-request");
yield* orchestrator.dispatch({
type: "thread.create",
commandId: CommandId.make("create-decision-request"),
threadId,
projectId: ProjectId.make("project:decision-request"),
title: "Autonomous work",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdBy: "agent",
creationSource: "mcp",
inboxOrigin: { kind: "agent", id: "lead" },
inboxRouting: inboxRoutingFor("agents"),
});
const lanes = Effect.gen(function* () {
const inbox = (yield* projections.getThreadShell(threadId))?.inbox;
return [founderInboxLane(inbox, "kameron"), founderInboxLane(inbox, "jeff")];
});
let step = 0;
const update = (decisionRequest: "ask" | null) =>
orchestrator.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make(`decision-request-${++step}`),
threadId,
decisionRequest:
decisionRequest === null
? null
: { founder: "kameron", kind: "approval", question: "Send this draft?" },
});
const message = (createdBy: "agent" | "user") =>
Effect.gen(function* () {
yield* TestClock.adjust("1 second");
const id = `decision-message-${++step}`;
yield* orchestrator.dispatch({
type: "message.dispatch",
commandId: CommandId.make(id),
threadId,
messageId: MessageId.make(id),
text: createdBy === "user" ? "Yes, send it." : "Still working.",
attachments: [],
dispatchMode: { type: "defer_start" },
createdBy,
creationSource: createdBy === "user" ? "web" : "mcp",
});
});
assert.deepEqual(yield* lanes, ["hidden", "hidden"]);

yield* update("ask");
assert.deepEqual(yield* lanes, ["action", "hidden"]);
yield* orchestrator.dispatch({
type: "thread.settle",
commandId: CommandId.make("settle-decision-request"),
threadId,
});
assert.deepEqual(yield* lanes, ["hidden", "hidden"]);

yield* TestClock.adjust("1 second");
yield* update("ask");
yield* message("agent");
assert.deepEqual(yield* lanes, ["action", "hidden"]);
yield* message("user");
assert.deepEqual(yield* lanes, ["hidden", "hidden"]);

yield* TestClock.adjust("1 second");
yield* update("ask");
assert.deepEqual(yield* lanes, ["action", "hidden"]);
yield* update(null);
assert.deepEqual(yield* lanes, ["hidden", "hidden"]);
}).pipe(Effect.provide(layerTest)),
);

const completeAndSnoozeThread = Effect.fn("test.completeAndSnoozeThread")(function* (
name: string,
snoozeMinutes: number,
Expand Down
36 changes: 28 additions & 8 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
OrchestrationV2ThreadHistoryPage,
ProjectId,
} from "@t3tools/contracts";
import { makeThreadInbox, routeThreadInbox } from "@t3tools/contracts";
import { makeThreadInbox, routeThreadInbox, type ThreadInbox } from "@t3tools/contracts";
import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts";
import {
latestExecutedRun,
Expand Down Expand Up @@ -797,6 +797,28 @@ function askedForLinkedMachine(
return hint !== "" && hint === normalize(linked.hint) && hint === normalize(linked.linkedLabel);
}

function withoutDecisionRequest(inbox: ThreadInbox): ThreadInbox {
const { decisionRequest: _closed, ...rest } = inbox;
return rest;
}

function askedInbox(
inbox: ThreadInbox | undefined,
command: Extract<OrchestrationV2Command, { readonly type: "thread.metadata.update" }>,
now: DateTime.Utc,
): ThreadInbox {
const base = inbox ?? makeThreadInbox({ actor: null });
const routed =
command.inboxRouting === undefined ? base : routeThreadInbox(base, command.inboxRouting);
if (command.decisionRequest === undefined) return routed;
return command.decisionRequest === null
? withoutDecisionRequest(routed)
: {
...routed,
decisionRequest: { ...command.decisionRequest, requestedAt: DateTime.formatIso(now) },
};
}

// A workspace change detaches the session, which can settle the calling run at once. Queuing its
// follow-up in a later command would let a delegated task report its result before that exists.
function metadataUpdateContinuation(
Expand Down Expand Up @@ -4732,6 +4754,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
thread.settledOverride === "settled" && thread.settledAt !== null && !wasPinned;
return {
...thread,
...(thread.inbox?.decisionRequest === undefined
? {}
: { inbox: withoutDecisionRequest(thread.inbox) }),
settledOverride: "settled",
settledAt: alreadySettled ? thread.settledAt : (command.settledAt ?? now),
// Settled threads refuse recovery, so an armed resume would stay hidden until un-settled.
Expand Down Expand Up @@ -4880,14 +4905,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
};
return {
...thread,
...(command.inboxRouting === undefined
...(command.inboxRouting === undefined && command.decisionRequest === undefined
? {}
: {
inbox: routeThreadInbox(
thread.inbox ?? makeThreadInbox({ actor: null }),
command.inboxRouting,
),
}),
: { inbox: askedInbox(thread.inbox, command, now) }),
...(command.title === undefined ? {} : { title: command.title }),
...(command.limitRecovery === undefined ? {} : { limitRecovery }),
...(command.limitRecovery !== undefined &&
Expand Down
Loading
Loading