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
29 changes: 29 additions & 0 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,19 @@ export class EnvironmentAuth extends Context.Service<
},
ServerAuthInternalError
>;
/**
* The calling link's own session, signed again for another full lifetime. The session id stays,
* so the work the link started here stays its own. Only a linked environment's session renews:
* an outside agent still signs in again when its session ends. None when it is revoked or gone.
*/
readonly renewMcpClientSession: (input: {
readonly sessionId: AuthSessionId;
readonly access: AuthMcpClientAccess;
readonly peerLink: boolean;
}) => Effect.Effect<
Option.Option<{ readonly token: string; readonly expiresAt: DateTime.Utc }>,
ServerAuthInternalError
>;
/**
* Spends a code covering all granted scopes and returns the level it approves. A level-bound
* code must name `access`. Rejects desktop grants and leaves refused codes unspent.
Expand Down Expand Up @@ -1567,6 +1580,21 @@ export const make = Effect.gen(function* () {
Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
);

const renewMcpClientSession: EnvironmentAuth["Service"]["renewMcpClientSession"] = (input) =>
input.peerLink
? sessions
.renew({
sessionId: input.sessionId,
ttl: MCP_CLIENT_SESSION_TTL,
...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
peerLink: true,
})
.pipe(
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
Effect.withSpan("EnvironmentAuth.renewMcpClientSession"),
)
: Effect.succeedNone;

const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
code,
access,
Expand Down Expand Up @@ -1626,6 +1654,7 @@ export const make = Effect.gen(function* () {
issueStartupPairingUrl,
authenticateMcpClient,
issueMcpClientSession,
renewMcpClientSession,
consumeMcpApprovalCode,
});
});
Expand Down
58 changes: 58 additions & 0 deletions apps/server/src/auth/SessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,20 @@ export class SessionStore extends Context.Service<
readonly replaceSessionId?: AuthSessionId;
}) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
/**
* Signs a live bearer session again with a later expiry, keeping its id, so everything bound
* to the session stays bound. None when it is revoked, expired, unknown or not a bearer session.
* The claims a row does not hold (`rtc`, `plk`) come from the caller's verified session.
*/
readonly renew: (input: {
readonly sessionId: AuthSessionId;
readonly ttl: Duration.Duration;
readonly runtimeModeCeiling?: RuntimeMode;
readonly peerLink?: boolean;
}) => Effect.Effect<
Option.Option<{ readonly token: string; readonly expiresAt: DateTime.Utc }>,
SessionCredentialInternalError
>;
readonly issueWebSocketToken: (
sessionId: AuthSessionId,
input?: {
Expand Down Expand Up @@ -770,6 +784,49 @@ const make = Effect.gen(function* () {
},
);

const renew: SessionStore["Service"]["renew"] = Effect.fn("SessionStore.renew")(
function* (input) {
const { sessionId } = input;
const issueError = (cause: unknown) => new SessionCredentialIssueError({ sessionId, cause });
const row = yield* authSessions.getById({ sessionId }).pipe(Effect.mapError(issueError));
// A DPoP session's key binding is not re-signed here; only bearer sessions renew.
if (
Option.isNone(row) ||
row.value.revokedAt !== null ||
row.value.method !== "bearer-access-token"
) {
return Option.none();
}
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(input.ttl) });
const claims: SessionClaims = {
v: 1,
kind: "session",
sid: sessionId,
sub: row.value.subject,
scopes: row.value.scopes,
method: row.value.method,
...(input.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
...(input.peerLink === true ? { plk: 1 as const } : {}),
iat: now.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = yield* encodeClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(issueError),
);
const signature = yield* signer.sign(encodedPayload);
// Only a session still live here moves; a revocation between the read and now wins.
const extended = yield* authSessions
.extend({ sessionId, expiresAt, now })
.pipe(Effect.mapError(issueError));
if (!extended) return Option.none();
const session = yield* loadActiveSession(sessionId).pipe(Effect.orElseSucceed(Option.none));
if (Option.isSome(session)) yield* emitUpsert(session.value);
return Option.some({ token: `${encodedPayload}.${signature}`, expiresAt });
},
);

const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
function* (token) {
if (devAuth?.matches(token)) {
Expand Down Expand Up @@ -1145,6 +1202,7 @@ const make = Effect.gen(function* () {
legacyCookieName,
issue,
verify,
renew,
issueWebSocketToken,
verifyWebSocketToken,
listActive,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ export const make = Effect.gen(function* () {
mcpModeLimitHeader: true,
linkFence: true,
linkedAppPairing: true,
linkRenewal: true,
mcpApprovalCodes: true,
mcpHostedApproval: true,
shellThreadFamilies: true,
Expand Down
70 changes: 67 additions & 3 deletions apps/server/src/mcp/toolkits/orchestrator/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mcpClientScopes, OrchestratorMcpFailure } from "@t3tools/contracts";
import { AuthSessionId, mcpClientScopes, OrchestratorMcpFailure } from "@t3tools/contracts";
import { OrchestratorToolkit } from "./tools.ts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
Expand Down Expand Up @@ -66,6 +66,61 @@ export const linkAppPairing = Effect.map(
),
);

/** The calling link's own session, renewed in place, so a link never needs a new pairing code. */
export const linkRenew = Effect.map(
Effect.serviceOption(EnvironmentAuth.EnvironmentAuth),
(environmentAuth) =>
McpToolAccess.reads(() =>
Effect.gen(function* () {
const { client } = yield* McpInvocationContext.McpInvocationContext;
if (client?.linked !== true) {
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "Only a linked T3 Code environment can renew its link.",
});
}
// The link's credential is the linked environment's, never one of its agents'.
if (client.senderThread !== undefined) {
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "Only the linked environment can renew its link, not its agents.",
});
}
if (Option.isNone(environmentAuth)) {
return yield* new OrchestratorMcpFailure({
code: "orchestration_error",
message: "This environment cannot renew links here.",
});
}
const renewed = yield* environmentAuth.value
.renewMcpClientSession({
sessionId: AuthSessionId.make(client.sessionId),
access: client.access,
peerLink: true,
})
.pipe(
Effect.mapError(
() =>
new OrchestratorMcpFailure({
code: "orchestration_error",
message: "The link could not be renewed here. The server log has details.",
}),
),
);
if (Option.isNone(renewed)) {
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "This link's session was revoked or has ended here, so it cannot be renewed.",
});
}
return {
accessToken: renewed.value.token,
expiresAt: DateTime.formatIso(renewed.value.expiresAt),
};
}),
),
);

const handlers = {
orchestrator_capabilities: McpToolAccess.reads((input) =>
Effect.gen(function* () {
Expand Down Expand Up @@ -291,9 +346,18 @@ const handlers = {
return yield* service.interruptThread(scope, input);
}),
),
} satisfies Omit<McpToolAccess.Handlers<typeof OrchestratorToolkit.tools>, "t3_link_app_pairing">;
} satisfies Omit<
McpToolAccess.Handlers<typeof OrchestratorToolkit.tools>,
"t3_link_app_pairing" | "t3_link_renew"
>;

export const layer = McpToolAccess.toLayer(
OrchestratorToolkit,
Effect.map(linkAppPairing, (pairing) => ({ ...handlers, t3_link_app_pairing: pairing })),
Effect.all([linkAppPairing, linkRenew]).pipe(
Effect.map(([pairing, renew]) => ({
...handlers,
t3_link_app_pairing: pairing,
t3_link_renew: renew,
})),
),
);
15 changes: 15 additions & 0 deletions apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
OrchestratorMcpEnvironmentUnlinkInput,
OrchestratorMcpEnvironmentUnlinkResult,
OrchestratorMcpLinkAppPairingResult,
OrchestratorMcpLinkRenewResult,
OrchestratorMcpCreateThreadsInput,
OrchestratorMcpCreateThreadsResult,
OrchestratorMcpDelegateTaskInput,
Expand Down Expand Up @@ -376,6 +377,19 @@ export const LinkAppPairingTool = Tool.make("t3_link_app_pairing", {
.annotate(Tool.Destructive, false)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.onlyForLinks);

// Offered to another environment's link only, never to an agent.
export const LinkRenewTool = Tool.make("t3_link_renew", {
description:
"For a linked T3 Code environment: its link's credential, signed again with a later expiry. The link keeps its session here.",
success: OrchestratorMcpLinkRenewResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies: [McpInvocationContext.McpInvocationContext],
})
.annotate(Tool.Title, "Renew this link")
.annotate(Tool.Destructive, false)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.onlyForLinks);

export const OrchestratorToolkit = Toolkit.make(
OrchestratorCapabilitiesTool,
DelegateTaskTool,
Expand All @@ -398,4 +412,5 @@ export const OrchestratorToolkit = Toolkit.make(
EnvironmentLinkTool,
EnvironmentUnlinkTool,
LinkAppPairingTool,
LinkRenewTool,
);
111 changes: 111 additions & 0 deletions apps/server/src/orchestration-v2/ModelAlertReactor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
modelAlertDestinations,
modelAlertFor,
overdueResumes,
type PeerLinkRenewalAlert,
recordLinkRenewal,
recordModelAlert,
recordUsageLimit,
RESUME_GRACE_MS,
Expand Down Expand Up @@ -633,3 +635,112 @@ it("a provider out of usage is tracked until its reset, and a healthy run clears
ProviderExhaustion.clear("magpie-primary-codex");
assert.equal(ProviderExhaustion.until("magpie-primary-codex", 1_000), null);
});

const linkAlert = (at: number): PeerLinkRenewalAlert => ({
type: "peer-link-renewal",
id: `peer-link-renewal:environment-box:${at}`,
environmentId: "environment-a",
environmentLabel: "primary-r720",
linkedEnvironmentId: "environment-box",
linkedLabel: "ASUS",
linkSession: "peer-link:environment-box:1",
expiresAt: "2026-12-19T00:00:00.000Z",
detail: "ASUS did not answer.",
occurredAt: DateTime.formatIso(DateTime.makeUnsafe(at)),
});

it("a link that keeps failing to renew alerts once, until it renews", () => {
let state = EMPTY_MODEL_ALERT_STATE;
const enqueued: Array<boolean> = [];
const step = (
outcome: Parameters<typeof recordLinkRenewal>[1],
destinations: ReadonlyArray<"watcher" | "webhook"> = ["watcher", "webhook"],
) => {
const result = recordLinkRenewal(state, outcome, destinations, 0);
state = result.state;
enqueued.push(result.enqueued);
};
// Every hourly sweep fails; only the first one queues anything.
for (const at of [1, 2, 3]) step({ _tag: "failed", alert: linkAlert(at) });
step({ _tag: "renewed", linkedEnvironmentId: "environment-box" });
// A later failure after a renewal is news again.
step({ _tag: "failed", alert: linkAlert(4) });
assert.deepEqual(enqueued, [true, false, false, false, true]);
assert.deepEqual(
state.outbox.map((entry) => [entry.alert.id, entry.destination]),
[
["peer-link-renewal:environment-box:1", "watcher"],
["peer-link-renewal:environment-box:1", "webhook"],
["peer-link-renewal:environment-box:4", "watcher"],
["peer-link-renewal:environment-box:4", "webhook"],
],
);
// Another link failing is its own alert.
const other = recordLinkRenewal(
state,
{ _tag: "failed", alert: { ...linkAlert(5), linkedEnvironmentId: "environment-air" } },
["watcher"],
0,
);
assert.equal(other.enqueued, true);
const message = watcherAlertMessage(linkAlert(1));
assert.include(message, "Link alert from primary-r720");
assert.include(message, "ASUS did not answer.");
});

it("a link alert counts only once queued, and only a delivered one keeps the link quiet", () => {
const WEEK = 7 * 24 * 60 * 60 * 1000;
// With nowhere to send it, nothing is marked, so the next sweep with a watcher alerts.
const nowhere = recordLinkRenewal(
EMPTY_MODEL_ALERT_STATE,
{ _tag: "failed", alert: linkAlert(1) },
[],
0,
);
assert.equal(nowhere.enqueued, false);
assert.deepEqual(nowhere.state.reported, {});
const queued = recordLinkRenewal(
nowhere.state,
{ _tag: "failed", alert: linkAlert(2) },
["watcher"],
0,
);
assert.equal(queued.enqueued, true);

// Never delivered and gone from the outbox: the link alerts again.
const expired = recordLinkRenewal(
queued.state,
{ _tag: "failed", alert: linkAlert(3) },
["watcher"],
WEEK + 1,
);
assert.equal(expired.enqueued, true);

// Delivered: quiet past the outbox's week, until it renews.
const delivered = afterDeliveryAttempt(queued.state, queued.state.outbox[0]!, true, 1);
assert.equal(delivered.outbox.length, 0);
const later = recordLinkRenewal(
delivered,
{ _tag: "failed", alert: linkAlert(4) },
["watcher"],
WEEK + 1,
);
assert.equal(later.enqueued, false);

// Linking again names a new session, so its first failure is news.
const relinked = recordLinkRenewal(
delivered,
{ _tag: "failed", alert: { ...linkAlert(5), linkSession: "peer-link:environment-box:2" } },
["watcher"],
2,
);
assert.equal(relinked.enqueued, true);
// A renewal clears every session's record for that link.
const renewed = recordLinkRenewal(
relinked.state,
{ _tag: "renewed", linkedEnvironmentId: "environment-box" },
[],
3,
);
assert.deepEqual(renewed.state.reported, {});
});
Loading
Loading