|
1 | 1 | import { tryCatch } from "@trigger.dev/core/utils"; |
2 | 2 | import type { Session } from "@trigger.dev/database"; |
3 | 3 | import { nanoid } from "nanoid"; |
| 4 | +import { prisma } from "~/db.server"; |
4 | 5 | import type { AuthenticatedEnvironment } from "~/services/apiAuth.server"; |
5 | 6 | import { S2RealtimeStreams } from "~/services/realtime/s2realtimeStreams.server"; |
6 | 7 | import { SESSION_CHANNEL_NAME_REGEX } from "~/services/realtime/sessionChannels.server"; |
7 | 8 | import { |
8 | 9 | canonicalSessionAddressingKey, |
| 10 | + resolveSessionByIdOrExternalId, |
9 | 11 | resolveSessionWithWriterFallback, |
10 | 12 | } from "~/services/realtime/sessions.server"; |
| 13 | +import { closeSession, sessionUpdateData } from "~/services/realtime/sessionWrites.server"; |
11 | 14 | import { getRealtimeStreamInstance } from "~/services/realtime/v1StreamsGlobal.server"; |
12 | 15 | import { ServiceValidationError } from "~/v3/services/common.server"; |
| 16 | +import { canonicalJson } from "../confirm/confirmation.server"; |
| 17 | +import type { McpPreviewRefusal, McpSubject } from "../gate/types"; |
| 18 | +import type { McpToolContext, McpToolResult } from "../gate/withMcpToolAuth.server"; |
13 | 19 | import type { McpToolDefinition } from "../registry.server"; |
14 | 20 | import { errorResult, resolveToolEnvironment, textResult } from "./define.server"; |
15 | | -import { defineWriteTool } from "./defineWrite.server"; |
16 | | -import { WriteSessionChannelInput } from "./schemas/sessions"; |
| 21 | +import { defineWriteTool, staleAnswer, staleApproval } from "./defineWrite.server"; |
| 22 | +import { plainError } from "./format/insights"; |
| 23 | +import { capText } from "./format/logFields"; |
| 24 | +import { renderSessionId } from "./format/sessions"; |
| 25 | +import { PREVIEW_UNSAFE, quoteForPreview } from "./format/webhooks"; |
| 26 | +import { startReadBudget } from "./readBudget.server"; |
| 27 | +import { |
| 28 | + CloseSessionInput, |
| 29 | + UpdateSessionInput, |
| 30 | + WriteSessionChannelInput, |
| 31 | +} from "./schemas/sessions"; |
| 32 | + |
| 33 | +const auth = { action: "write", subject: "sessions" } as const; |
| 34 | + |
| 35 | +const READ_BUDGET_MS = 10_000; |
| 36 | +const SHOWN_CHARS = 16_000; |
| 37 | +const STOPPED = { |
| 38 | + aborted: "The request was cancelled before the session was read; nothing changed.", |
| 39 | + timeout: "Reading the session took too long; nothing changed. Try again.", |
| 40 | +}; |
| 41 | +const SESSION_CHANGED = |
| 42 | + "The session was changed by another request before this ran; nothing changed. Call the tool again."; |
| 43 | + |
| 44 | +const CLOSED_UPDATE = "the session stays closed; only its tags and metadata change."; |
| 45 | + |
| 46 | +const NOTIFIED = { |
| 47 | + true: " A close message was sent on the session's input; a run waiting on it stops when it handles the message.", |
| 48 | + false: " The close message could not be sent on the session's input.", |
| 49 | + undefined: "", |
| 50 | +}; |
| 51 | + |
| 52 | +type Read = ReturnType<typeof startReadBudget>["read"]; |
| 53 | +type Plan<T> = { preview: string; value: T } | McpPreviewRefusal; |
| 54 | +type Build<A, T> = (args: A, environmentId: string, read: Read) => Promise<Plan<T>>; |
| 55 | + |
| 56 | +const sessionNotFound = (id: string) => |
| 57 | + `Session ${renderSessionId(id)} not found in this environment; list_sessions lists the sessions in this environment. Nothing changed.`; |
| 58 | + |
| 59 | +const revisionLine = (session: { updatedAt: Date }) => |
| 60 | + `Session revision ${session.updatedAt.toISOString()}: if the session changes before this runs, it is refused.`; |
| 61 | + |
| 62 | +const previewJson = (value: unknown) => |
| 63 | + canonicalJson(value).replace( |
| 64 | + PREVIEW_UNSAFE, |
| 65 | + (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}` |
| 66 | + ); |
| 67 | + |
| 68 | +function shown(value: unknown) { |
| 69 | + if (value === null || value === undefined) return "none"; |
| 70 | + return capText(previewJson(value), SHOWN_CHARS); |
| 71 | +} |
| 72 | + |
| 73 | +const shownTags = (tags: string[]) => (tags.length === 0 ? "none" : shown(tags)); |
| 74 | + |
| 75 | +async function findSession( |
| 76 | + environmentId: string, |
| 77 | + sessionId: string, |
| 78 | + read: Read |
| 79 | +): Promise<{ session: Session } | McpPreviewRefusal> { |
| 80 | + const found = await read(() => resolveSessionByIdOrExternalId(prisma, environmentId, sessionId)); |
| 81 | + if (!found.ok) return { refuse: STOPPED[found.reason] }; |
| 82 | + if (!found.value) return { refuse: sessionNotFound(sessionId) }; |
| 83 | + return { session: found.value }; |
| 84 | +} |
| 85 | + |
| 86 | +const sessionLabel = (session: Session) => |
| 87 | + `session ${session.friendlyId} of agent ${quoteForPreview(session.taskIdentifier)}`; |
| 88 | + |
| 89 | +async function updatePlan( |
| 90 | + args: UpdateSessionInput, |
| 91 | + environmentId: string, |
| 92 | + read: Read |
| 93 | +): Promise<Plan<Session>> { |
| 94 | + if (args.tags === undefined && args.metadata === undefined) { |
| 95 | + return { refuse: "No changes given: pass tags, metadata or both; nothing changed." }; |
| 96 | + } |
| 97 | + if (args.metadata && previewJson(args.metadata).length > SHOWN_CHARS) { |
| 98 | + return { |
| 99 | + refuse: `This metadata is too large to show in full for approval (the limit is ${SHOWN_CHARS.toLocaleString("en-US")} characters). Send smaller metadata; nothing changed.`, |
| 100 | + }; |
| 101 | + } |
| 102 | + const found = await findSession(environmentId, args.sessionId, read); |
| 103 | + if ("refuse" in found) return found; |
| 104 | + const { session } = found; |
| 105 | + |
| 106 | + const changes = [ |
| 107 | + ...(args.tags !== undefined && canonicalJson(args.tags) !== canonicalJson(session.tags) |
| 108 | + ? [`- Tags: ${shownTags(session.tags)} → ${shownTags(args.tags)}`] |
| 109 | + : []), |
| 110 | + ...(args.metadata !== undefined && |
| 111 | + canonicalJson(args.metadata) !== canonicalJson(session.metadata ?? null) |
| 112 | + ? [`- Metadata, replaced in full: ${shown(session.metadata)} → ${shown(args.metadata)}`] |
| 113 | + : []), |
| 114 | + ]; |
| 115 | + if (changes.length === 0) { |
| 116 | + return { |
| 117 | + refuse: `Session ${session.friendlyId} already has these tags and metadata; nothing changed.`, |
| 118 | + }; |
| 119 | + } |
| 120 | + |
| 121 | + const lines = [ |
| 122 | + `Update ${sessionLabel(session)}:`, |
| 123 | + ...changes, |
| 124 | + ...(session.closedAt ? [`It is closed; ${CLOSED_UPDATE}`] : []), |
| 125 | + "Its external ID, status and runs do not change.", |
| 126 | + revisionLine(session), |
| 127 | + ]; |
| 128 | + return { preview: lines.join("\n"), value: session }; |
| 129 | +} |
| 130 | + |
| 131 | +async function closePlan( |
| 132 | + args: CloseSessionInput, |
| 133 | + environmentId: string, |
| 134 | + read: Read |
| 135 | +): Promise<Plan<Session>> { |
| 136 | + const found = await findSession(environmentId, args.sessionId, read); |
| 137 | + if ("refuse" in found) return found; |
| 138 | + const { session } = found; |
| 139 | + if (session.closedAt) { |
| 140 | + return { refuse: `Session ${session.friendlyId} is already closed; nothing changed.` }; |
| 141 | + } |
| 142 | + |
| 143 | + const lines = [ |
| 144 | + `Close ${sessionLabel(session)} for good. A closed session can't be reopened: it accepts no more input and starts no more runs.`, |
| 145 | + session.currentRunId |
| 146 | + ? "A close message is sent on the session's input; a run waiting on it stops when it handles the message. This is best effort: the session is closed even if the message can't be sent." |
| 147 | + : "It has no current run, so no run is told.", |
| 148 | + `Reason: ${args.reason ? quoteForPreview(args.reason) : "none"}`, |
| 149 | + revisionLine(session), |
| 150 | + ]; |
| 151 | + return { preview: lines.join("\n"), value: session }; |
| 152 | +} |
| 153 | + |
| 154 | +function planPreview<A>(build: Build<A, unknown>) { |
| 155 | + return async (args: A, subject: McpSubject | null) => { |
| 156 | + if (!subject?.projectId || !subject.environmentId) return { refuse: "Environment not found" }; |
| 157 | + // The gate gives a preview no request signal, so only the deadline can stop its reads. |
| 158 | + const { read } = startReadBudget(READ_BUDGET_MS, new AbortController().signal); |
| 159 | + const plan = await build(args, subject.environmentId, read); |
| 160 | + return "refuse" in plan ? plan : plan.preview; |
| 161 | + }; |
| 162 | +} |
| 163 | + |
| 164 | +async function runPlan<A, T>( |
| 165 | + args: A, |
| 166 | + ctx: McpToolContext, |
| 167 | + build: Build<A, T>, |
| 168 | + act: (value: T, environment: AuthenticatedEnvironment) => Promise<McpToolResult> |
| 169 | +) { |
| 170 | + const { read } = startReadBudget(READ_BUDGET_MS, ctx.signal); |
| 171 | + const found = await read(() => resolveToolEnvironment(ctx)); |
| 172 | + if (!found.ok) return plainError(STOPPED[found.reason]); |
| 173 | + if (!found.value) return plainError("Environment not found"); |
| 174 | + const plan = await build(args, found.value.id, read); |
| 175 | + if ("refuse" in plan) return plainError(plan.refuse); |
| 176 | + return staleApproval(ctx, plan.preview, plainError) ?? act(plan.value, found.value); |
| 177 | +} |
| 178 | + |
| 179 | +/** A write refused because the session changed: stale for an approved call, plain otherwise. */ |
| 180 | +const changedAnswer = (ctx: McpToolContext) => |
| 181 | + ctx.confirmation ? staleAnswer(plainError) : plainError(SESSION_CHANGED); |
17 | 182 |
|
18 | 183 | type AppendChannelRecord = ( |
19 | 184 | environment: AuthenticatedEnvironment, |
@@ -86,6 +251,51 @@ export function createSessionsWriteTools( |
86 | 251 | ); |
87 | 252 | }, |
88 | 253 | }), |
| 254 | + defineWriteTool({ |
| 255 | + name: "update_session", |
| 256 | + title: "Update Session", |
| 257 | + description: |
| 258 | + "Replace a session's tags, its metadata, or both, like the public API's session update. Omitted fields keep their values; pass metadata null to clear it. This also works on a closed session. The external ID can't be changed.", |
| 259 | + shape: UpdateSessionInput.shape, |
| 260 | + approval: "configurable", |
| 261 | + auth, |
| 262 | + confirm: { preview: planPreview(updatePlan) }, |
| 263 | + run: (input, ctx) => |
| 264 | + runPlan(input, ctx, updatePlan, async (session) => { |
| 265 | + const { count } = await prisma.session.updateMany({ |
| 266 | + where: { id: session.id, updatedAt: session.updatedAt }, |
| 267 | + data: sessionUpdateData({ tags: input.tags, metadata: input.metadata }), |
| 268 | + }); |
| 269 | + if (count === 0) return changedAnswer(ctx); |
| 270 | + return textResult( |
| 271 | + `Updated session ${session.friendlyId}.${session.closedAt ? ` ${CLOSED_UPDATE}` : ""}` |
| 272 | + ); |
| 273 | + }), |
| 274 | + }), |
| 275 | + defineWriteTool({ |
| 276 | + name: "close_session", |
| 277 | + title: "Close Session", |
| 278 | + description: |
| 279 | + "Close a session for good, like the public API's session close. It accepts no more input and starts no more runs, and its current run is asked to stop (best effort). Optionally record a reason.", |
| 280 | + shape: CloseSessionInput.shape, |
| 281 | + approval: "configurable", |
| 282 | + auth, |
| 283 | + confirm: { preview: planPreview(closePlan) }, |
| 284 | + run: (input, ctx) => |
| 285 | + runPlan(input, ctx, closePlan, async (session, environment) => { |
| 286 | + const { closed, notified } = await closeSession({ |
| 287 | + session, |
| 288 | + environment, |
| 289 | + paramSession: input.sessionId, |
| 290 | + reason: input.reason, |
| 291 | + revision: session.updatedAt, |
| 292 | + }); |
| 293 | + if (!closed) return changedAnswer(ctx); |
| 294 | + return textResult( |
| 295 | + `Closed session ${session.friendlyId}.${NOTIFIED[String(notified) as keyof typeof NOTIFIED]}` |
| 296 | + ); |
| 297 | + }), |
| 298 | + }), |
89 | 299 | ]; |
90 | 300 | } |
91 | 301 |
|
|
0 commit comments