import { actingUserRequestOptions } from "@/agent/acting-user"; import { ApiRequestError, apiRequest } from "@/backend/api/request"; import { isCloudServerUrl } from "@/backend/api/server-url"; import { resolveBackendMode } from "@/backend/backend-mode"; import { getRuntimeActingUserAttribution } from "@/runtime-context"; import { resolveNotificationScope } from "@/utils/task-notifications.js"; import { buildMonitorResult } from "./monitor-result"; export const URL_MONITOR_MIN_INTERVAL_SECONDS = 60; const DEFAULT_URL_MONITOR_TIMEOUT_MS = 86_400_000; export interface UrlMonitorMatch { equals?: string[]; contains?: string; gt?: number; lt?: number; } export interface UrlMonitorArgs { description: string; url?: string; interval_seconds?: number; headers?: Record; select?: string; match?: UrlMonitorMatch; stop_on_match?: boolean; timeout_ms?: number; persistent?: boolean; command?: string; ws?: { url: string }; script?: string; backup_after_seconds?: number; backup_prompt?: string; toolCallId?: string; parentScope?: { agentId: string; conversationId: string }; } export interface UrlMonitorResult { content: Array<{ type: "text"; text: string }>; taskId: string; timeoutMs: number; persistent: false; } type Request = typeof apiRequest; export interface CloudUrlMonitorDeps { isCloud?: () => boolean; request?: Request; scope?: () => { conversationId: string } | undefined; } function isLettaCloud(): boolean { return resolveBackendMode() === "api" && isCloudServerUrl(); } export function isCloudMonitorId(taskId: string): boolean { return taskId.startsWith("cmon-"); } function cloudMonitorsPath(conversationId: string): string { return `/v1/conversations/${encodeURIComponent(conversationId)}/cloud-monitors`; } function isSavedConversation(conversationId: string): boolean { return conversationId !== "" && conversationId !== "default"; } const SECRET_REFERENCE = /\$(?:\{[A-Z_][A-Z0-9_]*\}|[A-Z_][A-Z0-9_]*)/; const CREDENTIAL_HEADER = /auth|cookie|token|secret|key|password|session/i; interface CloudUrlSource { type: "url"; url: string; interval_seconds: number; headers?: Record; select?: { type: "json"; path: string }; notify_when?: { type: "match" } & UrlMonitorMatch; stop_on_match?: boolean; } function validateHeaders(headers: unknown): Record | undefined { if (headers === undefined) return undefined; if ( typeof headers !== "object" || headers === null || Array.isArray(headers) || !Object.values(headers).every((value) => typeof value === "string") ) { throw new Error("Monitor headers must map header names to strings"); } const entries = Object.entries(headers as Record); for (const [name, value] of entries) { if (CREDENTIAL_HEADER.test(name) && !SECRET_REFERENCE.test(value)) { throw new Error( `Monitor header ${name} carries a credential, so its value must reference an agent secret ($NAME) instead of containing it`, ); } } return entries.length > 0 ? (headers as Record) : undefined; } function validateMatch(match: unknown): UrlMonitorMatch | undefined { if (match === undefined) return undefined; if (typeof match !== "object" || match === null || Array.isArray(match)) { throw new Error("Monitor match must be an object"); } const { equals, contains, gt, lt } = match as UrlMonitorMatch; const result: UrlMonitorMatch = {}; if (equals !== undefined) { if (!Array.isArray(equals) || !equals.every((v) => typeof v === "string")) { throw new Error("Monitor match.equals must be an array of strings"); } if (equals.length > 0) result.equals = equals; } if (contains !== undefined) { if (typeof contains !== "string" || contains === "") { throw new Error("Monitor match.contains must be a non-empty string"); } result.contains = contains; } for (const [key, value] of [ ["gt", gt], ["lt", lt], ] as const) { if (value === undefined) continue; if (typeof value !== "number" || !Number.isFinite(value)) { throw new Error(`Monitor match.${key} must be a number`); } result[key] = value; } if (Object.keys(result).length === 0) { throw new Error( "Monitor match needs at least one of equals, contains, gt or lt", ); } return result; } function buildCloudSource(args: UrlMonitorArgs, url: string): CloudUrlSource { const source: CloudUrlSource = { type: "url", url, interval_seconds: args.interval_seconds ?? URL_MONITOR_MIN_INTERVAL_SECONDS, }; const headers = validateHeaders(args.headers); if (headers) source.headers = headers; if (args.select !== undefined) { if ( typeof args.select !== "string" || args.select.split(".").some((segment) => segment === "") ) { throw new Error( "Monitor select must be a dot-separated path into the JSON response, such as 0.status", ); } source.select = { type: "json", path: args.select }; } const match = validateMatch(args.match); if (match) source.notify_when = { type: "match", ...match }; if (args.stop_on_match !== undefined) { if (typeof args.stop_on_match !== "boolean") { throw new Error("Monitor stop_on_match must be a boolean"); } if (args.stop_on_match && !match) { throw new Error("Monitor stop_on_match needs match"); } if (args.stop_on_match) source.stop_on_match = true; } return source; } function validateUrlMonitorArgs(args: UrlMonitorArgs): string { if (typeof args.description !== "string") { throw new Error("Monitor description is required"); } const otherSource = (typeof args.command === "string" && args.command.length > 0) || (typeof args.script === "string" && args.script.trim() !== "") || (args.ws !== undefined && args.ws?.url !== ""); if (otherSource) { throw new Error( "Monitor requires exactly one of command, ws, or script, or url", ); } if (args.persistent) { throw new Error( "Monitor url does not support persistent; set timeout_ms instead", ); } if ( args.backup_after_seconds !== undefined || args.backup_prompt !== undefined ) { throw new Error( "Monitor url does not support backup_after_seconds or backup_prompt", ); } let parsed: URL; try { parsed = new URL(String(args.url)); } catch { throw new Error("Monitor url must be an absolute http or https URL"); } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new Error("Monitor url must be an absolute http or https URL"); } const interval = args.interval_seconds; if ( interval !== undefined && (!Number.isInteger(interval) || interval < URL_MONITOR_MIN_INTERVAL_SECONDS) ) { throw new Error( `Monitor interval_seconds must be an integer of at least ${URL_MONITOR_MIN_INTERVAL_SECONDS}`, ); } if ( args.timeout_ms !== undefined && (!Number.isInteger(args.timeout_ms) || args.timeout_ms < 1000) ) { throw new Error("Monitor timeout_ms must be an integer of at least 1000"); } return parsed.toString(); } export async function startCloudUrlMonitor( args: UrlMonitorArgs, deps: CloudUrlMonitorDeps = {}, ): Promise { const url = validateUrlMonitorArgs(args); const source = buildCloudSource(args, url); if (!(deps.isCloud ?? isLettaCloud)()) { throw new Error( "Monitor url runs in Letta Cloud and is only available when connected to Letta Cloud. Use command with a polling loop instead.", ); } const scope = resolveNotificationScope(args.parentScope); if (!scope) { throw new Error("Monitor url needs an agent conversation to notify"); } if (!isSavedConversation(scope.conversationId)) { throw new Error( "Monitor url needs a saved conversation and is not available in the agent's default conversation. Use command with a polling loop instead.", ); } const timeoutMs = args.timeout_ms ?? DEFAULT_URL_MONITOR_TIMEOUT_MS; const request = deps.request ?? apiRequest; const created = await request<{ id: string }>( "POST", cloudMonitorsPath(scope.conversationId), { description: args.description, source, timeout_ms: timeoutMs, ...(args.toolCallId && { tool_call_id: args.toolCallId }), }, actingUserRequestOptions(scope.actingUserId), ); const taskId = created.id; return buildMonitorResult(taskId, timeoutMs, false); } export async function stopCloudUrlMonitor( taskId: string, deps: CloudUrlMonitorDeps = {}, ): Promise<{ killed: boolean }> { if (!(deps.isCloud ?? isLettaCloud)()) { return { killed: false, }; } const conversationId = (deps.scope ?? resolveNotificationScope)() ?.conversationId; if (!conversationId || !isSavedConversation(conversationId)) { return { killed: false, }; } const request = deps.request ?? apiRequest; let stopped: { status: string }; try { stopped = await request<{ status: string }>( "DELETE", `${cloudMonitorsPath(conversationId)}/${encodeURIComponent(taskId)}`, undefined, actingUserRequestOptions(getRuntimeActingUserAttribution()), ); } catch (error) { if (error instanceof ApiRequestError && error.status === 404) { return { killed: false, }; } throw error; } if (stopped.status !== "cancelled") { return { killed: false, }; } return { killed: true }; }