Multiplayer agent harness for work.
Stop discarding error information at the shared error paths (#2018)
Regan Bellccc7bee9cc44
diff --git a/docs/error-reporting.md b/docs/error-reporting.mdindex 579405392..4244bb3e3 100644--- a/docs/error-reporting.md+++ b/docs/error-reporting.md@@ -6,16 +6,18 @@ Use a separate project for deployments with different operators or data boundariReporting captures uncaught exceptions, unhandled promise rejections, HTTP handler and authentication delivery failures, and the core's operator error records. Recorded failures carry `error_code` and a matching grouping fingerprint. Recorded exceptions preserve their original stack; records without an exception carry the recording call's stack. Repeated capture of the same error object is deduplicated by the SDK. Ordinary console logs and expected failures outside these boundaries are not reported.-Only error events are enabled by default. Profiling, logs, replay, request instrumentation, and breadcrumbs are disabled. Sampled performance tracing is described below. Before transmission, an allowlist retains timestamps, release/environment, service/deployment, internal failure codes, built-in exception type, stack filenames, function names and line/column numbers, and handled status. Raw error messages, request bodies and headers, URLs, users, local variables, source context, ambient tags, and extras are discarded. Full error details remain in existing application logs. Deployment labels and release values must not contain secrets or personal data.+Only error events are enabled by default. Profiling, logs, replay and request instrumentation are disabled. Sampled performance tracing is described below. Events are sent unredacted: error messages, cause chains (as linked exceptions), stacks, and the failure's context (the `detail` passed to `reportFailure`, or the operator error record's category, code, message, scope and session) all reach Sentry so issues can be debugged there directly. Each recorded failure's log line also carries its Sentry event id (`[sentry=<id>]`).The SDK preserves existing fatal-error drain handlers. When no rejection handler exists it flushes and exits unsuccessfully. Core's explicit shutdown paths and web startup failures allow up to two seconds for pending error delivery. Delivery is best effort and never a substitute for application logs or infrastructure health alarms.-After deployment, verify a synthetic backend failure reaches the intended project with the expected release, environment, deployment and service. Check that its stack is readable and its payload contains no application content. Test alerts against that event before relying on notifications. Disable reporting by removing `SENTRY_DSN` and redeploying; retain the prior immutable application candidate for code rollback.+After deployment, verify a synthetic backend failure reaches the intended project with the expected release, environment, deployment and service. Check that its message and stack are readable. Test alerts against that event before relying on notifications. Disable reporting by removing `SENTRY_DSN` and redeploying; retain the prior immutable application candidate for code rollback.## Optional performance tracing-Set `SENTRY_TRACES_SAMPLE_RATE` (a fraction between 0 and 1; unset, 0, or an invalid value keeps tracing off) on a backend service that already has `SENTRY_DSN` to sample transactions. Start with `0.1`. Tracing enables the SDK's OpenTelemetry tracer for manual spans only; no automatic HTTP, database, model, or tool instrumentation is registered, so transactions contain no child spans and no trace headers are propagated to other services.+Set `SENTRY_TRACES_SAMPLE_RATE` (a fraction between 0 and 1; unset, 0, or an invalid value keeps tracing off) on a backend service that already has `SENTRY_DSN` to sample transactions. Start with `0.1`. Tracing enables the SDK's OpenTelemetry tracer for manual spans only; no automatic HTTP, database, model, or tool instrumentation is registered, and no trace headers are propagated to other services.-The core reports one transaction per sampled HTTP request except `/healthz` (`http.server`, named by the registered route template such as `GET /v1/sessions/:id`; unregistered or pattern-matched paths are reported as `METHOD /*` and deployment subdomain proxying as `/deployment-proxy/*`) and one per terminal run (`queue.task` `run`, with a `queue_wait` measurement and `surface` and `origin` tags drawn from fixed lists). Every transaction is rebuilt from an allowlist before transmission: timestamps, release, environment, service, deployment, the fixed name, span status, an HTTP status code, and millisecond measurements. Raw URLs, query strings, headers, bodies, user identifiers, host names, and span attributes are discarded.+The core reports one transaction per sampled HTTP request except `/healthz` (`http.server`, named by the registered route template such as `GET /v1/sessions/:id`; unregistered or pattern-matched paths are reported as `METHOD /*` and deployment subdomain proxying as `/deployment-proxy/*`) and one per terminal run (`queue.task` `run`, with a `queue_wait` measurement and `surface` and `origin` attributes). Transactions are sent without scrubbing: URLs including query strings, span descriptions and attributes, child spans, measurements, and any attached request or user context reach Sentry unchanged. Route names remain grouped by the registered template; the original request URL is retained as a span attribute.Browser timing uses `SENTRY_BROWSER_TRACES_SAMPLE_RATE` on the web server together with `SENTRY_BROWSER_DSN`; see the web-ui README.++Browser Sentry ignores plain network `TypeError` failures (`Failed to fetch`, `NetworkError when attempting to fetch resource.`, `Load failed`) and `AbortError` cancellations; HTTP 4xx/5xx failures still report.diff --git a/plugins/chassis/src/error-reporting.ts b/plugins/chassis/src/error-reporting.tsindex c1f1d1cbd..045348309 100644--- a/plugins/chassis/src/error-reporting.ts+++ b/plugins/chassis/src/error-reporting.ts@@ -1,63 +1,11 @@import type * as Sentry from "@sentry/node";-import { basename } from "node:path";-import { finishTiming, parseSampleRate, sanitizeTransactionEvent, type TimingResult } from "./timing.ts";+import { finishTiming, parseSampleRate, type TimingResult } from "./timing.ts";import { swallow } from "./errors.ts";const FLUSH_MS = 2_000;-const ERROR_TYPES = new Set([- "Error",- "TypeError",- "RangeError",- "ReferenceError",- "SyntaxError",- "URIError",- "EvalError",- "AggregateError",-]);let client: typeof Sentry | undefined;let tracing = false;-export function sanitizeErrorEvent(event: Sentry.ErrorEvent): Sentry.ErrorEvent {- const frames = (items: Sentry.StackFrame[] | undefined) =>- items?.map((frame) => ({- filename: frame.filename ? basename(frame.filename.split("?")[0]!) : undefined,- function: frame.function?.replace(/[^a-zA-Z0-9_.$<> [\]-]/g, "").slice(0, 160),- lineno: frame.lineno,- colno: frame.colno,- in_app: frame.in_app,- }));- return {- type: undefined,- event_id: event.event_id,- timestamp: event.timestamp,- platform: "node",- level: event.level,- environment: event.environment,- release: event.release,- tags: { service: event.tags?.service, deployment: event.tags?.deployment, error_code: event.tags?.error_code },- fingerprint: event.tags?.error_code ? ["{{ default }}", String(event.tags.error_code)] : undefined,- message: event.exception?.values?.length ? undefined : "Backend error; details retained in application logs",- exception: event.exception- ? {- values: event.exception.values?.map((exception) => ({- type: ERROR_TYPES.has(exception.type ?? "") ? exception.type : "Error",- value:- typeof event.tags?.error_code === "string"- ? event.tags.error_code- : "Details retained in application logs",- stacktrace: exception.stacktrace ? { frames: frames(exception.stacktrace.frames) } : undefined,- mechanism: exception.mechanism- ? {- type: exception.mechanism.type,- handled: exception.mechanism.handled,- }- : undefined,- })),- }- : undefined,- };-}-export function initializeErrorReporting(sdk: typeof Sentry,service: string,@@ -71,17 +19,17 @@ export function initializeErrorReporting(release: env.SENTRY_RELEASE ?? env.GIT_SHA,serverName: "",defaultIntegrations: false,- integrations: [sdk.onUncaughtExceptionIntegration()],+ integrations: [+ sdk.onUncaughtExceptionIntegration(),+ sdk.linkedErrorsIntegration(),+ sdk.extraErrorDataIntegration({ depth: 8 }),+ ],skipOpenTelemetrySetup: tracesSampleRate === 0,...(tracesSampleRate > 0 ? { tracesSampleRate } : {}),tracePropagationTargets: [],- sendDefaultPii: false,- maxBreadcrumbs: 0,attachStacktrace: true,sendClientReports: false,initialScope: { tags: { service, deployment: env.SENTRY_DEPLOYMENT ?? env.ORG_ID ?? env.CORE_ORG_ID } },- beforeSend: sanitizeErrorEvent,- beforeSendTransaction: (event) => sanitizeTransactionEvent(event, "node"),shutdownTimeout: FLUSH_MS,});client = sdk;@@ -98,8 +46,11 @@ export function initializeErrorReporting(});}-export function reportBackendError(error: unknown, code?: string): void {- client?.captureException(error, { tags: code && /^[a-zA-Z0-9_.:-]{1,120}$/.test(code) ? { error_code: code } : {} });+export function reportBackendError(error: unknown, code?: string, extra?: Record<string, unknown>): string | undefined {+ return client?.captureException(error, {+ ...(code ? { tags: { error_code: code }, fingerprint: ["{{ default }}", code] } : {}),+ ...(extra ? { extra } : {}),+ });}export type FinishTiming = (result: TimingResult) => void;diff --git a/plugins/chassis/src/errors.ts b/plugins/chassis/src/errors.tsindex de9a0949f..e4f5c3c06 100644--- a/plugins/chassis/src/errors.ts+++ b/plugins/chassis/src/errors.ts@@ -1,12 +1,112 @@export function errMessage(e: unknown, fallback?: string): string {if (e instanceof Error) return e.message;if (fallback !== undefined) return fallback;- if (typeof e === "string") return e;- if (e === null || (typeof e !== "object" && typeof e !== "function")) return String(e);- if ("message" in e && typeof e.message === "string") return e.message;+ return errorText(e);+}++function errorText(value: unknown): string {+ if (typeof value === "string") return value;+ if (value === null || (typeof value !== "object" && typeof value !== "function")) return String(value);+ if ("message" in value && typeof value.message === "string") return value.message;return "Unknown error";}+function describeCause(cause: unknown): string {+ if (!(cause instanceof Error)) return errorText(cause);+ const code = (cause as { code?: unknown }).code;+ const label = code !== undefined && code !== null && code !== "" ? `${cause.name} ${errorText(code)}` : cause.name;+ return cause.message ? `${label}: ${cause.message}` : label;+}++export function errChain(e: unknown): string {+ if (!(e instanceof Error)) return errorText(e);+ const parts = [e.message];+ const seen = new Set<unknown>();+ const messages = new Set([e.message]);+ const pending: unknown[] = [e];+ for (const cause of pending) {+ if (cause == null || seen.has(cause)) continue;+ seen.add(cause);+ const causeMessage = cause instanceof Error ? cause.message : errorText(cause);+ if (!messages.has(causeMessage)) parts.push(describeCause(cause));+ messages.add(causeMessage);+ if (cause instanceof Error) pending.push(cause.cause);+ if (cause instanceof AggregateError && Array.isArray(cause.errors)) pending.push(...cause.errors);+ }+ return parts.join(" <- ");+}++function errorFields(e: unknown): string {+ try {+ if (typeof e !== "object" || e === null) return "";+ const fields = Object.entries(Object.getOwnPropertyDescriptors(e))+ .filter(([key, descriptor]) => key !== "cause" && descriptor.enumerable)+ .map(([key, descriptor]) => {+ try {+ const seen = new Set<object>();+ const value = descriptor.value;+ const text =+ typeof value === "object" && value !== null+ ? JSON.stringify(value, (_key, item) => {+ if (typeof item === "bigint") return String(item);+ if (typeof item === "object" && item !== null) {+ if (seen.has(item)) return "[Circular]";+ seen.add(item);+ }+ return item;+ })+ : String(value);+ return `${key}=${descriptor.get ? "[Getter]" : text}`;+ } catch {+ return `${key}=[Unserializable]`;+ }+ });+ return fields.length ? ` [${fields.join(" ")}]` : "";+ } catch {+ return "";+ }+}++export function errDetail(e: unknown, seen = new Set<unknown>()): string {+ try {+ if (seen.has(e)) return "";+ seen.add(e);+ const frames =+ e instanceof Error+ ? (e.stack+ ?.split("\n")+ .slice(1)+ .map((line) => line.trim()) ?? [])+ : [];+ const stack = frames.filter(Boolean).join(" | ");+ const nested =+ e instanceof Error ? [e.cause, ...(e instanceof AggregateError && Array.isArray(e.errors) ? e.errors : [])] : [];+ const details = nested+ .filter((error) => error != null)+ .map((error) => errDetail(error, seen))+ .filter(Boolean);+ return `${errChain(e)}${errorFields(e)}${stack ? ` {stack: ${stack}}` : ""}${details.length ? ` {causes: ${details.join(" | ")}}` : ""}`;+ } catch {+ return "[Uninspectable error]";+ }+}+export function swallow(context: string, e: unknown): void {- console.warn(`[swallowed] ${context}: ${errMessage(e)}`);+ console.warn(`[swallowed] ${context}: ${errDetail(e)}`);+}++export function swallowAs<T>(context: string, fallback: T): (e: unknown) => T {+ return (e) => {+ swallow(context, e);+ return fallback;+ };+}++export function failureCode(context: string): string {+ return context+ .toLowerCase()+ .replace(/\s*:\s*/g, ":")+ .replace(/[^a-z0-9_.:-]+/g, "_")+ .replace(/^_+|_+$/g, "")+ .slice(0, 120);}diff --git a/plugins/chassis/src/timing.ts b/plugins/chassis/src/timing.tsindex 4c9550a4b..51167d2a3 100644--- a/plugins/chassis/src/timing.ts+++ b/plugins/chassis/src/timing.ts@@ -1,8 +1,6 @@import type * as Sentry from "@sentry/node";import { swallow } from "./errors.ts";-export type TransactionEvent = Sentry.Event & { type: "transaction" };-export type TimingStatus =| "ok"| "cancelled"@@ -25,63 +23,6 @@ export type TimingSdk = Pick<typeof Sentry, "setMeasurement">;const SPAN_STATUS_OK = 1;const SPAN_STATUS_ERROR = 2;-const NAME = /^[A-Z]{3,7} (\/(v[0-9]{1,3}|[a-z][a-z-]{0,31}|:[a-zA-Z]{1,32}|\*)){1,10}$|^(run|pageload)$/;-const OPS = new Set(["http.server", "http.client", "queue.task", "pageload"]);-const STATUSES = new Set<string>([- "ok",- "cancelled",- "unauthenticated",- "permission_denied",- "not_found",- "resource_exhausted",- "invalid_argument",- "internal_error",-]);-const TAG_KEYS = new Set(["service", "deployment"]);-const TAG_VALUE = /^[a-zA-Z0-9_.:-]{1,64}$/;-const HTTP_STATUS = /^([1-5][0-9]{2}|network)$/;-const setHas = (values: string[]) => {- const set = new Set(values);- return (value: string) => set.has(value);-};-const BUCKETS: Record<string, (value: string) => boolean> = {- surface: setHas([- "core",- "cron",- "external",- "inbound_file",- "keychain-ask",- "loop",- "monitor",- "secret-drop",- "shared_skill",- "slack",- "steer",- "swarm",- "web",- "webhook",- ]),- origin: setHas(["direct", "human", "ambient", "automation"]),- page: setHas([- "calendar",- "chats",- "contexts",- "crons",- "deploys",- "files",- "inbox",- "keychain",- "loops",- "memory",- "settings",- "skills",- "webhooks",- ]),- http_status: (value) => HTTP_STATUS.test(value),-};-const MEASUREMENTS = new Set(["queue_wait", "ttfb", "dom_content_loaded", "load", "fcp", "lcp"]);-const HEX = /^[a-f0-9]+$/;-export function parseSampleRate(value: string | undefined): number {const rate = Number(value ?? 0);return Number.isFinite(rate) && rate >= 0 && rate <= 1 ? rate : 0;@@ -113,65 +54,3 @@ export function finishTiming(sdk: TimingSdk, span: Sentry.Span, result: TimingReswallow("timing", error);}}--function scopeTags(tags: Record<string, unknown>): Record<string, string> {- return Object.fromEntries(- Object.entries(tags).filter(- ([key, value]) => TAG_KEYS.has(key) && typeof value === "string" && TAG_VALUE.test(value),- ),- ) as Record<string, string>;-}--function bucketed(data: Record<string, unknown>): Record<string, string> {- return Object.fromEntries(- Object.entries(data)- .filter(([key, value]) => Object.hasOwn(BUCKETS, key) && typeof value === "string")- .map(([key, value]) => [key, BUCKETS[key]!(value as string) ? (value as string) : "other"]),- );-}--export function sanitizeTransactionEvent(- event: TransactionEvent,- platform: "node" | "javascript",-): TransactionEvent | null {- const trace = event.contexts?.trace;- const measurements: NonNullable<Sentry.Event["measurements"]> = event.measurements ?? {};- const start = event.start_timestamp;- const end = event.timestamp;- if (- !NAME.test(event.transaction ?? "") ||- typeof start !== "number" ||- typeof end !== "number" ||- !Number.isFinite(start) ||- !Number.isFinite(end) ||- end < start ||- !trace ||- !HEX.test(trace.trace_id ?? "") ||- !HEX.test(trace.span_id ?? "") ||- !OPS.has(trace.op ?? "") ||- !STATUSES.has(trace.status ?? "")- )- return null;- return {- type: "transaction",- event_id: HEX.test(event.event_id ?? "") ? event.event_id : undefined,- transaction: event.transaction,- transaction_info: { source: "route" },- start_timestamp: start,- timestamp: end,- platform,- environment: event.environment,- release: event.release,- tags: { ...scopeTags(event.tags ?? {}), ...bucketed(trace.data ?? {}) },- contexts: {- trace: { trace_id: trace.trace_id, span_id: trace.span_id, op: trace.op, status: trace.status, origin: "manual" },- },- measurements: Object.fromEntries(- Object.entries(measurements).filter(- ([key, measurement]) =>- MEASUREMENTS.has(key) && Number.isFinite(measurement.value) && measurement.unit === "millisecond",- ),- ),- spans: [],- };-}diff --git a/plugins/web-ui/README.md b/plugins/web-ui/README.mdindex b70751cc6..722c11a46 100644--- a/plugins/web-ui/README.md+++ b/plugins/web-ui/README.md@@ -327,30 +327,24 @@ origin to the web application's connection policy.Reporting starts after authentication and stops on sign-out or an authenticationfailure. It is disabled during impersonation and when the browser DSN is unset.-Only uncaught errors and unhandled promise rejections are collected. Events retain-standard error types, release, and same-origin compiled asset filenames with line-and column numbers. Fingerprints use the sanitized error type, capture mechanism,-and last retained stack position. Identical asset locations group across release-label changes; changed asset hashes start separate groups. Without a retained-frame, grouping falls back to the sanitized type and mechanism.-Other stack frames and function names are omitted. Messages,-URLs, requests, user identities, content, attachments, breadcrumbs, replay, logs,-and tracing are excluded. A final transport gate rejects unsanitized SDK failures-and non-event envelopes. Requests omit cookies and referrers. The ingestion-server can still see the network source IP. Delivery is best effort.+It collects uncaught errors, unhandled promise rejections, and errors the client+catches and handles (tagged with an `error_code` naming the catch site and grouped+by it). Events carry the full error message, cause chain, stack, release, org and+signed-in user. Delivery is best effort.### Browser performance timingSet `SENTRY_BROWSER_TRACES_SAMPLE_RATE` (0 to 1, default 0) alongside `SENTRY_BROWSER_DSN` to samplebrowser timings; `0.1` is a reasonable start. Each timing is sampled independently at that rateand carries its own random trace id. A page reports one `pageload` transaction (time to first-byte, DOM content loaded, load, first and largest contentful paint, and a `page` tag drawn from-the fixed list of application views) and one `http.client` transaction per same-origin request+byte, DOM content loaded, load, first and largest contentful paint, and a `page` attribute for+the application view) and one `http.client` transaction per same-origin requestmade through the web client's shared fetch helper, measured to response headers and named by afixed `/api/<resource>` allowlist (`GET /api/sessions/*`) with the HTTP status. At most 200-timings are sent per page. URLs, query strings, identifiers, and request or response content are-never included; timings stop with error reporting on sign-out, authentication failure, and-impersonation.+timings are sent per page. The full page/request URL, including query strings, is retained as a+span attribute. Transactions, child spans, descriptions, attributes, and any attached request or+user context are sent without scrubbing. Timings stop with error reporting on sign-out,+authentication failure, and impersonation.## Personal AI accountsdiff --git a/plugins/web-ui/src/browser-errors.ts b/plugins/web-ui/src/browser-errors.tsindex 8a86a6447..05b5b087f 100644--- a/plugins/web-ui/src/browser-errors.ts+++ b/plugins/web-ui/src/browser-errors.ts@@ -1,26 +1,10 @@import type * as Browser from "@sentry/browser";-import type { init, ErrorEvent, StackFrame } from "@sentry/browser";+import type { init } from "@sentry/browser";import type { Me } from "./shell-state";import { parseDeepLink, UI_BASE } from "./deep-link.ts";-import {- finishTiming,- sanitizeTransactionEvent,- traceStatus,- type TimingResult,- type TransactionEvent,-} from "../../chassis/src/timing.ts";+import { finishTiming, traceStatus, type TimingResult } from "../../chassis/src/timing.ts";+import { errDetail, swallow } from "../../chassis/src/errors.ts";-const ERROR_TYPES = new Set([- "Error",- "TypeError",- "RangeError",- "ReferenceError",- "SyntaxError",- "URIError",- "EvalError",- "AggregateError",- "UnhandledRejection",-]);const MAX_TIMINGS_PER_PAGE = 200;const API_RESOURCES = new Set(["approvals",@@ -62,58 +46,6 @@ let timingBudget = 0;let largestContentfulPaint: number | undefined;let pageLoadReported = false;-function safeFrame(frame: StackFrame, origin: string): StackFrame[] {- try {- const url = new URL(frame.filename ?? "", origin);- const filename = url.pathname.match(/\/assets\/([a-zA-Z0-9_-]{1,100}-[a-zA-Z0-9_-]{8}\.js)$/)?.[1];- if (url.origin !== origin || !filename) return [];- const position = (value: number | undefined) => (Number.isSafeInteger(value) && value! > 0 ? value : undefined);- return [{ filename, lineno: position(frame.lineno), colno: position(frame.colno), in_app: true }];- } catch {- return [];- }-}--export function sanitizeBrowserError(event: ErrorEvent, origin: string, release?: string): ErrorEvent {- const sanitized: ErrorEvent = {- type: undefined,- event_id: /^[a-f0-9]{32}$/.test(event.event_id ?? "") ? event.event_id : undefined,- timestamp: Number.isFinite(event.timestamp) ? event.timestamp : undefined,- platform: "javascript",- level: "error",- release,- tags: { service: "web-ui-browser" },- exception: {- values: (event.exception?.values?.slice(-5) ?? [{}]).map((exception) => ({- type: ERROR_TYPES.has(exception.type ?? "") ? exception.type : "Error",- value: "Browser error; details omitted",- stacktrace: {- frames: exception.stacktrace?.frames?.slice(-50).flatMap((frame) => safeFrame(frame, origin)) ?? [],- },- mechanism: {- handled: false,- type:- exception.mechanism?.type === "auto.browser.global_handlers.onunhandledrejection"- ? "onunhandledrejection"- : "onerror",- },- })),- },- };- sanitized.fingerprint = [- "web-ui-browser-v1",- ...(sanitized.exception?.values ?? []).flatMap((exception) => {- const frame = exception.stacktrace?.frames?.at(-1);- return [- exception.type ?? "Error",- exception.mechanism?.type ?? "onerror",- frame ? `${frame.filename}:${frame.lineno ?? 0}:${frame.colno ?? 0}` : "no-app-frame",- ];- }),- ];- return sanitized;-}-function timing(op: string, name: string, startMs: number, result: TimingResult): void {if (!client || !sdk || timingBudget <= 0) return;timingBudget--;@@ -149,7 +81,7 @@ export function reportRequestTiming(url: string, method: string, startMs: numberif (target.origin !== window.location.origin) return;timing("http.client", `${/^[A-Z]{3,7}$/.test(method) ? method : "GET"} ${apiRouteName(target.pathname)}`, startMs, {status: status === null ? "internal_error" : traceStatus(status),- data: { http_status: status === null ? "network" : String(status) },+ data: { url: target.href, http_status: status === null ? "network" : String(status) },});}@@ -162,7 +94,7 @@ function reportPageLoad(): void {timing("pageload", "pageload", performance.timeOrigin, {status: "ok",endMs: performance.timeOrigin + navigation.loadEventEnd,- data: { page: view ?? "other" },+ data: { page: view ?? "other", url: navigation.name },measurements: {ttfb: navigation.responseStart,dom_content_loaded: navigation.domContentLoadedEventEnd,@@ -196,6 +128,12 @@ function startTiming(rate: number): void {}}+export function reportHandledError(context: string, error: unknown): void {+ console.warn(`[handled] ${context}: ${errDetail(error)}`);+ if (!client || !sdk) return;+ sdk.captureException(error, { tags: { error_code: context }, fingerprint: ["{{ default }}", context] });+}+export function stopBrowserErrors(): void {generation++;timingBudget = 0;@@ -213,52 +151,37 @@ export async function initializeBrowserErrors(me: Me): Promise<void> {const browser = await import("@sentry/browser");if (current !== generation) return;sdk = browser;- const safeEvents = new WeakSet<ErrorEvent | TransactionEvent>();client = browser.init({dsn,release,defaultIntegrations: false,- integrations: [browser.globalHandlersIntegration()],- sendDefaultPii: false,- maxBreadcrumbs: 0,+ integrations: [+ browser.globalHandlersIntegration(),+ browser.linkedErrorsIntegration(),+ browser.extraErrorDataIntegration({ depth: 8 }),+ ],attachStacktrace: true,sendClientReports: false,enableLogs: false,tracesSampleRate: rate,tracePropagationTargets: [],- transportOptions: { fetchOptions: { credentials: "omit", referrerPolicy: "no-referrer" } },- transport: (options) => {- const transport = browser.makeFetchTransport(options);- return {- flush: (timeout) => transport.flush(timeout),- send: (envelope) => {- const [item] = envelope[1];- if (- current !== generation ||- envelope[1].length !== 1 ||- (item?.[0].type !== "event" && item?.[0].type !== "transaction") ||- !safeEvents.has(item[1] as ErrorEvent | TransactionEvent)- )- return Promise.resolve({});- return transport.send(envelope);- },- };- },+ initialScope: { tags: { service: "web-ui-browser", org: me.org }, user: { username: me.user } },beforeSend: (event, hint) => {- if (current !== generation) return null;- hint.attachments = [];- const sanitized = sanitizeBrowserError(event, window.location.origin, release);- safeEvents.add(sanitized);- return sanitized;- },- beforeSendTransaction: (event) => {- if (current !== generation) return null;- const sanitized = sanitizeTransactionEvent(event, "javascript");- if (sanitized) safeEvents.add(sanitized);- return sanitized;+ const error = hint.originalException;+ return current !== generation ||+ (error instanceof Error &&+ (error.name === "AbortError" ||+ (error.name === "TypeError" &&+ ["Failed to fetch", "NetworkError when attempting to fetch resource.", "Load failed"].includes(+ error.message,+ ))))+ ? null+ : event;},+ beforeSendTransaction: (event) => (current === generation ? event : null),});- } catch {+ } catch (error) {+ swallow("browser error reporting initialization", error);if (current === generation) client = undefined;}if (client) startTiming(rate);diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 4f8210323..1110309a8 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -207,6 +207,7 @@ import { decorateTextCodeBlocks } from "./text-code";import { createTranscriptViewport } from "./transcript-viewport";import { suggestedActivities } from "./suggested-activities";+import { reportHandledError } from "./browser-errors.ts";installMarkdownSanitizer();@@ -883,8 +884,8 @@ export function createChatSurface(const rawEarlier = page.earlierEntries ?? 0;chatState.earlierCount = currentEarlierCount(chatState.forkSession ?? {}, rawEarlier);chatState.transcriptAnchorSeq = rawEarlier > 0 ? (page.entries?.[0]?.seq ?? null) : null;- } catch {- void 0;+ } catch (error) {+ reportHandledError("web:transcript_refresh", error);}drawActiveChat(agent);}@@ -908,7 +909,8 @@ export function createChatSurface(let active: Awaited<ReturnType<typeof activeRunForThread>>;try {active = await activeRunForThread(threadRef);- } catch {+ } catch (error) {+ reportHandledError("web:reattach_active_run", error);return;}if (agent !== chatState.agent || threadRef !== chatState.threadRef || agent.state.isStreaming) return;@@ -940,7 +942,8 @@ export function createChatSurface(let activeRun: Awaited<ReturnType<typeof activeRunForThread>>;try {activeRun = await activeRunForThread(threadRef);- } catch {+ } catch (error) {+ reportHandledError("web:resume_active_run", error);return false;}if (agent === chatState.agent && threadRef === chatState.threadRef)@@ -1404,8 +1407,8 @@ export function createChatSurface(scrollerNow.scrollTop = priorTop + (scrollerNow.scrollHeight - priorHeight);scrollerNow.style.scrollBehavior = prev;});- } catch {- void 0;+ } catch (error) {+ reportHandledError("web:load_earlier", error);} finally {if (agent === chatState.agent && sessionId === chatState.sessionId && chatState.loadingEarlier) {chatState.loadingEarlier = false;diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex ff8bd99c6..b6dfe75fb 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -1,4 +1,4 @@-import { reportRequestTiming, stopBrowserErrors } from "./browser-errors.ts";+import { reportHandledError, reportRequestTiming, stopBrowserErrors } from "./browser-errors.ts";import { captureMessage, stopAnalytics } from "./product-analytics.ts";import { streamedAnswer } from "./timeline.ts";import { EventType } from "@tanstack/ai/client";@@ -364,7 +364,10 @@ export function unresolvedApprovals(approvals: PendingApproval[]): PendingApprovexport function fetchSessionApprovals(id: string): Promise<{ approvals: PendingApproval[] } | null> {return api<{ approvals: PendingApproval[] }>(`/api/sessions/${encodeURIComponent(id)}/approvals`).then((result) => ({ approvals: unresolvedApprovals(result.approvals) }))- .catch(() => null);+ .catch((error: unknown) => {+ reportHandledError("web:approvals_fetch", error);+ return null;+ });}export async function fetchEntry(sessionId: string, seq: number): Promise<SessionEntry> {diff --git a/plugins/web-ui/test/browser-errors.test.ts b/plugins/web-ui/test/browser-errors.test.tsindex 76c906948..1d978e28d 100644--- a/plugins/web-ui/test/browser-errors.test.ts+++ b/plugins/web-ui/test/browser-errors.test.ts@@ -1,68 +1,12 @@import assert from "node:assert/strict";import { test } from "node:test";-import { sanitizeBrowserError, initializeBrowserErrors, stopBrowserErrors } from "../src/browser-errors.ts";+import { initializeBrowserErrors, reportHandledError, stopBrowserErrors } from "../src/browser-errors.ts";import { browserErrorConfig } from "../server/browser-error-config.ts";+import { ApiError } from "../src/core-bridge.ts";import type { Me } from "../src/shell-state.ts";const origin = "https://app.example.com";-test("browser errors discard content and retain only local asset stack positions", () => {- const event = sanitizeBrowserError(- {- type: undefined,- event_id: "a".repeat(32),- timestamp: 123,- message: "secret",- user: { email: "[email protected]" },- request: { url: `${origin}/s/secret`, headers: { authorization: "secret" } },- breadcrumbs: [{ message: "secret" }],- extra: { content: "secret" },- contexts: { trace: { trace_id: "secret", span_id: "secret" } },- tags: { secret: "secret" },- release: "secret",- exception: {- values: [- {- type: "TypeError",- value: "secret",- mechanism: { type: "auto.browser.global_handlers.onunhandledrejection", data: { secret: "secret" } },- stacktrace: {- frames: [- {- filename: `${origin}/web/assets/main-Abc12345.js?secret#secret`,- function: "secret",- lineno: 42,- colno: 8,- vars: { secret: "secret" },- pre_context: ["secret"],- },- { filename: "https://secret.example.com/assets/main-Abc12345.js", lineno: 2 },- { filename: `${origin}/s/secret`, lineno: 3 },- { filename: "data:secret", lineno: 4 },- { filename: `${origin}/assets/main-Abc12345.js`, lineno: -1, colno: Infinity },- ],- },- },- { type: "secret", value: "secret" },- ],- },- },- origin,- "release-1",- );- assert.equal(JSON.stringify(event).includes("secret"), false);- assert.equal(JSON.stringify(event).includes("https:"), false);- assert.equal(event.release, "release-1");- assert.deepEqual(event.tags, { service: "web-ui-browser" });- assert.equal(event.exception?.values?.[0]?.type, "TypeError");- assert.equal(event.exception?.values?.[1]?.type, "Error");- assert.deepEqual(event.exception?.values?.[0]?.stacktrace?.frames, [- { filename: "main-Abc12345.js", lineno: 42, colno: 8, in_app: true },- { filename: "main-Abc12345.js", lineno: undefined, colno: undefined, in_app: true },- ]);- assert.equal(event.exception?.values?.[0]?.mechanism?.type, "onunhandledrejection");-});-test("browser config is opt-in and does not expose a backend secret DSN", () => {assert.equal(browserErrorConfig({ SENTRY_DSN: "https://public:[email protected]/1" }), undefined);assert.deepEqual(@@ -93,43 +37,7 @@ test("disabled and impersonated reporting never requires a browser SDK", async (stopBrowserErrors();});-test("browser grouping separates minified locations without using private content", () => {- const makeEvent = (colno: number, secret = "secret", asset = "main-Abc12345.js") => ({- type: undefined,- fingerprint: [secret],- message: secret,- exception: {- values: [- {- type: "TypeError",- value: secret,- stacktrace: {- frames: [- { filename: `${origin}/assets/caller-Abc12345.js`, lineno: 1, colno: 12 },- { filename: `${origin}/assets/${asset}?${secret}`, lineno: 1, colno, function: secret },- { filename: `https://external.example.com/${secret}`, lineno: 1, colno: 99 },- ],- },- },- ],- },- });- const first = sanitizeBrowserError(makeEvent(100), origin, "release-1").fingerprint;- assert.deepEqual(first, ["web-ui-browser-v1", "TypeError", "onerror", "main-Abc12345.js:1:100"]);- assert.notDeepEqual(first, sanitizeBrowserError(makeEvent(101), origin, "release-1").fingerprint);- assert.deepEqual(- first,- sanitizeBrowserError(makeEvent(100, "other-private-content"), origin, "release-2").fingerprint,- );- assert.notDeepEqual(first, sanitizeBrowserError(makeEvent(100, "secret", "main-Def67890.js"), origin).fingerprint);- const fallback = sanitizeBrowserError(- { type: undefined, exception: { values: [{ type: "secret", value: "secret", mechanism: { type: "secret" } }] } },- origin,- ).fingerprint;- assert.deepEqual(fallback, ["web-ui-browser-v1", "Error", "onerror", "no-app-frame"]);-});--test("SDK processing failures cannot bypass browser event redaction", async () => {+test("browser errors keep HTTP failures and their context while dropping network failures and aborts", async () => {const realFetch = globalThis.fetch;const realWindow = Object.getOwnPropertyDescriptor(globalThis, "window");const sent: string[] = [];@@ -140,28 +48,35 @@ test("SDK processing failures cannot bypass browser event redaction", async () =Object.defineProperty(globalThis, "window", { configurable: true, value: { location: { origin } } });try {await initializeBrowserErrors({- user: "test",- org: "test",+ user: "[email protected]",+ org: "acme",browserErrors: { dsn: "https://[email protected]/1" },});const sdk = await import("@sentry/browser");- const client = sdk.getClient()!;- sdk.captureException(new Error("private original event"));+ for (const message of ["Failed to fetch", "NetworkError when attempting to fetch resource.", "Load failed"]) {+ reportHandledError("web:network", new TypeError(message));+ sdk.captureException(new TypeError(message));+ }+ reportHandledError("web:network", new DOMException("request cancelled", "AbortError"));+ sdk.captureException(new DOMException("request cancelled", "AbortError"));+ const body = { error: { details: { reason: "db down" } } };+ reportHandledError(+ "web:approvals_fetch",+ Object.assign(new ApiError("approvals 500", 500, body), { cause: new Error("db down") }),+ );await sdk.flush(1000);assert.equal(sent.length, 1);- assert.equal(sent[0]!.includes("private"), false);- const beforeSend = client.getOptions().beforeSend;- client.getOptions().beforeSend = () => {- throw new Error("private SDK failure");- };- sdk.captureException(new Error("private trigger"));- await sdk.flush(1000);- assert.equal(sent.length, 1);- client.getOptions().beforeSend = beforeSend;- client.addEventProcessor(() => {- throw new Error("private processor failure");- });- sdk.captureException(new Error("private processor trigger"));+ const event = JSON.parse(sent[0]!.split("\n")[2]!);+ const values = event.exception.values.map((value: { value: string }) => value.value);+ assert.ok(values.includes("approvals 500"));+ assert.ok(values.includes("db down"));+ assert.equal(event.contexts.ApiError.status, 500);+ assert.deepEqual(event.contexts.ApiError.body, body);+ assert.equal(event.tags.error_code, "web:approvals_fetch");+ assert.deepEqual(event.fingerprint, ["{{ default }}", "web:approvals_fetch"]);+ assert.equal(event.user.username, "[email protected]");+ stopBrowserErrors();+ sdk.captureException(new Error("after stop"));await sdk.flush(1000);assert.equal(sent.length, 1);} finally {diff --git a/plugins/web-ui/test/browser-timing.test.ts b/plugins/web-ui/test/browser-timing.test.tsindex 4565051dc..5bbdcdee1 100644--- a/plugins/web-ui/test/browser-timing.test.ts+++ b/plugins/web-ui/test/browser-timing.test.ts@@ -94,7 +94,7 @@ const me = (tracesSampleRate?: number) => ({browserErrors: { dsn: "https://[email protected]/1", release: "release-1", tracesSampleRate },});-test("real browser SDK sends sanitized page load and request timings when sampled", async () => {+test("real browser SDK preserves page URLs, request data and child spans when sampled", async () => {await withBrowser(async (sent) => {await initializeBrowserErrors(me(1));const sdk = await import("@sentry/browser");@@ -136,8 +136,8 @@ test("real browser SDK sends sanitized page load and request timings when sample});await sdk.flush(1000);const payload = JSON.stringify(sent);- assert.equal(payload.includes("private"), false);- assert.equal(payload.includes("0f3a9c1e"), false);+ assert.equal(payload.includes("private"), true);+ assert.equal(payload.includes("0f3a9c1e"), true);const items = sent.map((envelope) => [envelope[1]!.type, envelope[2]!.transaction, envelope[2]]);assert.deepEqual(items.map(([type, name]) => [type, name]),@@ -146,12 +146,18 @@ test("real browser SDK sends sanitized page load and request timings when sample["transaction", "GET /api/sessions/*"],["transaction", "PUT /api/ui-state"],["transaction", "POST /api/runs"],+ ["transaction", "GET /api/private/1234"],["transaction", "GET /api/direct"],],);const pageload = items[0]![2]!;- assert.deepEqual(pageload.tags, { page: "chats" });- assert.equal(pageload.contexts.trace.data, undefined);+ assert.deepEqual(pageload.tags, { service: "web-ui-browser", org: "private-org" });+ assert.equal(pageload.contexts.trace.data.page, "chats");+ assert.equal(pageload.contexts.trace.data.url, `${origin}/s/private-session?token=private`);+ assert.equal(+ items[1]![2]!.contexts.trace.data.url,+ `${origin}/api/sessions/0f3a9c1e-1d2b-4c5d-8e9f-abcdef012345/entries?after=private`,+ );assert.deepEqual(pageload.measurements, {ttfb: { value: 120, unit: "millisecond" },dom_content_loaded: { value: 800, unit: "millisecond" },@@ -164,19 +170,15 @@ test("real browser SDK sends sanitized page load and request timings when sampleassert.equal(pageload.platform, "javascript");assert.equal(items[1]![2]!.contexts.trace.status, "ok");assert.equal(items[2]![2]!.contexts.trace.status, "invalid_argument");- assert.deepEqual(items[3]![2]!.tags, { http_status: "network" });+ assert.equal(items[3]![2]!.contexts.trace.data.http_status, "network");assert.equal(items[3]![2]!.contexts.trace.status, "internal_error");- assert.deepEqual(items[4]![2]!.spans, []);- assert.deepEqual(items[4]![2]!.tags, {});+ assert.equal(items[5]![2]!.spans[0].description, "private");+ assert.equal(items[5]![2]!.request.url, "private");+ assert.equal(items[5]![2]!.tags.private, "private");+ assert.equal(items[5]![2]!.contexts.trace.data.private, 1);const traceIds = new Set(items.slice(0, 4).map(([, , event]) => event!.contexts.trace.trace_id));assert.equal(traceIds.size, 4);- for (const [, , event] of items) {- assert.equal(event!.user, undefined);- assert.equal(event!.request, undefined);- assert.equal(event!.breadcrumbs, undefined);- assert.deepEqual(Object.keys(sent[0]![0]!).sort(), ["event_id", "sdk", "sent_at"]);- }- assert.doesNotMatch(JSON.stringify(sent.map((envelope) => envelope[0]!.trace)), /private|user|segment/);+ assert.equal(pageload.user.username, "private-user");});});diff --git a/src/admin/error-log.ts b/src/admin/error-log.tsindex a0e52343c..ac898e363 100644--- a/src/admin/error-log.ts+++ b/src/admin/error-log.ts@@ -36,7 +36,7 @@ export function withErrorReporting(store: ErrorLog): ErrorLog {...store,record(event, error) {if (!errorAlreadyReported(error)) {- reportBackendError(error ?? new Error("Recorded backend failure"), `${event.category}:${event.code}`);+ reportBackendError(error ?? new Error(event.message), `${event.category}:${event.code}`, { ...event });markErrorReported(error);}store.record(event);diff --git a/src/api/server.ts b/src/api/server.tsindex 2ef8d41e4..ebc8285b0 100644--- a/src/api/server.ts+++ b/src/api/server.ts@@ -541,7 +541,7 @@ function buildServer(app: App, deps: ServerOptions, allowUnsignedSourceAuth: boofinishTiming({name: `${req.method ?? "GET"} ${requestNames.get(req) ?? "/*"}`,status: res.writableFinished ? traceStatus(res.statusCode) : "cancelled",- data: { http_status: res.writableFinished ? String(res.statusCode) : undefined },+ data: { url: req.url, http_status: res.writableFinished ? String(res.statusCode) : undefined },}),);req.on("error", () => res.destroy());diff --git a/src/core/orchestrator/sandboxes.ts b/src/core/orchestrator/sandboxes.tsindex 81ef0004c..be20158a8 100644--- a/src/core/orchestrator/sandboxes.ts+++ b/src/core/orchestrator/sandboxes.ts@@ -135,7 +135,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {const recordScratchLifecycle = (action: string,handle?: SandboxHandle,- timing?: { releasedAt: number; cleanupMs: number },+ extra?: { releasedAt?: number; cleanupMs?: number; error?: string },): void => {deps.auditLog?.record({at: Date.now(),@@ -151,7 +151,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {startedAt: scratchStartedAt,readyAt: scratchReadyAt,provisionMs: scratchBox.provisionMs,- ...timing,+ ...extra,}),});};@@ -161,15 +161,17 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {};let ownerAuthProvisionInFlight: Promise<SandboxHandle> | null = null;const destroyEphemeralHandle = async (handle: SandboxHandle): Promise<void> => {+ const errors: unknown[] = [];for (let attempt = 1; attempt <= 3; attempt++) {try {await deps.sandbox.teardown(handle, { destroy: true });return;- } catch {+ } catch (error) {+ errors.push(error);if (attempt < 3) await sleep(50 * attempt);}}- throw new Error("Disposable sandbox destruction failed");+ throw new AggregateError(errors, "Disposable sandbox destruction failed");};const scrubOwnerAuthHandle = async (handle: SandboxHandle): Promise<void> => {if (!deps.keychain || !isolateOwnerKeychain) return;@@ -557,7 +559,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {})().catch((error) => {scratchProvisionInFlight = null;if (error instanceof SandboxProvisionCleanupError) scratchBox.pending = error.handle;- recordScratchLifecycle("provision_failed", scratchBox.pending ?? undefined);+ recordScratchLifecycle("provision_failed", scratchBox.pending ?? undefined, { error: errMessage(error) });throw error;});return scratchProvisionInFlight;@@ -719,7 +721,8 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {const reclaimBox = async (): Promise<void> => {let ownerCleanupError: unknown;let scratchCleanupError: unknown;- if (ownerAuthProvisionInFlight) await ownerAuthProvisionInFlight.catch(() => {});+ if (ownerAuthProvisionInFlight)+ await ownerAuthProvisionInFlight.catch(swallowAs("orchestrator: owner auth provision", undefined));ownerAuthProvisionInFlight = null;const reachEntries = [...reachBoxes.entries()];reachBoxes.clear();@@ -735,10 +738,12 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {}}if (keepReachWarm) {- await deps.sandbox.teardown(h, { keepWarm: true }).catch(() => {});+ await deps.sandbox+ .teardown(h, { keepWarm: true })+ .catch(swallowAs("orchestrator: keep warm teardown", undefined));return;}- await deps.sandbox.teardown(h).catch(() => {});+ await deps.sandbox.teardown(h).catch(swallowAs("orchestrator: teardown", undefined));}),);const ownerHandle = ownerAuthBox.handle ?? ownerAuthBox.pending;@@ -773,7 +778,8 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {);}}- if (scratchProvisionInFlight) await scratchProvisionInFlight.catch(() => {});+ if (scratchProvisionInFlight)+ await scratchProvisionInFlight.catch(swallowAs("orchestrator: scratch provision", undefined));scratchProvisionInFlight = null;const scratchHandle = scratchBox.handle ?? scratchBox.pending;if (scratchHandle) {@@ -786,17 +792,18 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {releasedAt: Date.now(),cleanupMs: Date.now() - cleanupStart,});- } catch {- scratchCleanupError = new Error("Disposable sandbox destruction failed");+ } catch (error) {+ scratchCleanupError = error instanceof Error ? error : new Error(errMessage(error));recordScratchLifecycle("release_failed", scratchHandle, {releasedAt: Date.now(),cleanupMs: Date.now() - cleanupStart,+ error: errMessage(error),});deps.errors?.record({category: "sandbox",code: "scratch_destroy_failed",- message: "Disposable sandbox destruction failed",+ message: errMessage(error),scopeLabel: scopeId,sessionId: session.id,},@@ -819,7 +826,9 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {await clearTurnFiles(handle);} finally {await deps.sandbox.teardown(handle, {- keepWarm: await hasLiveProcesses(handle, memoryScopeId).catch(() => true),+ keepWarm: await hasLiveProcesses(handle, memoryScopeId).catch(+ swallowAs("orchestrator: live process check", true),+ ),});}})(),@@ -830,7 +839,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {if (result.status === "rejected") swallow("resource sandbox release", result.reason);resourceHandles.clear();resourcePendingHandles.clear();- if (provisionInFlight) await provisionInFlight.catch(() => {});+ if (provisionInFlight) await provisionInFlight.catch(swallowAs("orchestrator: provision", undefined));provisionInFlight = null;const handle = box.handle ?? box.pending;box.handle = null;diff --git a/src/cron/authority.ts b/src/cron/authority.tsindex 80dcf62ca..4e8ff3fe7 100644--- a/src/cron/authority.ts+++ b/src/cron/authority.ts@@ -3,6 +3,7 @@ import type { TriggerSpec } from "../triggers/run-trigger.ts";import type { CapabilityClaims } from "../auth/capability-token.ts";import type { App } from "../api/app.ts";import type { AdminService } from "../admin/admin-service.ts";+import { errMessage } from "../util/errors.ts";type TriggerAuthority = Pick<TriggerSpec,@@ -30,7 +31,12 @@ export async function unattendedGrantRefusal(if (!(await app.samePerson(cron.owner, capability.actorId))) return "only the cron owner may set unattended grants";if (!cron.ownerScopeId.startsWith("personal:") || (cron.runAs !== undefined && cron.runAs !== "owner"))return "unattended grants require a personal-scope cron that runs as its owner";- const status = await admin?.adminStatusOf({ id: capability.actorId, type: "internal" }).catch(() => undefined);+ let status: Awaited<ReturnType<AdminService["adminStatusOf"]>> | undefined;+ try {+ status = await admin?.adminStatusOf({ id: capability.actorId, type: "internal" });+ } catch (e) {+ return `unattended grants could not confirm the cron owner is a current org admin: ${errMessage(e)}`;+ }if (!status?.isAdmin) return "unattended grants require the cron owner to be a current org admin";return null;}diff --git a/src/directory/person.ts b/src/directory/person.tsindex 63f40fa67..3fc72fb37 100644--- a/src/directory/person.ts+++ b/src/directory/person.ts@@ -1,3 +1,5 @@+import { swallowAs } from "../util/errors.ts";+export interface PrincipalLinkResolver {canonical(key: string): string | undefined;aliases(key: string): readonly string[];@@ -59,7 +61,10 @@ export async function samePersonInDirectory(): Promise<boolean> {if (samePerson(a, b)) return true;if (!personKey(a) || !personKey(b)) return false;- const [ma, mb] = await Promise.all([directory.get(a).catch(() => null), directory.get(b).catch(() => null)]);+ const [ma, mb] = await Promise.all([+ directory.get(a).catch(swallowAs("samePerson: directory lookup", null)),+ directory.get(b).catch(swallowAs("samePerson: directory lookup", null)),+ ]);const bKeys = personKeys(mb, b);for (const key of personKeys(ma, a)) if (bKeys.has(key)) return true;return false;@@ -69,7 +74,7 @@ export async function samePersonMatcher(directory: { get(principalId: string): Promise<RosterPerson | null> },actorId: string,): Promise<(id: string) => Promise<boolean>> {- const row = await directory.get(actorId).catch(() => null);+ const row = await directory.get(actorId).catch(swallowAs("directory lookup", null));const keys = personKeys(row, actorId);return async (id) => {if (keys.has(personKey(id))) return true;diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex 9ca724cf9..d14760bc6 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -742,7 +742,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):...sandboxLog({ tool: "execute", ...scopeNote }),callId,isError: true,- result: "Command execution failed.",+ result: `Command execution failed: ${redactSecrets(errMessage(e))}`,});throw e;}diff --git a/src/memory/disclosure.ts b/src/memory/disclosure.tsindex 14779ddaa..4e0e86e6b 100644--- a/src/memory/disclosure.ts+++ b/src/memory/disclosure.ts@@ -6,6 +6,7 @@ import type { CurrentScopeMembers, IsCurrentSharedScopeMember } from "../resolutimport { legacyMemoryRecords, parseMemoryRecords, restoreMemoryRecords, type MemoryRecords } from "./records.ts";import { memoryBlocks } from "./notebook.ts";import { queryBullets, recallBody, type MemoryService } from "./memory-service.ts";+import { swallow, swallowAs } from "../util/errors.ts";type RecordEntry = MemoryRecords["records"][number];@@ -38,7 +39,7 @@ function memoryDisclosurePolicy(input: MemoryDisclosure) {const once = (key: string, read: () => Promise<boolean>) => {let decision = decisions.get(key);if (!decision) {- decision = read().catch(() => false);+ decision = read().catch(swallowAs(`memory disclosure: ${key}`, false));decisions.set(key, decision);}return decision;@@ -51,7 +52,7 @@ function memoryDisclosurePolicy(input: MemoryDisclosure) {: (input.currentScopeMembers?.(input.targetScope).then((members) => members ?? [])- .catch(() => []) ?? Promise.resolve([])));+ .catch(swallowAs("memory disclosure: audience", [])) ?? Promise.resolve([])));const native = (scope: ScopeId) => input.nativeScopes.includes(scope);function entitled(person: Principal, scope: ScopeId): Promise<boolean> {return once(`member:${person.id}:${scope}`, async () => {@@ -93,7 +94,8 @@ function memoryDisclosurePolicy(input: MemoryDisclosure) {async narrow(scope: ScopeId) {try {return await narrow(scope);- } catch {+ } catch (e) {+ swallow("memory disclosure: narrow", e);return false;}},@@ -105,7 +107,8 @@ function memoryDisclosurePolicy(input: MemoryDisclosure) {return (await Promise.all(record.sources.map((source) => sourceAllowed(source.scopeId, record.sensitivity)))).every(Boolean);- } catch {+ } catch (e) {+ swallow("memory disclosure: allows", e);return false;}},diff --git a/src/resolution/scope-membership.ts b/src/resolution/scope-membership.tsindex b48e53992..a4fd0a474 100644--- a/src/resolution/scope-membership.ts+++ b/src/resolution/scope-membership.ts@@ -1,6 +1,7 @@import type { Principal, ScopeId } from "../types.ts";import { parseScopeId } from "../types.ts";import { samePerson } from "../directory/person.ts";+import { swallowAs } from "../util/errors.ts";export interface ManagedGroupDirectory {recognizes(groupId: string): boolean;@@ -44,14 +45,24 @@ async function currentSharedScopeMember(principalId: string,): Promise<boolean> {if (!activePrincipal(deps, principalId)) return false;- const member = await deps.directory?.get?.(principalId).catch(() => null);+ const member = await deps.directory?.get?.(principalId).catch(swallowAs("scope membership: directory lookup", null));const ids = [...new Set([principalId, member?.principalId, member?.slackId].filter((id): id is string => !!id))];if (kind === "group" && deps.managedGroups?.recognizes(ref)) {- for (const id of ids) if ((await deps.managedGroups.membership(ref, id).catch(() => false)) === true) return true;+ for (const id of ids)+ if (+ (await deps.managedGroups.membership(ref, id).catch(swallowAs("scope membership: group membership", false))) ===+ true+ )+ return true;return false;}const direct = kind === "channel" ? deps.directory?.channelMember : deps.directory?.groupMember;- for (const id of ids) if ((await direct?.call(deps.directory, ref, id).catch(() => false)) === true) return true;+ for (const id of ids)+ if (+ (await direct?.call(deps.directory, ref, id).catch(swallowAs("scope membership: channel membership", false))) ===+ true+ )+ return true;return false;}@@ -63,14 +74,27 @@ async function sharedScopeMembership(): Promise<boolean | undefined> {if (!activePrincipal(deps, principalId)) return false;if (kind === "group" && deps.managedGroups?.recognizes(ref)) {- return (await deps.managedGroups.membership(ref, principalId).catch(() => false)) === true;+ return (+ (await deps.managedGroups+ .membership(ref, principalId)+ .catch(swallowAs("scope membership: group membership", false))) === true+ );}const triState = kind === "channel" ? deps.directory?.channelMembership : deps.directory?.groupMembership;- if (triState) return triState.call(deps.directory, ref, principalId).catch(() => undefined);+ if (triState)+ return triState+ .call(deps.directory, ref, principalId)+ .catch(swallowAs("scope membership: channel membership", undefined));const direct = kind === "channel" ? deps.directory?.channelMember : deps.directory?.groupMember;- const member = await direct?.call(deps.directory, ref, principalId).catch(() => false);+ const member = await direct+ ?.call(deps.directory, ref, principalId)+ .catch(swallowAs("scope membership: channel membership", false));if (member === true) return true;- if (kind === "channel" && (await deps.directory?.channelPrivacy?.(ref).catch(() => undefined)) !== undefined)+ if (+ kind === "channel" &&+ (await deps.directory?.channelPrivacy?.(ref).catch(swallowAs("scope membership: channel privacy", undefined))) !==+ undefined+ )return false;return undefined;}@@ -85,7 +109,9 @@ async function memberOfSharedScope(const current = await sharedScopeMembership(deps, kind, ref, principalId);if (current !== undefined) return current;return (- (await deps.sessions?.listByParticipant(principalId).catch(() => []))?.some((s) => s.scopeId === fullScope) === true+ (+ await deps.sessions?.listByParticipant(principalId).catch(swallowAs("scope membership: session lookup", []))+ )?.some((s) => s.scopeId === fullScope) === true);}@@ -172,7 +198,9 @@ export function createCanReadScope(deps: ScopeMembershipDeps): CanReadScope {if (kind === "group") return memberOfSharedScope(deps, kind, ref, principalId, targetScope);if (kind === "channel") {if (await memberOfSharedScope(deps, kind, ref, principalId, targetScope)) return true;- const isPrivate = await deps.directory?.channelPrivacy?.(ref).catch(() => undefined);+ const isPrivate = await deps.directory+ ?.channelPrivacy?.(ref)+ .catch(swallowAs("scope membership: channel privacy", undefined));if (isPrivate === false) return activePrincipal(deps, principalId);return false;}@@ -199,7 +227,11 @@ export function createMembershipControlsScope(deps: ScopeMembershipDeps): Memberreturn async function membershipControlsScope(scope) {const { kind, ref } = parseScopeId(scope);if (kind === "group") return true;- return kind === "channel" && (await deps.directory?.channelPrivacy?.(ref).catch(() => undefined)) === true;+ return (+ kind === "channel" &&+ (await deps.directory?.channelPrivacy?.(ref).catch(swallowAs("scope membership: channel privacy", undefined))) ===+ true+ );};}@@ -210,7 +242,9 @@ export function createCanManageScope(deps: ScopeMembershipDeps): CanManageScopeif (kind === "personal") return samePerson(ref, principalId);if (kind === "group") return currentSharedScopeMember(deps, kind, ref, principalId);if (kind === "channel") {- const isPrivate = await deps.directory?.channelPrivacy?.(ref).catch(() => undefined);+ const isPrivate = await deps.directory+ ?.channelPrivacy?.(ref)+ .catch(swallowAs("scope membership: channel privacy", undefined));if (isPrivate !== true) return false;return currentSharedScopeMember(deps, kind, ref, principalId);}@@ -230,7 +264,12 @@ export function createManagesArtifactHome(const { kind, ref } = parseScopeId(homeScopeId);if (!samePerson(createdBy, principalId)) return false;if (kind === "personal") return true;- if (kind === "channel") return (await deps.directory?.channelPrivacy?.(ref).catch(() => undefined)) === false;+ if (kind === "channel")+ return (+ (await deps.directory+ ?.channelPrivacy?.(ref)+ .catch(swallowAs("scope membership: channel privacy", undefined))) === false+ );return false;};}diff --git a/src/sandbox/agent37-sandbox.ts b/src/sandbox/agent37-sandbox.tsindex a53aebd61..196560627 100644--- a/src/sandbox/agent37-sandbox.ts+++ b/src/sandbox/agent37-sandbox.ts@@ -554,7 +554,7 @@ export function createAgent37Sandbox(workspace: WorkspaceStore, opts: Agent37Sanreturn handle;} catch (err) {- await cleanupFailedProvision(sandbox, handle);+ await cleanupFailedProvision(sandbox, handle, err);throw err;}},diff --git a/src/sandbox/aws-sandbox.ts b/src/sandbox/aws-sandbox.tsindex c67882a39..cb37da0ff 100644--- a/src/sandbox/aws-sandbox.ts+++ b/src/sandbox/aws-sandbox.ts@@ -461,7 +461,7 @@ export function createAwsSandbox(workspace: WorkspaceStore, opts: AwsSandboxOptireturn handle;} catch (error) {- await cleanupFailedProvision(sandbox, handle);+ await cleanupFailedProvision(sandbox, handle, error);throw error;}},diff --git a/src/sandbox/e2b-sandbox.ts b/src/sandbox/e2b-sandbox.tsindex 9b310414b..15f5e0d24 100644--- a/src/sandbox/e2b-sandbox.ts+++ b/src/sandbox/e2b-sandbox.ts@@ -464,7 +464,7 @@ export function createE2bSandbox(workspace: WorkspaceStore, opts: E2bSandboxOptireturn handle;} catch (err) {- await cleanupFailedProvision(sandbox, handle);+ await cleanupFailedProvision(sandbox, handle, err);throw err;}},diff --git a/src/sandbox/exec-sandbox-base.ts b/src/sandbox/exec-sandbox-base.tsindex 99b806b44..6a88f5b07 100644--- a/src/sandbox/exec-sandbox-base.ts+++ b/src/sandbox/exec-sandbox-base.ts@@ -88,6 +88,7 @@ export function createExecSandboxBase(deps: ExecSandboxBaseDeps): ExecSandboxBasawait cleanupFailedProvision({ teardown: () => deps.deleteInstance(name) },{ id: name, rootDir: workspaceDir, scratch: true, backend: label },+ error,);scratchKeyByName.delete(name);throw error;@@ -206,7 +207,7 @@ export function createExecSandboxBase(deps: ExecSandboxBaseDeps): ExecSandboxBasreturn handle;} catch (err) {- await cleanupFailedProvision({ teardown }, handle);+ await cleanupFailedProvision({ teardown }, handle, err);throw err;}}diff --git a/src/sandbox/local-sandbox.ts b/src/sandbox/local-sandbox.tsindex 219b1d036..e1c215034 100644--- a/src/sandbox/local-sandbox.ts+++ b/src/sandbox/local-sandbox.ts@@ -433,7 +433,7 @@ export function createLocalSandbox(workspace: WorkspaceStore, opts: LocalSandboxreturn handle;} catch (err) {- await cleanupFailedProvision(sandbox, handle);+ await cleanupFailedProvision(sandbox, handle, err);throw err;}},diff --git a/src/sandbox/modal-sandbox.ts b/src/sandbox/modal-sandbox.tsindex 66c08abfc..ca6d29358 100644--- a/src/sandbox/modal-sandbox.ts+++ b/src/sandbox/modal-sandbox.ts@@ -744,7 +744,7 @@ export function createModalSandbox(workspace: WorkspaceStore, opts: ModalSandboxreturn handle;} catch (err) {- await cleanupFailedProvision(sandbox, handle);+ await cleanupFailedProvision(sandbox, handle, err);throw err;}},diff --git a/src/sandbox/porter-sandbox.ts b/src/sandbox/porter-sandbox.tsindex 78cf4e721..ff7b0ed21 100644--- a/src/sandbox/porter-sandbox.ts+++ b/src/sandbox/porter-sandbox.ts@@ -334,7 +334,7 @@ export function createPorterSandbox(workspace: WorkspaceStore, opts: PorterSandbreturn handle;} catch (err) {- await cleanupFailedProvision(sandbox, handle);+ await cleanupFailedProvision(sandbox, handle, err);throw err;}},diff --git a/src/sandbox/sandbox.ts b/src/sandbox/sandbox.tsindex 86ab65136..21527b07d 100644--- a/src/sandbox/sandbox.ts+++ b/src/sandbox/sandbox.ts@@ -1,4 +1,4 @@-import { swallow } from "../util/errors.ts";+import { errMessage, swallow } from "../util/errors.ts";import type { EgressPolicy, WorkspaceLayer } from "../types.ts";export interface SandboxHandle {@@ -14,27 +14,31 @@ export interface SandboxHandle {scopeId?: string;}-export class SandboxProvisionCleanupError extends Error {+export class SandboxProvisionCleanupError extends AggregateError {readonly handle: SandboxHandle;- constructor(handle: SandboxHandle) {- super("Disposable sandbox initialization cleanup failed");+ constructor(handle: SandboxHandle, cleanupError: unknown, provisionError: unknown) {+ super(+ [provisionError, cleanupError],+ `Disposable sandbox cleanup failed after initialization failed (${errMessage(provisionError)})`,+ {+ cause: cleanupError,+ },+ );this.name = "SandboxProvisionCleanupError";- this.handle = {- id: handle.id,- rootDir: handle.rootDir,- scratch: true,- ...(handle.backend ? { backend: handle.backend } : {}),- ...(handle.providerSandboxId ? { providerSandboxId: handle.providerSandboxId } : {}),- };+ this.handle = { ...handle, scratch: true };}}-export async function cleanupFailedProvision(sandbox: Pick<Sandbox, "teardown">, handle: SandboxHandle): Promise<void> {+export async function cleanupFailedProvision(+ sandbox: Pick<Sandbox, "teardown">,+ handle: SandboxHandle,+ provisionError: unknown,+): Promise<void> {try {await sandbox.teardown(handle, handle.scratch ? { destroy: true } : undefined);} catch (error) {- if (handle.scratch) throw new SandboxProvisionCleanupError(handle);+ if (handle.scratch) throw new SandboxProvisionCleanupError(handle, error, provisionError);swallow("sandbox: teardown after failed provision", error);}}diff --git a/src/sandbox/superserve-sandbox.ts b/src/sandbox/superserve-sandbox.tsindex 1011de337..61ce73036 100644--- a/src/sandbox/superserve-sandbox.ts+++ b/src/sandbox/superserve-sandbox.ts@@ -623,7 +623,7 @@ export function createSuperserveSandbox(workspace: WorkspaceStore, opts: Superse? provisionQueue(`scratch:${scratch.key}`, provisionAndPrepare): provisionQueue(scope, () => advisoryLock.withLock(lockKey(scope), provisionAndPrepare)));} catch (err) {- if (pendingHandle) await cleanupFailedProvision(sandbox, pendingHandle);+ if (pendingHandle) await cleanupFailedProvision(sandbox, pendingHandle, err);throw err;}});diff --git a/src/security/secret-masking.ts b/src/security/secret-masking.tsindex b32f5e528..be73b7f75 100644--- a/src/security/secret-masking.ts+++ b/src/security/secret-masking.ts@@ -33,7 +33,16 @@ export function createSecretValueMasker(env: Record<string, string> | undefined)};}-export class MaskedExecutionError extends Error {}+export class MaskedExecutionError extends Error {+ readonly code: unknown;++ constructor(original: unknown, mask: (text: string) => string, message: string) {+ super(message);+ this.name = original instanceof Error ? original.name : "Error";+ this.code = (original as { code?: unknown } | null)?.code;+ if (original instanceof Error && original.stack) this.stack = mask(original.stack);+ }+}export function createExactSecretValueMasker(values: Iterable<string>): (text: string) => string {const secrets = [...new Set(values)].filter(Boolean).sort((a, b) => b.length - a.length);diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex 35034e637..467504556 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -860,7 +860,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {} catch (error) {const message = errMessage(error);const masked = mask(message);- if (masked !== message) throw new MaskedExecutionError(masked);+ if (masked !== message) throw new MaskedExecutionError(error, mask, masked);throw error;}return reached ? { ...r, reached } : r;diff --git a/src/util/errors.ts b/src/util/errors.tsindex 4e48f046e..d9588c74a 100644--- a/src/util/errors.ts+++ b/src/util/errors.ts@@ -1,51 +1,11 @@import { reportBackendError } from "../../plugins/chassis/src/error-reporting.ts";+import { errChain as errMessage, errDetail, failureCode } from "../../plugins/chassis/src/errors.ts";import { WorkAdmissionClosed } from "./admitted-work.ts";-const CAUSE_DEPTH = 5;--function errorText(value: unknown): string {- if (typeof value === "string") return value;- if (value === null || (typeof value !== "object" && typeof value !== "function")) return String(value);- if ("message" in value && typeof value.message === "string") return value.message;- return "Unknown error";-}--function describeCause(cause: unknown): string {- if (!(cause instanceof Error)) return errorText(cause);- const code = (cause as { code?: unknown }).code;- const label = code !== undefined && code !== null && code !== "" ? `${cause.name} ${errorText(code)}` : cause.name;- return cause.message ? `${label}: ${cause.message}` : label;-}--export function errMessage(e: unknown): string {- if (!(e instanceof Error)) return errorText(e);- const parts = [e.message];- const seen = new Set<unknown>([e]);- const messages = new Set([e.message]);- let cause: unknown = e.cause;- while (cause !== undefined && cause !== null && !seen.has(cause) && parts.length <= CAUSE_DEPTH) {- seen.add(cause);- const causeMessage = cause instanceof Error ? cause.message : errorText(cause);- if (!messages.has(causeMessage)) parts.push(describeCause(cause));- messages.add(causeMessage);- cause = cause instanceof Error ? cause.cause : undefined;- }- return parts.join(" <- ");-}+export { errChain as errMessage, failureCode, swallow, swallowAs } from "../../plugins/chassis/src/errors.ts";export function asError(e: unknown): Error {- return e instanceof Error ? e : new Error(errorText(e));-}--export function swallow(context: string, e: unknown): void {- console.warn(`[swallowed] ${context}: ${errMessage(e)}`);-}--export function swallowAs<T>(context: string, fallback: T): (e: unknown) => T {- return (e) => {- swallow(context, e);- return fallback;- };+ return e instanceof Error ? e : new Error(errMessage(e), { cause: e });}const reportedErrors = new WeakSet<object>();@@ -62,20 +22,15 @@ function isExpectedInterruption(e: unknown): boolean {return (e instanceof Error && e.name === "AbortError") || e instanceof WorkAdmissionClosed;}-export function failureCode(context: string): string {- return context- .toLowerCase()- .replace(/\s*:\s*/g, ":")- .replace(/[^a-z0-9_.:-]+/g, "_")- .replace(/^_+|_+$/g, "")- .slice(0, 120);-}-export function reportFailure(context: string, e: unknown, detail?: string): void {- console.error(`[failed] ${context}${detail ? ` (${detail})` : ""}: ${errMessage(e)}`);- if (isExpectedInterruption(e) || errorAlreadyReported(e)) return;- markErrorReported(e);- reportBackendError(asError(e), failureCode(context));+ const reportable = !isExpectedInterruption(e) && !errorAlreadyReported(e);+ if (reportable) markErrorReported(e);+ const eventId = reportable+ ? reportBackendError(asError(e), failureCode(context), detail ? { detail } : undefined)+ : undefined;+ console.error(+ `[failed] ${context}${detail ? ` (${detail})` : ""}${eventId ? ` [sentry=${eventId}]` : ""}: ${errDetail(e)}`,+ );}export function reportFailureAs<T>(context: string, fallback: T, detail?: string): (e: unknown) => T {diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.tsindex 870938181..6a53561b5 100644--- a/test/agent-tools.test.ts+++ b/test/agent-tools.test.ts@@ -3959,7 +3959,7 @@ test("command exit codes are data; timeouts and thrown tool errors are failures"await assert.rejects(run, /sandbox provider unavailable/);const result = entries.find((e) => e.type === "tool_result")!.payload;assert.equal(result.isError, true);- assert.equal(result.result, "Command execution failed.");+ assert.equal(result.result, "Command execution failed: sandbox provider unavailable");assert.equal(result.code, undefined);continue;}diff --git a/test/aws-role-cutover.test.ts b/test/aws-role-cutover.test.tsindex 64ca0ac44..195664ae7 100644--- a/test/aws-role-cutover.test.ts+++ b/test/aws-role-cutover.test.ts@@ -352,8 +352,11 @@ test("shared ACMECLI cutover isolates brokered STS without shrinking the existin}),(error: Error) => {assert.equal(error.message, "Disposable sandbox destruction failed");- assert.equal(error.cause, undefined);- assert.ok(!error.stack?.includes("persistent control-plane deletion failure"));+ assert.ok(error instanceof AggregateError);+ assert.deepEqual(+ error.errors.map((attempt: Error) => attempt.message),+ Array(3).fill("persistent control-plane deletion failure"),+ );return true;},);diff --git a/test/e2b-sandbox.test.ts b/test/e2b-sandbox.test.tsindex c3f6e4d50..af4cb262d 100644--- a/test/e2b-sandbox.test.ts+++ b/test/e2b-sandbox.test.ts@@ -723,7 +723,7 @@ test("failed scratch preparation retains the live session when rollback fails",throw new Error("preparation failed");},async kill() {- if (kills++ === 0) throw new Error("sentinel-secret");+ if (kills++ === 0) throw new Error("kill-boom");await session.kill();},};@@ -734,8 +734,8 @@ test("failed scratch preparation retains the live session when rollback fails",await assert.rejects(box.provision(layers, { scratch: { key: "failed-preparation" } }), (error: Error) => {assert.ok(error instanceof SandboxProvisionCleanupError);pending = error.handle;- assert.equal(error.cause, undefined);- assert.ok(!error.message.includes("sentinel-secret"));+ assert.equal((error.cause as Error).message, "kill-boom");+ assert.match(error.message, /preparation failed/);return true;});assert.ok(pending);diff --git a/test/error-reporting.test.ts b/test/error-reporting.test.tsindex ceedf4ef1..04eb67c88 100644--- a/test/error-reporting.test.ts+++ b/test/error-reporting.test.ts@@ -3,54 +3,7 @@ import { test } from "node:test";import { spawn } from "node:child_process";import { createServer } from "node:http";import { once } from "node:events";-import { sanitizeErrorEvent } from "../plugins/chassis/src/error-reporting.ts";-import { sanitizeTransactionEvent, traceStatus } from "../plugins/chassis/src/timing.ts";--test("error event allowlist excludes content, credentials, paths and ambient scope", () => {- const clean = sanitizeErrorEvent({- type: undefined,- message: "private-prompt",- logentry: { message: "private-prompt" },- user: { email: "private-email" },- request: { data: "private-body", headers: { authorization: "private-token" } },- breadcrumbs: [{ message: "private-breadcrumb" }],- extra: { payload: "private-payload" },- contexts: { private: { value: "private-context" } },- server_name: "private-host",- transaction: "private-url",- tags: { service: "core", deployment: "test", private: "private-tag", error_code: "run:failed" },- exception: {- values: [- {- type: "TypeError",- value: "private-message",- stacktrace: {- frames: [- {- filename: "/private-user/src/server.ts?private-query",- function: "serve",- lineno: 42,- vars: { token: "private-local" },- context_line: "private-source",- pre_context: ["private-before"],- },- ],- },- },- ],- },- });- assert.doesNotMatch(JSON.stringify(clean), /private/);- assert.equal(clean.exception?.values?.[0]?.type, "TypeError");- assert.deepEqual(clean.exception?.values?.[0]?.stacktrace?.frames?.[0], {- filename: "server.ts",- function: "serve",- lineno: 42,- colno: undefined,- in_app: undefined,- });- assert.deepEqual(clean.fingerprint, ["{{ default }}", "run:failed"]);-});+import { traceStatus } from "../plugins/chassis/src/timing.ts";async function runReporting(body: string, enabled = true, env: Record<string, string> = {}) {const events: Record<string, any>[] = [];@@ -115,21 +68,33 @@ async function runReporting(body: string, enabled = true, env: Record<string, st}}-test("real SDK sends one redacted exception when captured and logged, plus a classified record", async () => {- const { events, code } = await runReporting(`- const error = new TypeError('private-message');+test("real SDK sends full exception details, causes and classification", async () => {+ const { events, code, output } = await runReporting(`+ const error = Object.assign(new TypeError('top-message', { cause: new Error('root-cause') }), { stderr: 'command failed', exitCode: 17, body: { upstream: { reason: 'failure' } } });+ const { errDetail } = await import('./plugins/chassis/src/errors.ts');+ console.log(errDetail(error));reportBackendError(error);- console.error('private-request-url', error);- reportBackendError(new Error('private-record'), 'run:failed');+ console.error('request-url', error);+ reportBackendError(new Error('record-message'), 'run:failed', { detail: 'extra-detail' });await flushErrorReporting();`);assert.equal(code, 0);assert.equal(events.length, 2);- assert.doesNotMatch(JSON.stringify(events), /private-/);- assert.ok(events[0]!.exception.values[0].stacktrace.frames.length);+ assert.equal(events[0]!.contexts.TypeError.stderr, "command failed");+ assert.equal(events[0]!.contexts.TypeError.exitCode, 17);+ assert.deepEqual(events[0]!.contexts.TypeError.body, { upstream: { reason: "failure" } });+ assert.ok(output.includes("stderr=command failed"));+ assert.ok(output.includes("exitCode=17"));+ const values = events[0]!.exception.values.map((value: { value: string }) => value.value);+ assert.ok(values.includes("top-message"));+ assert.ok(values.includes("root-cause"));+ assert.ok(events[0]!.exception.values.at(-1).stacktrace.frames.length);assert.equal(events[0]!.tags.deployment, "test-deployment");assert.equal(events[0]!.release, "test-release");assert.equal(events[1]!.tags.error_code, "run:failed");+ assert.deepEqual(events[1]!.fingerprint, ["{{ default }}", "run:failed"]);+ assert.equal(events[1]!.extra.detail, "extra-detail");+ assert.equal(events[1]!.exception.values[0].value, "record-message");});test("disabled reporting leaves process listeners and logging alone", async () => {@@ -167,7 +132,7 @@ test("fatal reporting preserves the core drain handler and avoids duplicate consassert.equal(events.length, 1);});-test("operator error records retain local details and send one classified event after safe logging", async () => {+test("operator error records send one classified event with the record details", async () => {const { events, code, output } = await runReporting(`const { createErrorLog, withErrorReporting } = await import('./src/admin/error-log.ts');const errors = withErrorReporting(createErrorLog());@@ -181,106 +146,8 @@ test("operator error records retain local details and send one classified eventassert.equal(output.trim(), "private-job-failure");assert.equal(events.length, 1);assert.equal(events[0]!.tags.error_code, "turn:failed");- assert.doesNotMatch(JSON.stringify(events), /private-/);-});--test("transaction allowlist keeps timing shape only and rejects unsafe names", () => {- const clean = sanitizeTransactionEvent(- {- type: "transaction",- event_id: "b".repeat(32),- transaction: "GET /v1/sessions/:id",- transaction_info: { source: "url" },- start_timestamp: 10,- timestamp: 10.5,- environment: "verification",- release: "test-release",- user: { id: "private-user" },- request: { url: "https://private-host/v1/sessions/private-id", headers: { authorization: "private-token" } },- breadcrumbs: [{ message: "private-breadcrumb" }],- extra: { sql: "private-sql" },- server_name: "private-host",- spans: [- { span_id: "1", trace_id: "2", description: "SELECT private", start_timestamp: 10, timestamp: 10.1, data: {} },- ],- tags: { service: "core", http_status: "private", private: "private-tag", surface: "private-tag" },- measurements: { queue_wait: { value: 5, unit: "millisecond" }, private: { value: 1, unit: "millisecond" } },- contexts: {- trace: {- trace_id: "a".repeat(32),- span_id: "c".repeat(16),- op: "http.server",- status: "ok",- data: { private: 1, http_status: "200", surface: "web", page: "private id", "sentry.sample_rate": 1 },- },- otel: { resource: { "service.name": "private-host" } },- runtime: { name: "node" },- private: { value: "private-context" },- },- },- "node",- );- assert.doesNotMatch(JSON.stringify(clean), /private/);- assert.equal(clean?.transaction, "GET /v1/sessions/:id");- assert.deepEqual(clean?.transaction_info, { source: "route" });- assert.deepEqual(clean?.tags, { service: "core", http_status: "200", surface: "web", page: "other" });- assert.deepEqual(clean?.measurements, { queue_wait: { value: 5, unit: "millisecond" } });- assert.deepEqual(clean?.spans, []);- assert.deepEqual(clean?.contexts?.trace, {- trace_id: "a".repeat(32),- span_id: "c".repeat(16),- op: "http.server",- status: "ok",- origin: "manual",- });- const base = {- type: "transaction" as const,- start_timestamp: 1,- timestamp: 2,- contexts: { trace: { trace_id: "a".repeat(32), span_id: "c".repeat(16), op: "queue.task", status: "ok" } },- };- for (const transaction of ["GET /v1/sessions/1234?token=private", "private text", "GET https://x/", undefined])- assert.equal(sanitizeTransactionEvent({ ...base, transaction }, "node"), null);- assert.equal(sanitizeTransactionEvent({ ...base, transaction: "run", timestamp: 0 }, "node"), null);- assert.equal(sanitizeTransactionEvent({ ...base, transaction: "run", contexts: {} }, "node"), null);- const traced = (op: string, status: string) => ({- ...base,- transaction: "run",- contexts: { trace: { ...base.contexts.trace, op, status } },- });- assert.equal(sanitizeTransactionEvent(traced("private.op", "ok"), "node"), null);- assert.equal(sanitizeTransactionEvent(traced("queue.task", "private status"), "node"), null);- assert.equal(sanitizeTransactionEvent(traced("queue.task", "ok"), "node")?.contexts?.trace?.op, "queue.task");- const bucketed = sanitizeTransactionEvent(- {- ...traced("queue.task", "ok"),- contexts: {- trace: {- ...base.contexts.trace,- op: "queue.task",- status: "ok",- data: { surface: "private-surface", origin: "private-origin", http_status: "private", page: "private" },- },- },- },- "node",- );- assert.deepEqual(bucketed?.tags, { surface: "other", origin: "other", http_status: "other", page: "other" });- const inherited = sanitizeTransactionEvent(- {- ...traced("queue.task", "ok"),- contexts: {- trace: {- ...base.contexts.trace,- op: "queue.task",- status: "ok",- data: { toString: "private prompt", constructor: "private-user", hasOwnProperty: "private" },- },- },- },- "node",- );- assert.deepEqual(inherited?.tags, {});+ assert.equal(events[0]!.exception.values[0].value, "private-job-failure");+ assert.equal(events[0]!.extra.scopeLabel, "private-scope");});test("trace statuses map HTTP outcomes", () => {@@ -296,7 +163,7 @@ test("trace statuses map HTTP outcomes", () => {]);});-test("real SDK sends sanitized sampled transactions only when a sample rate is configured", async () => {+test("real SDK preserves sampled transaction data only when a sample rate is configured", async () => {const body = `startTiming('queue.task', 'run', Date.now() - 500)?.({ status: 'ok', endMs: Date.now(),data: { surface: 'web', origin: 'human', private: 'private-tag', page: 'private-page' },@@ -317,44 +184,31 @@ test("real SDK sends sanitized sampled transactions only when a sample rate is cassert.equal(on.code, 0);assert.equal(on.events.length, 1);assert.equal(on.transactions.length, 2);- assert.doesNotMatch(JSON.stringify(on.transactions), /private/);+ assert.match(JSON.stringify(on.transactions), /private-tag/);const [run, request] = on.transactions;assert.equal(run!.transaction, "run");assert.ok(Math.abs(run!.timestamp - run!.start_timestamp - 0.5) < 0.05);assert.deepEqual(run!.tags, {service: "test",deployment: "test-deployment",- surface: "web",- origin: "human",- page: "other",});- assert.deepEqual(run!.measurements, { queue_wait: { value: 20, unit: "millisecond" } });+ assert.deepEqual(run!.measurements, {+ queue_wait: { value: 20, unit: "millisecond" },+ private: { value: 5, unit: "millisecond" },+ });+ assert.equal(run!.contexts.trace.data.private, "private-tag");+ assert.equal(run!.contexts.trace.data.page, "private-page");assert.equal(run!.contexts.trace.op, "queue.task");assert.equal(run!.release, "test-release");assert.equal(run!.environment, "verification");assert.equal(request!.transaction, "GET /v1/sessions/:id");assert.equal(request!.contexts.trace.status, "not_found");- assert.equal(request!.tags.http_status, "404");- assert.deepEqual(Object.keys(run!).sort(), [- "contexts",- "environment",- "event_id",- "measurements",- "platform",- "release",- "sdk",- "spans",- "start_timestamp",- "tags",- "timestamp",- "transaction",- "transaction_info",- "type",- ]);+ assert.equal(request!.contexts.trace.data.http_status, "404");});test("reportFailure sends one classified event per distinct failure and skips cancellations and recorded errors", async () => {- const { events, code } = await runReporting(`+ const { events, code, output } = await runReporting(`+ console.error = (line) => console.log(line);const { reportFailure } = await import('./src/util/errors.ts');const { createErrorLog, withErrorReporting } = await import('./src/admin/error-log.ts');const errors = withErrorReporting(createErrorLog());@@ -376,6 +230,23 @@ test("reportFailure sends one classified event per distinct failure and skips caevents.map((event) => event.tags.error_code),["turn:error", "scheduler:tick", "audit:persist_event", "tools:persist_artifact"],);- assert.doesNotMatch(JSON.stringify(events), /private-/);- assert.equal(events[1]!.exception.values[0].value, "scheduler:tick");+ assert.equal(events[1]!.exception.values[0].value, "private-db-down");+ const tick = output.split("\n").find((line) => line.startsWith("[failed] scheduler: tick"));+ assert.match(tick ?? "", new RegExp(`\\[sentry=${events[1]!.event_id}\\]: private-db-down \\{stack: `));+});++test("sandbox cleanup errors send both original failures and their stacks", async () => {+ const { events, code } = await runReporting(`+ const { SandboxProvisionCleanupError } = await import('./src/sandbox/sandbox.ts');+ const provision = new Error('provision failed', { cause: new Error('provision root') });+ const cleanup = new Error('cleanup failed');+ reportBackendError(new SandboxProvisionCleanupError({ id: 'test', rootDir: '/tmp' }, cleanup, provision));+ await flushErrorReporting();+ `);+ assert.equal(code, 0);+ const values = events[0]!.exception.values;+ for (const message of ["provision failed", "provision root", "cleanup failed"]) {+ const value = values.find((entry: { value: string }) => entry.value === message);+ assert.ok(value?.stacktrace.frames.length, message);+ }});diff --git a/test/errors.test.ts b/test/errors.test.tsindex 0e308321b..a9b401fe0 100644--- a/test/errors.test.ts+++ b/test/errors.test.ts@@ -6,11 +6,13 @@ import {errorAlreadyReported,failureCode,reportFailure,+ swallow,+ swallowAs,httpFailure,withRequestId,} from "../src/util/errors.ts";import { WorkAdmissionClosed } from "../src/util/admitted-work.ts";-import { errMessage as pluginErrMessage } from "../plugins/chassis/src/errors.ts";+import { errDetail, errMessage as pluginErrMessage } from "../plugins/chassis/src/errors.ts";import { runInNewContext } from "node:vm";test("errMessage keeps the cause chain that fetch failures hide behind their generic message", () => {@@ -114,12 +116,38 @@ test("reportFailure logs every failure but marks only reportable ones as reportereportFailure("scheduler: fire", boom);assert.equal(errorAlreadyReported(boom), true);reportFailure("worker: retry", "a string throw", "run=r1");- assert.deepEqual(logged, [- "[failed] scheduler: fire: stopped",- "[failed] scheduler: tick: This deployment is not accepting synchronous work",- "[failed] scheduler: fire: boom",- "[failed] worker: retry (run=r1): a string throw",- ]);+ assert.deepEqual(+ logged.map((line) => line.replace(/ \{stack: .*\}$/, "")),+ [+ "[failed] scheduler: fire: stopped",+ "[failed] scheduler: tick: This deployment is not accepting synchronous work",+ "[failed] scheduler: fire: boom",+ "[failed] worker: retry (run=r1): a string throw",+ ],+ );+ assert.match(logged[2]!, /\{stack: at .*errors\.test\.ts/);+});++test("swallow logs the cause chain, structured error fields and stack instead of only the message", (t) => {+ const logged: string[] = [];+ t.mock.method(console, "warn", (...args: unknown[]) => {+ logged.push(args.map(String).join(" "));+ });+ const slack = Object.assign(+ new Error("An API error occurred: not_in_channel", { cause: new Error("socket hang up") }),+ {+ code: "slack_webapi_platform_error",+ data: { error: "not_in_channel" },+ },+ );+ swallow("slack: post", slack);+ swallow("http", Object.assign(new Error("upstream failed"), { statusCode: 503 }));+ assert.ok(logged[0]!.includes("code=slack_webapi_platform_error"));+ assert.ok(logged[0]!.includes('data={"error":"not_in_channel"}'));+ assert.ok(logged[0]!.includes("{stack: at "));+ assert.ok(logged[1]!.includes("[statusCode=503]"));+ assert.equal(swallowAs("lookup", false)(new Error("db down")), false);+ assert.match(logged[2]!, /^\[swallowed\] lookup: db down \{stack: /);});test("httpFailure names the status, a clipped body, and the provider request id", async () => {@@ -133,3 +161,48 @@ test("httpFailure names the status, a clipped body, and the provider request id");assert.equal(withRequestId("fine", new Headers()), "fine");});++test("errDetail preserves browser frames, nested stacks and aggregate errors without cycles", () => {+ const provision = new Error("provision");+ provision.stack = "Error: provision\ninitialize@https://example.com/app.js:1:2";+ const cleanup = new Error("cleanup", { cause: provision });+ const error = new AggregateError([provision, cleanup], "both", { cause: cleanup });+ provision.cause = error;+ const detail = errDetail(error);+ assert.ok(detail.includes("initialize@https://example.com/app.js:1:2"));+ assert.ok(detail.includes("cleanup"));+ assert.equal(detail.split("initialize@").length, 2);+});++test("error fields tolerate circular data, bigint, failing serializers and malformed aggregate errors", () => {+ const body: Record<string, unknown> = { count: 1n };+ body.self = body;+ const error = Object.assign(new AggregateError([], "failure"), {+ stderr: "failed",+ body,+ broken: {+ toJSON() {+ throw new Error("serializer failed");+ },+ },+ });+ Reflect.set(error, "errors", null);+ const detail = errDetail(error);+ assert.ok(detail.includes("stderr=failed"));+ assert.ok(detail.includes('"count":"1"'));+ assert.ok(detail.includes("[Circular]"));+ assert.ok(detail.includes("broken=[Unserializable]"));+ assert.equal(asError(body).cause, body);+});++test("field enumeration failures preserve the message and stack", () => {+ const error = Object.assign(new Error("failure"), { cause: new Error("root") });+ assert.ok(!errDetail(error).includes("cause="));+ Object.defineProperty(error, "stack", { value: "Error: failure\n at test.ts:1:1" });+ const hostile = new Proxy(error, {+ ownKeys() {+ throw new Error("enumeration failed");+ },+ });+ assert.equal(errDetail(hostile), errDetail(error));+});diff --git a/test/execute-scratch.test.ts b/test/execute-scratch.test.tsindex 7d81f11f1..388d6b88a 100644--- a/test/execute-scratch.test.ts+++ b/test/execute-scratch.test.ts@@ -583,7 +583,7 @@ test("reclaim waits for in-flight scratch creation before destroying its handle"assert.equal(boxes.scratchBox.handle, null);});-test("scratch destruction failures remain visible and retain the handle for retry", async () => {+test("scratch destruction failures keep their cause and retain the handle for retry", async () => {let attempts = 0;let fail = true;const { boxes, events, errors } = turnBoxes({@@ -592,37 +592,43 @@ test("scratch destruction failures remain visible and retain the handle for retr},async teardown() {attempts++;- if (fail) throw new Error("sentinel-secret");+ if (fail) throw new Error(`teardown-boom-${attempts}`);},});await boxes.provisionScratch();await assert.rejects(boxes.reclaimBox(), (error: Error) => {assert.equal(error.message, "Disposable sandbox destruction failed");- assert.equal(error.cause, undefined);- assert.ok(!error.stack?.includes("sentinel-secret"));+ assert.ok(error instanceof AggregateError);+ assert.deepEqual(+ error.errors.map((attempt: Error) => attempt.message),+ ["teardown-boom-1", "teardown-boom-2", "teardown-boom-3"],+ );return true;});assert.equal(attempts, 3);assert.equal(boxes.scratchBox.handle, scratchHandle);assert.equal(events.filter((event) => event.action === "sandbox.scratch.release_failed").length, 1);assert.equal(events.filter((event) => event.action === "sandbox.scratch.released").length, 0);- assert.ok(!JSON.stringify({ events, errors }).includes("sentinel-secret"));+ assert.equal(+ JSON.parse(events.find((event) => event.action === "sandbox.scratch.release_failed")!.detail!).error,+ "Disposable sandbox destruction failed <- Error: teardown-boom-1 <- Error: teardown-boom-2 <- Error: teardown-boom-3",+ );assert.equal(errors.length, 1);fail = false;await boxes.reclaimBox();assert.equal(boxes.scratchBox.handle, null);});-test("failed scratch provisioning is audited safely and can retry", async () => {+test("failed scratch provisioning is audited with its error and can retry", async () => {let attempts = 0;const { boxes, events } = turnBoxes({async provision() {- if (attempts++ === 0) throw new Error("sentinel-secret");+ if (attempts++ === 0) throw new Error("provision-boom");return scratchHandle;},async teardown() {},});- await assert.rejects(boxes.provisionScratch(), /sentinel-secret/);+ await assert.rejects(boxes.provisionScratch(), /provision-boom/);await boxes.provisionScratch();await boxes.reclaimBox();assert.deepEqual(@@ -635,31 +641,31 @@ test("failed scratch provisioning is audited safely and can retry", async () =>"sandbox.scratch.released",],);- assert.ok(!JSON.stringify(events).includes("sentinel-secret"));+ assert.equal(JSON.parse(events[1]!.detail!).error, "provision-boom");});for (const recovers of [true, false]) {- test(`failed scratch initialization preserves safe cleanup identity; recovery=${recovers}`, async () => {+ test(`failed scratch initialization keeps both errors and the cleanup identity; recovery=${recovers}`, async () => {let destroys = 0;- const partial = { ...scratchHandle, backend: "local", env: { TOKEN: "sentinel-secret" } };+ const partial = { ...scratchHandle, backend: "local", env: { TOKEN: "token" } };const sandbox: Partial<Sandbox> = {async provision() {- await cleanupFailedProvision({ teardown: sandbox.teardown! }, partial);- throw new Error("initialization failed");+ const failure = new Error("initialization failed");+ await cleanupFailedProvision({ teardown: sandbox.teardown! }, partial, failure);+ throw failure;},async teardown(handle, opts) {assert.equal(handle.id, partial.id);assert.equal(opts?.destroy, true);- if (destroys++ === 0 || !recovers) throw new Error("sentinel-secret");+ if (destroys++ === 0 || !recovers) throw new Error("teardown-boom");},};- const { boxes, events, errors } = turnBoxes(sandbox);+ const { boxes, events } = turnBoxes(sandbox);await assert.rejects(boxes.provisionScratch(), (error: Error) => {assert.ok(error instanceof SandboxProvisionCleanupError);assert.equal(error.handle.id, partial.id);- assert.equal(error.handle.env, undefined);- assert.equal(error.cause, undefined);- assert.ok(!JSON.stringify(error).includes("sentinel-secret"));+ assert.match(error.message, /initialization failed/);+ assert.equal((error.cause as Error).message, "teardown-boom");return true;});await assert.rejects(boxes.provisionScratch(), /cleanup is still pending/);@@ -671,7 +677,6 @@ for (const recovers of [true, false]) {assert.equal(JSON.parse(failure.detail!).sandboxId, partial.id);assert.equal(JSON.parse(failure.detail!).backend, "local");assert.equal(events.at(-1)?.action, `sandbox.scratch.${recovers ? "released" : "release_failed"}`);- assert.ok(!JSON.stringify({ events, errors }).includes("sentinel-secret"));assert.equal(boxes.scratchBox.pending === null, recovers);});}diff --git a/test/request-timing.test.ts b/test/request-timing.test.tsindex 2d97b0340..390f59f62 100644--- a/test/request-timing.test.ts+++ b/test/request-timing.test.ts@@ -35,7 +35,7 @@ after(async () => {await new Promise<void>((resolve) => collector.close(() => resolve()));});-test("core request timings carry registered route templates, never raw paths, and runs report queue wait", async () => {+test("core request timings keep raw URLs alongside route templates and runs report queue wait", async () => {const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "timing-")) }));const server = createInsecureTestServer(built.app);server.listen(0);@@ -54,9 +54,20 @@ test("core request timings carry registered route templates, never raw paths, anawait settle(3);const requests = captured.filter((event) => event.contexts?.trace?.op === "http.server");assert.equal(requests.length, 3);- assert.doesNotMatch(JSON.stringify(requests), /private/);assert.deepEqual(- requests.map((event) => [event.transaction, event.contexts?.trace?.status, event.tags?.http_status]),+ requests.map((event) => event.contexts.trace.data.url),+ [+ "/v1/sessions/private-session-id?token=private-token",+ "/v1/no-such-route/private-segment-9f3a/deep",+ "/v1/blobs/private-blob-id",+ ],+ );+ assert.deepEqual(+ requests.map((event) => [+ event.transaction,+ event.contexts?.trace?.status,+ event.contexts?.trace?.data?.http_status,+ ]),[["GET /v1/sessions/:id", "invalid_argument", "400"],["POST /*", "not_found", "404"],@@ -68,9 +79,6 @@ test("core request timings carry registered route templates, never raw paths, anassert.equal(event.tags?.service, "core");assert.ok(event.timestamp! >= event.start_timestamp!);assert.match(event.contexts!.trace!.trace_id!, /^[a-f0-9]{32}$/);- assert.equal(event.server_name, undefined);- assert.equal(event.contexts.otel, undefined);- assert.equal(event.contexts.trace.data, undefined);assert.deepEqual(event.spans, []);}const { run } = await built.runs.enqueue({@@ -89,9 +97,10 @@ test("core request timings carry registered route templates, never raw paths, anawait settle(4);const runs = captured.filter((event) => event.contexts?.trace?.op === "queue.task");assert.equal(runs.length, 1);- assert.doesNotMatch(JSON.stringify(runs), /private/);assert.equal(runs[0]!.transaction, "run");- assert.deepEqual(runs[0]!.tags, { service: "core", surface: "web", origin: "human" });+ assert.deepEqual(runs[0]!.tags, { service: "core" });+ assert.equal(runs[0]!.contexts.trace.data.surface, "web");+ assert.equal(runs[0]!.contexts.trace.data.origin, "human");assert.equal(runs[0]!.contexts?.trace?.status, "ok");assert.equal(runs[0]!.measurements?.queue_wait?.unit, "millisecond");assert.ok(runs[0]!.measurements!.queue_wait!.value >= 0);diff --git a/test/sandbox-routing.test.ts b/test/sandbox-routing.test.tsindex c8f9be443..f7138c01a 100644--- a/test/sandbox-routing.test.ts+++ b/test/sandbox-routing.test.ts@@ -212,7 +212,11 @@ test("scratch with no selected computer uses the installation provider without ctest("failed scratch initialization keeps its selected backend for cleanup", async () => {const { router, sprites } = build({ "personal:p": resource("p", "sprites") });sprites.provision = async () => {- throw new SandboxProvisionCleanupError({ id: "partial", rootDir: "/workspace", scratch: true });+ throw new SandboxProvisionCleanupError(+ { id: "partial", rootDir: "/workspace", scratch: true },+ new Error("cleanup"),+ new Error("provision"),+ );};let pending: SandboxHandle | undefined;await assert.rejects(router.provision([], { scratch: { key: "turn" }, routeScopeId: "personal:p" }), (e: Error) => {diff --git a/test/secret-masking.test.ts b/test/secret-masking.test.tsindex ce3c95cd3..39e930e57 100644--- a/test/secret-masking.test.ts+++ b/test/secret-masking.test.ts@@ -3,6 +3,7 @@ import assert from "node:assert/strict";import {createSecretValueMasker,createExactSecretValueMasker,+ MaskedExecutionError,executionSecretEnv,} from "../src/security/secret-masking.ts";@@ -99,3 +100,14 @@ test("conflicting public metadata cannot exempt an explicitly secret value", (){ TOKEN: "protected" },);});++test("MaskedExecutionError keeps the original error class, code and masked stack", () => {+ const mask = createExactSecretValueMasker(["s3cr3t-value"]);+ const original = Object.assign(new TypeError("connect failed for s3cr3t-value"), { code: "ECONNRESET" });+ const masked = new MaskedExecutionError(original, mask, mask(original.message));+ assert.equal(masked.message, "connect failed for <redacted:credential>");+ assert.equal(masked.name, "TypeError");+ assert.equal(masked.code, "ECONNRESET");+ assert.match(masked.stack ?? "", /^TypeError: connect failed for <redacted:credential>\n\s+at /);+ assert.doesNotMatch(masked.stack ?? "", /s3cr3t-value/);+});diff --git a/test/sprites-sandbox.test.ts b/test/sprites-sandbox.test.tsindex baad4eabb..d481f0b54 100644--- a/test/sprites-sandbox.test.ts+++ b/test/sprites-sandbox.test.ts@@ -800,7 +800,7 @@ test("failed scratch initialization and deletion retain a safe retryable identitpending = error.handle;assert.equal(pending.backend, "sprites");assert.ok(fake.names().includes(pending.id));- assert.equal(error.cause, undefined);+ assert.ok(error.cause);return true;});assert.ok(pending);