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
59 changes: 59 additions & 0 deletions apps/server/src/auth/settleActor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { AuthSessionId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";

import { settleActorOf } from "./settleActor.ts";

const sessionId = AuthSessionId.make("settle-actor-session");
const pairedBrowser = {
sessionId,
device: "Chrome",
deviceType: "desktop",
founder: null,
} as const;

describe("settleActorOf", () => {
it("names a person's assigned client session as its founder", () => {
expect(
settleActorOf(
{ sessionId, device: "Laptop", deviceType: "desktop", founder: "kameron" },
"one-time-token",
true,
),
).toEqual({ kind: "founder", founder: "kameron", sessionId, client: "Laptop" });
});

it("names the desktop app's own bootstrap session a founder before an owner is set", () => {
expect(
settleActorOf(
{ sessionId, device: "", deviceType: "desktop", founder: null },
"desktop-bootstrap",
true,
).kind,
).toBe("founder");
});

it("names a bot's session as an agent, so a founder's inbox refuses its settle", () => {
expect(
settleActorOf({ sessionId, device: "", deviceType: "bot", founder: null }, "bot", false),
).toEqual({ kind: "agent", founder: null, sessionId });
});

it("names an unknown or failed sender read an agent", () => {
expect(
settleActorOf({ sessionId, device: "", deviceType: "unknown", founder: null }, "x", false)
.kind,
).toBe("agent");
expect(
settleActorOf(
{ sessionId, device: "", deviceType: "unknown", founder: "kameron" },
"desktop-bootstrap",
false,
).kind,
).toBe("agent");
});

it("names an unassigned paired person session a founder unless founder identity is required", () => {
expect(settleActorOf(pairedBrowser, "one-time-token", false).kind).toBe("founder");
expect(settleActorOf(pairedBrowser, "one-time-token", true).kind).toBe("agent");
});
});
23 changes: 23 additions & 0 deletions apps/server/src/auth/settleActor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { OrchestrationV2CommandActor, OrchestrationV2MessageSentBy } from "@t3tools/contracts";

const PERSON_DEVICES = new Set(["desktop", "mobile", "tablet"]);

/**
* Settles as a founder only from a person's device type; an unknown or failed sender read settles
* as an agent, so a founder's inbox refuses it. Under `requireFounderIdentity` the session must
* also be enrolled: an assigned founder or the desktop app's own bootstrap session.
*/
export const settleActorOf = (
sentBy: OrchestrationV2MessageSentBy,
sessionSubject: string,
requireFounderIdentity: boolean,
): OrchestrationV2CommandActor => ({
kind:
PERSON_DEVICES.has(sentBy.deviceType) &&
(!requireFounderIdentity || sentBy.founder !== null || sessionSubject === "desktop-bootstrap")
? "founder"
: "agent",
founder: sentBy.founder,
sessionId: sentBy.sessionId,
...(sentBy.device === "" ? {} : { client: sentBy.device }),
});
49 changes: 49 additions & 0 deletions apps/server/src/mcp/toolkits/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,55 @@ it.effect("rejects an unknown organize target instead of archiving the calling t
);
});

it.effect("settles through organize as an agent, on its own thread or another", () => {
const settles: Array<
Parameters<ThreadManagement.ThreadManagementServiceShape["settleThread"]>[0]
> = [];
return Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const settle = (invocation: McpInvocationContext.McpInvocationScope, target?: string) =>
server
.callTool({
name: "t3_thread_organize",
arguments: { action: "settle", ...(target === undefined ? {} : { threadId: target }) },
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect((yield* settle(scope)).isError).toBe(false);
expect((yield* settle(clientScope("full-access"), "other-thread")).isError).toBe(false);
expect(settles).toMatchObject([
{ threadId, byOwnAgent: true, actor: { kind: "agent", agentThreadId: threadId } },
{
threadId: "other-thread",
byOwnAgent: false,
actor: { kind: "agent", client: "Claude Code" },
},
]);
}).pipe(
Effect.provide(
layerThreadToolkit.pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(NodeCrypto.layer),
Layer.provide(
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)),
getProjectThreadRecords: ({ threadId: id }) =>
Effect.succeed(
McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)),
),
settleThread: (input) => {
settles.push(input);
return Effect.succeed({ sequence: 1 });
},
}),
),
),
),
);
});

it.effect("keeps unexpected handler defects private through the production registration", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
Expand Down
13 changes: 11 additions & 2 deletions apps/server/src/mcp/toolkits/thread/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,11 +413,20 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
),
t3_thread_organize: writesThread((input) =>
Effect.gen(function* () {
const { threads, projection, caller } = yield* readThread(input.threadId);
const { threads, projection, caller, scope } = yield* readThread(input.threadId);
const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
if (input.action === "settle") {
// Every MCP caller is an agent, a linked environment's included.
return yield* threads
.settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id })
.settleThread({
...common,
byOwnAgent: caller?.id === projection.thread.id,
actor: {
kind: "agent",
...(caller === undefined ? {} : { agentThreadId: caller.id }),
...(scope.client === undefined ? {} : { client: scope.client.label }),
},
})
.pipe(Effect.mapError(dispatchFailure));
}
let command: OrchestrationV2Command;
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/thread/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts";

const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
description:
"Organize this thread by default. `snooze` needs `snoozedUntil`. Self-settle waits for turn end; failure or a queued message keeps it active.",
"Organize this thread by default. `snooze` needs `snoozedUntil`. Self-settle waits for turn end; failure or a queued message keeps it active. A thread in a founder or Shared inbox refuses settle: leave it for the founder.",
parameters: Schema.Struct({
environmentId: OrchestratorMcpEnvironmentTarget,
threadId: Schema.optional(ThreadId),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
RuntimeRequestId,
ThreadId,
TurnItemId,
makeThreadInbox,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
Expand Down Expand Up @@ -2511,6 +2512,7 @@ it.effect.each(["thread.settle", "thread.auto-settle"] as const)(
payload: {
...before,
id: childId,
inbox: makeThreadInbox({ actor: null }),
lineage: {
parentThreadId: threadId,
rootThreadId: threadId,
Expand All @@ -2534,6 +2536,13 @@ it.effect.each(["thread.settle", "thread.auto-settle"] as const)(
threadId,
standing: null,
});
// A persona files the thread for the founders; only once it is back in Agents may it settle.
yield* orchestrator.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make("standing-root:to-agents"),
threadId,
inboxRouting: { owner: null, assignee: null, audience: "agent-only" },
});
const retired = yield* projections.getThread(threadId);
yield* orchestrator.dispatch({
type,
Expand Down
20 changes: 20 additions & 0 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import type {
} from "@t3tools/contracts";
import {
inboxAfterStandingSet,
founderInboxHolder,
founderInboxSettleRefusal,
isStandingThreadRoot,
makeThreadInbox,
nextFounderSeenMessage,
Expand Down Expand Up @@ -5622,6 +5624,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
"Standing role threads cannot be settled. Clear its standing persona before settling.",
});
}
// Every settle path reaches here, a deferred settle-after-run included, so it re-checks now.
// Project decisionRequest through the shell when present so answered asks don't linger.
const projectedShell =
thread.inbox?.decisionRequest !== undefined
? yield* projectionStore.getThreadShell(command.threadId).pipe(mapDispatchError(command))
: null;
const inboxHolder = founderInboxHolder(projectedShell?.inbox ?? thread.inbox);
if (inboxHolder !== null && command.actor?.kind !== "founder") {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: founderInboxSettleRefusal(inboxHolder),
});
}
const projection = yield* loadProjectionForCommand(
command,
["runs", "runtimeRequests", "providerThreads", "turnItems"],
Expand Down Expand Up @@ -6678,6 +6694,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
providerInstanceId: updatedThread.providerInstanceId,
occurredAt: now,
payload: updatedThread,
...(command.type === "thread.settle" && command.actor !== undefined
? { actor: command.actor }
: {}),
});
// Archiving ends the guest share, so its waiting files go too.
yield* releaseGuestAttachments(command, thread.guestShare, updatedThread.guestShare, effects);
Expand Down Expand Up @@ -17676,6 +17695,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
type: "thread.settle",
commandId: command.commandId,
threadId: command.threadId,
actor: { kind: "server" },
...(command.settledAt === undefined ? {} : { settledAt: command.settledAt }),
},
events,
Expand Down
39 changes: 37 additions & 2 deletions apps/server/src/orchestration-v2/ThreadManagementService.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import * as SecureRandom from "effect/crypto/SecureRandom";
import {
BACKGROUND_WAIT_STALE_MINUTES,
founderInboxHolder,
founderInboxSettleRefusal,
isStandingThreadRoot,
type OrchestrationV2CommandActor,
ThreadRedirectError,
} from "@t3tools/contracts";
import { staleTimeoutMs } from "./waitStaleness.ts";
Expand Down Expand Up @@ -590,11 +593,15 @@ export interface ThreadManagementServiceShape {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly runId: RunId;
/** Who asked; absent means the server. A founder inbox refuses any but a founder. */
readonly actor?: OrchestrationV2CommandActor;
}) => Effect.Effect<void, ThreadManagementFailure>;
/** Refuses at once when a founder's inbox holds the thread and `actor` is not a founder. */
readonly settleThread: (input: {
readonly threadId: ThreadId;
readonly commandId: CommandId;
readonly byOwnAgent: boolean;
readonly actor: OrchestrationV2CommandActor;
}) => Effect.Effect<
{ readonly sequence: number } | { readonly settlesWhenTurnEnds: true },
Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
Expand Down Expand Up @@ -1473,6 +1480,16 @@ const make = Effect.gen(function* () {
)
)
return true;
// A founder's inbox took the thread while the turn ran; the dispatch would refuse it.
const projectedInbox =
records.thread.inbox?.decisionRequest !== undefined
? (yield* orchestrator.getThreadShell(input.threadId))?.inbox
: undefined;
if (
founderInboxHolder(projectedInbox ?? records.thread.inbox) !== null &&
input.actor?.kind !== "founder"
)
return true;
const later = records.runs.filter((candidate) => candidate.ordinal > run.ordinal);
const cancelledMessageIds = later
.filter((candidate) => candidate.status === "cancelled")
Expand Down Expand Up @@ -1536,6 +1553,7 @@ const make = Effect.gen(function* () {
commandId: CommandId.make(`server:settle-after-run:${input.runId}:${sequence}`),
threadId: input.threadId,
expectedLatestRunId: latest.id,
actor: input.actor ?? { kind: "server" },
}).pipe(
Effect.as(true),
// A notification can start between the projection read and the guarded dispatch.
Expand Down Expand Up @@ -1564,19 +1582,36 @@ const make = Effect.gen(function* () {
const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn(
"orchestrationV2.threadManagement.settleThread",
)(function* (input) {
const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
if (shell != null && shell.activeRunId !== null && !isStandingThreadRoot(shell)) {
const shell = yield* orchestrator.getThreadShell(input.threadId);
const inboxHolder =
shell != null && isStandingThreadRoot(shell) ? null : founderInboxHolder(shell?.inbox);
// Refuse before deferring, so an agent learns now instead of at a settle that never lands.
if (inboxHolder !== null && input.actor.kind !== "founder") {
return yield* new Orchestrator.OrchestratorDispatchError({
commandId: input.commandId,
commandType: "thread.settle",
cause: founderInboxSettleRefusal(inboxHolder),
});
}
if (
input.byOwnAgent &&
shell != null &&
shell.activeRunId !== null &&
!isStandingThreadRoot(shell)
) {
yield* settleAfterRun({
projectId: shell.projectId,
threadId: shell.id,
runId: shell.activeRunId,
actor: input.actor,
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope));
return { settlesWhenTurnEnds: true } as const;
}
const result = yield* dispatch({
type: "thread.settle",
commandId: input.commandId,
threadId: input.threadId,
actor: input.actor,
});
return { sequence: result.sequence };
});
Expand Down
7 changes: 2 additions & 5 deletions apps/server/src/orchestration-v2/ThreadSettlementService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
import {
CommandId,
isDelegatedAppThread,
founderInboxHolder,
isStandingThreadRoot,
isOrchestrationV2WorkActive,
type ThreadId,
Expand Down Expand Up @@ -202,17 +203,13 @@ export function settlesFinishedAgentWork(
return !agentBackgroundWorkPending(thread);
}

const HUMAN_INBOX_AUDIENCES = new Set(["kameron", "jeff", "shared"]);

export function isAutoSettlementCandidate(
thread: Omit<ProjectionStore.ProjectionSettlementCandidate, "latestResumingMessageAt">,
nowMs: number,
): boolean {
if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false;
if (thread.inbox?.audience !== undefined && HUMAN_INBOX_AUDIENCES.has(thread.inbox.audience)) {
return false;
}
if (founderInboxHolder(thread.inbox) !== null) return false;
if (thread.inbox?.audience === "agent-only" && thread.status === "failed") return false;
if (isStandingThreadRoot(thread)) return false;
if (thread.pendingRuntimeRequest !== null) return false;
Expand Down
Loading
Loading