Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Log discarded errors at 39 empty-catch sites (#2474)

Regan Bell69b2cfb01eda
diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.html
index a85083413..64872a866 100644
--- a/plugins/admin/public/index.html
+++ b/plugins/admin/public/index.html
@@ -6899,9 +6899,12 @@
let data = null;
try {
data = text ? JSON.parse(text) : null;
- } catch {}
+ } catch (error) {
+ console.warn("[swallowed] admin api: non-JSON response", method, path, res.status, error);
+ }
return { ok: res.ok, status: res.status, data };
- } catch {
+ } catch (error) {
+ console.warn("[swallowed] admin api: request failed", method, path, error);
return { ok: false, status: 0, data: { message: "Network request failed." } };
}
}
@@ -8153,7 +8156,7 @@
refreshModelChoices.forEach((refresh) => refresh());
initCustomDropdowns($("view-governance"));
})
- .catch(() => {});
+ .catch((error) => console.warn("[swallowed] admin: model catalog refresh", error));
}
}
async function refreshSoulConflict() {
diff --git a/plugins/admin/ui/onboarding.ts b/plugins/admin/ui/onboarding.ts
index 2702ffef4..f0894494f 100644
--- a/plugins/admin/ui/onboarding.ts
+++ b/plugins/admin/ui/onboarding.ts
@@ -1,4 +1,5 @@
import { html, nothing, render } from "lit";
+import { swallowAs } from "../../chassis/src/errors.ts";
type Data = Record<string, any>;
const providerLabels: Record<string, string> = {
anthropic: "Anthropic",
@@ -151,7 +152,7 @@ export class Onboarding {
const token = ++this.request,
view = this.context.view();
const selection = { provider: this.provider, model: this.model, apiKey: this.apiKey };
- void this.loadRegistry().catch(() => {});
+ void this.loadRegistry().catch(swallowAs("admin: load model registry", undefined));
const [models, slack, catalog, config] = await Promise.all([
this.context.api("GET", "/api/model-providers?catalog=cached"),
this.context.api("GET", "/api/slack-installation"),
diff --git a/plugins/chassis/src/errors.ts b/plugins/chassis/src/errors.ts
index e4f5c3c06..5c4b232e4 100644
--- a/plugins/chassis/src/errors.ts
+++ b/plugins/chassis/src/errors.ts
@@ -1,3 +1,5 @@
+import { isSensitiveKey, redactSecrets } from "./redact-secrets.ts";
+
export function errMessage(e: unknown, fallback?: string): string {
if (e instanceof Error) return e.message;
if (fallback !== undefined) return fallback;
@@ -42,12 +44,14 @@ function errorFields(e: unknown): string {
const fields = Object.entries(Object.getOwnPropertyDescriptors(e))
.filter(([key, descriptor]) => key !== "cause" && descriptor.enumerable)
.map(([key, descriptor]) => {
+ if (isSensitiveKey(key)) return `${key}=[redacted]`;
try {
const seen = new Set<object>();
const value = descriptor.value;
const text =
typeof value === "object" && value !== null
- ? JSON.stringify(value, (_key, item) => {
+ ? JSON.stringify(value, (itemKey, item) => {
+ if (isSensitiveKey(itemKey)) return "[redacted]";
if (typeof item === "bigint") return String(item);
if (typeof item === "object" && item !== null) {
if (seen.has(item)) return "[Circular]";
@@ -56,7 +60,7 @@ function errorFields(e: unknown): string {
return item;
})
: String(value);
- return `${key}=${descriptor.get ? "[Getter]" : text}`;
+ return `${key}=${descriptor.get ? "[Getter]" : redactSecrets(text)}`;
} catch {
return `${key}=[Unserializable]`;
}
diff --git a/src/harness/redact-secrets.ts b/plugins/chassis/src/redact-secrets.ts
similarity index 85%
rename from src/harness/redact-secrets.ts
rename to plugins/chassis/src/redact-secrets.ts
index 59332a9d0..e213f6a95 100644
--- a/src/harness/redact-secrets.ts
+++ b/plugins/chassis/src/redact-secrets.ts
@@ -1,23 +1,20 @@
-const SENSITIVE_KEYS = new Set([
- "accesstoken",
- "refreshtoken",
- "idtoken",
+const SENSITIVE_KEY_SUFFIXES = [
+ "token",
"apikey",
- "clientsecret",
+ "secret",
+ "accesskey",
+ "privatekey",
"credential",
"credentials",
"password",
"passphrase",
- "secret",
- "token",
"authorization",
- "proxyauthorization",
"cookie",
- "setcookie",
-]);
+];
-function diagnosticKeyIsSensitive(key: string): boolean {
- return SENSITIVE_KEYS.has(key.toLowerCase().replace(/[^a-z]/g, ""));
+export function isSensitiveKey(key: string): boolean {
+ const normalized = key.toLowerCase().replace(/[^a-z]/g, "");
+ return SENSITIVE_KEY_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
}
function redactStructuredDiagnosticsValue(value: unknown, sensitive = false): unknown {
@@ -25,10 +22,7 @@ function redactStructuredDiagnosticsValue(value: unknown, sensitive = false): un
if (Array.isArray(value)) return value.map((item) => redactStructuredDiagnosticsValue(item));
if (!value || typeof value !== "object") return value;
return Object.fromEntries(
- Object.entries(value).map(([key, item]) => [
- key,
- redactStructuredDiagnosticsValue(item, diagnosticKeyIsSensitive(key)),
- ]),
+ Object.entries(value).map(([key, item]) => [key, redactStructuredDiagnosticsValue(item, isSensitiveKey(key))]),
);
}
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 7f580d199..63bab56c1 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -2,6 +2,7 @@ import "./instrument.ts";
import { handleVoiceRoute, sweepDictationSpool } from "./voice-routes.ts";
import { browserErrorConfig } from "./browser-error-config.ts";
import { flushErrorReporting, reportBackendError } from "../../chassis/src/error-reporting.ts";
+import { swallow } from "../../chassis/src/errors.ts";
import { appEditSlug } from "../src/app-edit.ts";
import { composioCallbackUrl } from "./composio-return.ts";
import { sharedSessionHtml } from "./shared-session.ts";
@@ -513,6 +514,7 @@ async function slackWorkspaceUrl(): Promise<string | null> {
const WEB_DELIVERY_POLL_MS = Number(process.env.WEB_DELIVERY_POLL_MS ?? 2500);
const WEB_DELIVERY_GIVEUP_MS = 60_000;
let deliveriesPollInFlight = false;
+let deliveriesPollFailing = false;
interface PendingWebDelivery {
id: string;
@@ -520,36 +522,53 @@ interface PendingWebDelivery {
destination?: { target?: string };
}
-async function drainWebDeliveries(): Promise<void> {
+export async function drainWebDeliveries(): Promise<void> {
if (deliveriesPollInFlight) return;
deliveriesPollInFlight = true;
try {
- const r = await coreFetch("GET", "/v1/deliveries?type=web");
- if (r.status !== 200) return;
- let pending: PendingWebDelivery[] = [];
- try {
- pending = (JSON.parse(r.text) as { deliveries?: PendingWebDelivery[] }).deliveries ?? [];
- } catch {
- return;
- }
- const now = Date.now();
- for (const d of pending) {
- const target = d.destination?.target ?? "";
- const conns = deliveryClients.get(ownerOfWebThread(target) ?? "");
- if (conns && conns.size) {
- for (const res of conns) sseEvent(res, "delivery", { threadRef: target });
- } else if (now - (d.createdAt ?? 0) < WEB_DELIVERY_GIVEUP_MS) {
- continue;
- }
- await coreFetch("POST", `/v1/deliveries/${encodeURIComponent(d.id)}/ack`).catch(() => {});
- }
- } catch {
- void 0;
+ noteDeliveriesPoll(await pollWebDeliveries());
+ } catch (e) {
+ noteDeliveriesPoll(e);
} finally {
deliveriesPollInFlight = false;
}
}
+function noteDeliveriesPoll(failure: unknown): void {
+ if (failure === undefined) {
+ if (deliveriesPollFailing) console.log("[web-ui] web delivery poll recovered");
+ deliveriesPollFailing = false;
+ return;
+ }
+ if (!deliveriesPollFailing) swallow("web-ui: web delivery poll (further failures quiet until recovery)", failure);
+ deliveriesPollFailing = true;
+}
+
+async function pollWebDeliveries(): Promise<unknown> {
+ const r = await coreFetch("GET", "/v1/deliveries?type=web");
+ if (r.status !== 200) return new Error(`GET /v1/deliveries http ${r.status}: ${r.text.slice(0, 200)}`);
+ const pending = (JSON.parse(r.text) as { deliveries?: PendingWebDelivery[] }).deliveries ?? [];
+ const now = Date.now();
+ let failure: unknown;
+ for (const d of pending) {
+ const target = d.destination?.target ?? "";
+ const conns = deliveryClients.get(ownerOfWebThread(target) ?? "");
+ if (conns && conns.size) {
+ for (const res of conns) sseEvent(res, "delivery", { threadRef: target });
+ } else if (now - (d.createdAt ?? 0) < WEB_DELIVERY_GIVEUP_MS) {
+ continue;
+ }
+ try {
+ const ack = await coreFetch("POST", `/v1/deliveries/${encodeURIComponent(d.id)}/ack`);
+ if (ack.status !== 200)
+ failure ??= new Error(`ack delivery ${d.id} http ${ack.status}: ${ack.text.slice(0, 200)}`);
+ } catch (e) {
+ failure ??= e;
+ }
+ }
+ return failure;
+}
+
const SSE_HEARTBEAT_MS = 15_000;
const STATE_FEED_RECONNECT_MS = Number(process.env.STATE_FEED_RECONNECT_MS ?? 3_000);
diff --git a/plugins/web-ui/src/app-annotations.ts b/plugins/web-ui/src/app-annotations.ts
index a36014b82..49d367af5 100644
--- a/plugins/web-ui/src/app-annotations.ts
+++ b/plugins/web-ui/src/app-annotations.ts
@@ -1,3 +1,5 @@
+import { swallowAs } from "../../chassis/src/errors.ts";
+
const MAX_ANNOTATION_TEXT = 20_000;
const MAX_ANNOTATION_BYTES = 20 * 1024 * 1024;
@@ -52,7 +54,7 @@ export function watchAppAnnotations(
(event.source as Window).postMessage({ type: "qm:annotations-ack", id: data.id }, event.origin);
};
const onMessage = (event: MessageEvent): void => {
- queue = queue.then(() => receive(event)).catch(() => undefined);
+ queue = queue.then(() => receive(event)).catch(swallowAs("web-ui: app annotation message", undefined));
};
window.addEventListener("message", onMessage);
return () => {
diff --git a/plugins/web-ui/src/generated-activities.ts b/plugins/web-ui/src/generated-activities.ts
index 299d4e116..d339dd840 100644
--- a/plugins/web-ui/src/generated-activities.ts
+++ b/plugins/web-ui/src/generated-activities.ts
@@ -1,5 +1,6 @@
import { parseSuggestedActivities } from "../../chassis/src/suggested-activities.ts";
import { api } from "./core-bridge";
+import { swallowAs } from "../../chassis/src/errors.ts";
import type { Me } from "./shell-state";
const requests = new WeakMap<Me, { until: number; pending: Promise<void> }>();
@@ -19,7 +20,7 @@ export function loadGeneratedActivities(me: Me, onChange?: () => void): Promise<
if (!response.pending) return;
await new Promise((resolve) => setTimeout(resolve, 10_000));
}
- })().catch(() => undefined);
+ })().catch(swallowAs("web-ui: load generated activities", undefined));
requests.set(me, { until: Date.now() + 5 * 60_000, pending });
return pending;
}
diff --git a/plugins/web-ui/src/search.ts b/plugins/web-ui/src/search.ts
index 0b6ed2cce..f3be45476 100644
--- a/plugins/web-ui/src/search.ts
+++ b/plugins/web-ui/src/search.ts
@@ -10,6 +10,7 @@ import { destinations } from "./browse";
import { UI_BASE } from "./deep-link";
import { resourceResults, matchResources, type ResourceHit, type ResourceSearchResponse } from "./search-resources";
import { icon } from "./icons";
+import { swallow } from "../../chassis/src/errors.ts";
interface ChatSearchHit {
sessionId: string;
@@ -163,8 +164,9 @@ async function runSearch(q: string): Promise<void> {
}
searchState.hits = hits;
searchState.failed = false;
- } catch {
+ } catch (e) {
if (seq !== fetchSeq || ctl.signal.aborted) return;
+ swallow("web-ui: chat search", e);
searchState.hits = [];
searchState.failed = true;
}
@@ -190,8 +192,9 @@ async function runResourceSearch(q: string, ctl: AbortController, seq: number):
searchState.resources = result.hits;
searchState.resourcesLimited = Boolean(response.limited?.length);
searchState.resourceFailures = result.failed;
- } catch {
+ } catch (e) {
if (seq !== fetchSeq || ctl.signal.aborted) return;
+ swallow("web-ui: resource search", e);
searchState.resourceFailures = ["resources"];
}
searchState.resourcesLoading = false;
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index 7c1844024..385f260d7 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -71,7 +71,7 @@ import {
type ChatBrowseStatus,
} from "./session-list";
import { tip } from "./tooltip";
-import { errMessage } from "../../chassis/src/errors";
+import { errMessage, swallow, swallowAs } from "../../chassis/src/errors";
import { copyText, menuSelect, relTime, workingWave } from "./ui";
import { slackMark } from "./slack-mark";
import { icon } from "./icons";
@@ -1581,8 +1581,8 @@ async function refreshSessionTitle(s: CoreSession): Promise<void> {
);
}
renderList();
- } catch {
- void 0;
+ } catch (e) {
+ swallow("web-ui: regenerate session title", e);
} finally {
await refreshSessions({ silent: true });
refreshingTitleIds.delete(s.id);
@@ -1598,7 +1598,8 @@ async function persistSessionPatch(id: string, patch: SessionPatch): Promise<voi
try {
await request;
renderList();
- } catch {
+ } catch (e) {
+ swallow("web-ui: save session change", e);
if (sessionPatchGeneration === generation) await refreshSessions({ silent: true, patchEpoch: sessionPatchEpoch });
}
}
@@ -1802,7 +1803,7 @@ export async function openSessionInto(
const isCurrent = conv.mountLoadingPane();
const fetchEntries = (): Promise<TranscriptPage | null> =>
- fetchTranscript(s.id, { tailTurns: TAIL_TURNS }).catch(() => null);
+ fetchTranscript(s.id, { tailTurns: TAIL_TURNS }).catch(swallowAs("web-ui: load session transcript", null));
const continuable = s.canContinue === true;
// Approvals load alongside the transcript but never hold up the first draw:
// the chat mounts as soon as entries arrive, and cards attach when this settles.
diff --git a/plugins/web-ui/src/settings.ts b/plugins/web-ui/src/settings.ts
index c853cb0bd..fe16bbf8d 100644
--- a/plugins/web-ui/src/settings.ts
+++ b/plugins/web-ui/src/settings.ts
@@ -16,7 +16,7 @@ import { Download, ExternalLink, LogOut, Monitor, Moon, ShieldUser, Sun, type Ic
import { icon } from "./icons";
import { ADMIN_HOME_URL, appState, can, signOut } from "./shell";
import { sessionsState, setWebOnly } from "./sessions";
-import { errMessage } from "../../chassis/src/errors";
+import { errMessage, swallowAs } from "../../chassis/src/errors";
import { importTheme, isPalette, themeCss, themeTokens, type Palette } from "./theme-import";
type ThemeChoice = "light" | "dark" | "system" | "custom";
@@ -269,7 +269,9 @@ function setOpenNewChat(value: boolean): void {
openNewChatTouched = true;
openNewChat = value;
drawSettings();
- void putUiState(OPEN_NEW_CHAT_KEY, value, Date.now()).catch(() => void 0);
+ void putUiState(OPEN_NEW_CHAT_KEY, value, Date.now()).catch(
+ swallowAs("web-ui: save open-new-chat setting", undefined),
+ );
}
const OPEN_OPTIONS: Array<{ newChat: boolean; label: string }> = [
diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.ts
index eec22e402..9077a4544 100644
--- a/plugins/web-ui/src/split.ts
+++ b/plugins/web-ui/src/split.ts
@@ -1,5 +1,6 @@
import { openSessionShare } from "./session-share";
import { preserveTranscriptScroll } from "./transcript-viewport";
+import { swallow, swallowAs } from "../../chassis/src/errors.ts";
import { html, nothing, render, type TemplateResult } from "lit";
import { ref } from "lit/directives/ref.js";
import {
@@ -146,8 +147,8 @@ function persist(): void {
const payload = { v: 2, active: splitState.active, layout: lastLayout, updatedAt: persistedUpdatedAt };
localStorage.setItem(STORE_KEY, JSON.stringify(payload));
pushRemoteSoon(payload);
- } catch {
- void 0;
+ } catch (e) {
+ swallow("web-ui: persist split layout", e);
}
}
@@ -158,7 +159,7 @@ function pushRemoteSoon(payload: { updatedAt: number }): void {
remoteTimer = null;
const p = remotePayload;
remotePayload = null;
- if (p) void putUiState(REMOTE_STATE_KEY, p, p.updatedAt).catch(() => void 0);
+ if (p) void putUiState(REMOTE_STATE_KEY, p, p.updatedAt).catch(swallowAs("web-ui: sync split layout", undefined));
}, 400);
}
@@ -175,7 +176,9 @@ function flushRemoteNow(): void {
const p = remotePayload;
if (!p) return;
remotePayload = null;
- void putUiState(REMOTE_STATE_KEY, p, p.updatedAt, { keepalive: true }).catch(() => void 0);
+ void putUiState(REMOTE_STATE_KEY, p, p.updatedAt, { keepalive: true }).catch(
+ swallowAs("web-ui: flush split layout", undefined),
+ );
}
window.addEventListener("pagehide", flushRemoteNow);
@@ -472,7 +475,7 @@ export function loadPersistedSplit(): void {
export function fetchRemoteSplit(timeoutMs = 2000): Promise<UiStateRecord | null> {
return Promise.race([
- fetchUiState(REMOTE_STATE_KEY).catch(() => null),
+ fetchUiState(REMOTE_STATE_KEY).catch(swallowAs("web-ui: fetch synced split layout", null)),
new Promise<null>((resolve) => window.setTimeout(() => resolve(null), timeoutMs)),
]);
}
@@ -486,8 +489,8 @@ export async function adoptRemoteSplit(pending: Promise<UiStateRecord | null>):
persistedUpdatedAt = at;
try {
localStorage.setItem(STORE_KEY, JSON.stringify({ ...rec.value, updatedAt: at }));
- } catch {
- void 0;
+ } catch (e) {
+ swallow("web-ui: cache synced split layout", e);
}
}
diff --git a/scripts/dev/cli.ts b/scripts/dev/cli.ts
index f5614ade4..d051764e5 100644
--- a/scripts/dev/cli.ts
+++ b/scripts/dev/cli.ts
@@ -40,7 +40,7 @@ import {
} from "./lib/client.ts";
import { sweepSlackTokenOrphans } from "./lib/orphans.ts";
import { destroyLocalDevSandboxes } from "./lib/sandbox.ts";
-import { bestEffort, errMessage, formatAge, nowEpoch, sleep } from "./lib/util.ts";
+import { bestEffort, errMessage, formatAge, nowEpoch, sleep, swallowAs } from "./lib/util.ts";
import { runDoctor } from "./commands/doctor.ts";
import type { BootPhaseEvent, BootResult, DevSandboxChoice, LeaseInfo } from "./lib/types.ts";
import { CHILD_ORDER, EXIT } from "./lib/types.ts";
@@ -137,14 +137,16 @@ async function legacyTeardown(lease: LeaseInfo): Promise<void> {
const pid = readPidFile(lease.lockDir, `${name}.pid`);
if (pid) await killTree(pid, 5000);
}
- await destroyLocalDevSandboxes((m) => out(m)).catch(() => undefined);
+ await destroyLocalDevSandboxes((m) => out(m)).catch(swallowAs("dev: destroy local sandboxes", undefined));
releaseSlotLock(lease.slot, store);
}
async function teardownLease(lease: LeaseInfo): Promise<void> {
const sock = resolveSocketPath(lease.lockDir);
if (await supervisorReachable(sock)) {
- await supervisorRequest(sock, "POST", "/shutdown", {}).catch(() => {});
+ await supervisorRequest(sock, "POST", "/shutdown", {}).catch(
+ swallowAs("dev: supervisor shutdown request", undefined),
+ );
const deadline = Date.now() + 20_000;
while (Date.now() < deadline && existsSync(lease.lockDir)) await sleep(300);
if (!existsSync(lease.lockDir)) return;
@@ -294,7 +296,7 @@ async function bootOnSlot(slot: string, worktree: string, branch: string): Promi
await streamBootEvents(sock, (e) => {
renderPhase(e);
if (e.event === "done" && e.result) result = e.result;
- }).catch(() => {});
+ }).catch(swallowAs("dev: boot event stream", undefined));
return result ?? { ok: false, reason: "boot event stream ended without a result", slot };
}
diff --git a/scripts/dev/lib/util.ts b/scripts/dev/lib/util.ts
index 39184b96c..7b639302e 100644
--- a/scripts/dev/lib/util.ts
+++ b/scripts/dev/lib/util.ts
@@ -40,7 +40,7 @@ export function envSha(env: Record<string, string>): string {
return sha256Hex(lines.join("\n")).slice(0, 16);
}
-export { errMessage } from "../../../src/util/errors.ts";
+export { errMessage, swallowAs } from "../../../src/util/errors.ts";
export function bestEffort(fn: () => void): unknown {
try {
diff --git a/scripts/dev/twin-instance.ts b/scripts/dev/twin-instance.ts
index 9b3bf7788..966e83cf4 100644
--- a/scripts/dev/twin-instance.ts
+++ b/scripts/dev/twin-instance.ts
@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync }
import { join } from "node:path";
import { provisionTwinEnvironment, teardownTwinEnvironment } from "../../test/live-slack/arga-provision.ts";
import { readEnvFile } from "../../cli/src/util.ts";
+import { swallowAs } from "../../src/util/errors.ts";
const root = fileURLToPath(new URL("../..", import.meta.url)).replace(/\/$/, "");
const dir = join(root, ".twin-instance");
@@ -31,7 +32,9 @@ async function up(): Promise<void> {
stdio: "inherit",
});
if (boot.status !== 0) {
- await teardownTwinEnvironment(process.env.ARGA_API_KEY!, bootEnv.ARGA_TWIN_RUN_ID).catch(() => {});
+ await teardownTwinEnvironment(process.env.ARGA_API_KEY!, bootEnv.ARGA_TWIN_RUN_ID).catch(
+ swallowAs("twin instance: teardown after failed boot", undefined),
+ );
rmSync(dir, { recursive: true, force: true });
throw new Error("instance boot failed — twin torn down");
}
diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.ts
index d95f6cc98..365dd599f 100644
--- a/src/api/app-helpers.ts
+++ b/src/api/app-helpers.ts
@@ -406,7 +406,7 @@ export function createAppHelpers(deps: AppDeps, app: App) {
for (const groupId of groups) scopes.add(scopeId("group", groupId));
for (const project of projects) scopes.add(project.scopeId);
} catch (error) {
- void error;
+ swallow("app: current resource scopes for viewer", error);
}
return [...scopes];
}
diff --git a/src/api/app-search.ts b/src/api/app-search.ts
index 605dc65d6..6da55638c 100644
--- a/src/api/app-search.ts
+++ b/src/api/app-search.ts
@@ -5,6 +5,7 @@ import { matchesSearchTerms, searchSnippet, searchTerms } from "../sessions/entr
import type { Principal } from "../types.ts";
import { conversationWebUrl } from "../util/conversation-links.ts";
import { collectBytes } from "../util/bytes.ts";
+import { swallowAs } from "../util/errors.ts";
import type { App, AppDeps } from "./app-types.ts";
import type { AppHelpers } from "./app-helpers.ts";
@@ -73,7 +74,9 @@ function fileBackend(deps: AppDeps, app: App, helpers: AppHelpers): SearchBacken
if (searchableFile(file.mimetype, file.name)) {
const opened = await app.openFileForViewer(file.id, request.principals[0]!.id);
if (opened) {
- const collected = await collectBytes(opened.stream, { maxBytes: 512 * 1024 }).catch(() => null);
+ const collected = await collectBytes(opened.stream, { maxBytes: 512 * 1024 }).catch(
+ swallowAs("app search: read file contents", null),
+ );
if (collected) text += `\n${collected.data.toString("utf8")}`;
}
}
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index f53636265..7a54ac91a 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -18,6 +18,7 @@ import { cronIsActive, cronTiedTo } from "../cron/cron-store.ts";
import { cronRef, deployRef, encodeRef, fileRef, parseRef, skillRef } from "../acl/resource-ref.ts";
import { samePerson } from "../directory/person.ts";
import { AdminError } from "../admin/admin-service.ts";
+import { swallowAs } from "../util/errors.ts";
import { type ArtifactHome } from "./artifact-share.ts";
import { randomUUID } from "node:crypto";
import { isOpenScopeMember } from "../resolution/sharing-access.ts";
@@ -643,7 +644,9 @@ export function createSessionMethods(
if (e instanceof ProcessSessionGoneError) return { chunk: "", cursor: sinceCursor, state: "exited" };
throw e;
} finally {
- await sandbox.teardown(handle, { keepWarm: true }).catch(() => {});
+ await sandbox
+ .teardown(handle, { keepWarm: true })
+ .catch(swallowAs("app sessions: release process sandbox", undefined));
}
},
diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.ts
index 4fb3a0a79..f8426d591 100644
--- a/src/api/routes/admin-resources.ts
+++ b/src/api/routes/admin-resources.ts
@@ -43,7 +43,7 @@ import { authorizeUrl, PROVIDERS, type ConsentMode } from "../../connectors/oaut
import { resolverFor } from "./connectors.ts";
import { encodeRef, serviceCredRef } from "../../acl/resource-ref.ts";
import { audit } from "./shared.ts";
-import { errMessage, reportFailure } from "../../util/errors.ts";
+import { errMessage, reportFailure, swallowAs } from "../../util/errors.ts";
import {
DEFAULT_SECURITY_SCREEN_RUBRIC,
parseSecurityPosture,
@@ -281,7 +281,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [
get: async (deps, scope) => {
const ref = channelContainer(scope);
if (!deps.channelPolicy || !ref) return undefined;
- const p = await deps.channelPolicy.get(ref).catch(() => undefined);
+ const p = await deps.channelPolicy.get(ref).catch(swallowAs("admin: read channel ambient policy", undefined));
if (p === undefined) return undefined;
return {
orders: p?.orders ?? "",
diff --git a/src/api/routes/composio.ts b/src/api/routes/composio.ts
index ce908f50d..99161ed79 100644
--- a/src/api/routes/composio.ts
+++ b/src/api/routes/composio.ts
@@ -12,7 +12,7 @@ import { parseRef } from "../../acl/resource-ref.ts";
import { orgId } from "../../config.ts";
import { principalEntitledToScope } from "../../resolution/context-filter.ts";
import { sendJson } from "../http.ts";
-import { redactSecrets } from "../../harness/redact-secrets.ts";
+import { redactSecrets } from "../../../plugins/chassis/src/redact-secrets.ts";
import { createExactSecretValueMasker } from "../../security/secret-masking.ts";
import { errMessage, httpFailure, reportFailure } from "../../util/errors.ts";
import { activePrincipal, audit } from "./shared.ts";
diff --git a/src/api/routes/connectors.ts b/src/api/routes/connectors.ts
index 860166103..438693296 100644
--- a/src/api/routes/connectors.ts
+++ b/src/api/routes/connectors.ts
@@ -22,7 +22,7 @@ import type { ConnectorTokenStore, DerivedOAuthAuth, OAuthTokenStatus } from "..
import { createEnvSecretSource } from "../../credentials/secret-source.ts";
import type { ServerDeps } from "../deps.ts";
import { personKey, samePerson } from "../../directory/person.ts";
-import { errMessage } from "../../util/errors.ts";
+import { errMessage, swallowAs } from "../../util/errors.ts";
import { normalizeInboundExpiresAt } from "../expiry.ts";
import { sendJson, sendRedirect } from "../http.ts";
import { audit } from "./shared.ts";
@@ -171,7 +171,7 @@ async function oauthCallback(ctx: BaseCtx): Promise<void> {
scopeLabel: state.principalId,
});
if (state.consentLinkId && deps.consentLinks) {
- await deps.consentLinks.redeem(state.consentLinkId).catch(() => null);
+ await deps.consentLinks.redeem(state.consentLinkId).catch(swallowAs("connectors: redeem consent link", null));
}
if (state.returnTo) {
const dest = new URL(state.returnTo, "http://localhost");
@@ -192,7 +192,7 @@ async function principalHasProvider(deps: ServerDeps, provider: string, principa
for (const at of ACCOUNT_TYPES) {
const st = await deps.connectorTokens
.connectorTokenStatus(host, principalId, at)
- .catch(() => ({ connected: false }) as OAuthTokenStatus);
+ .catch(swallowAs("connectors: token status", { connected: false } as OAuthTokenStatus));
if (st.connected && !st.needsReconnect) return true;
}
}
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index 767e10e75..5d6a3a510 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -13,7 +13,7 @@ import {
import { spawn } from "node:child_process";
import { basename, dirname } from "node:path";
import { deploymentView, type App, type DeployInput, type RedeployInput } from "../app.ts";
-import { errMessage, reportFailureAs } from "../../util/errors.ts";
+import { errMessage, reportFailureAs, swallowAs } from "../../util/errors.ts";
import { escapeHtml } from "../../../plugins/chassis/src/http.ts";
import { canonicalPayload } from "../../../plugins/chassis/src/source-auth-sign.ts";
import { sendJson, verifyOrReject } from "../http.ts";
@@ -97,7 +97,7 @@ async function proxyDeployment(ctx: BaseCtx): Promise<void> {
method === "GET" &&
String(req.headers["sec-fetch-dest"] ?? "") === "document"
) {
- const d = await app.getDeployment(id).catch(() => null);
+ const d = await app.getDeployment(id).catch(swallowAs("deployments: load deployment", null));
const slug = d?.name ?? d?.id;
if (d && slug && /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(slug)) {
res.writeHead(302, {
@@ -841,7 +841,7 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
cleanUrlRedirect();
return true;
}
- const deployment = await app.getDeployment(slug).catch(() => null);
+ const deployment = await app.getDeployment(slug).catch(swallowAs("deployments: load deployment", null));
const externalAllowed = deployment
? await externalAppSharingAllowed(deps.featureFlags, deployment.ownerScopeId)
: false;
@@ -969,7 +969,7 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
canManage || isPublic || session?.appOnly ? { bypassAcl: true } : undefined,
);
if (reach.status === "denied") {
- const owner = (await app.getDeployment(slug).catch(() => null))?.ownerScopeId;
+ const owner = (await app.getDeployment(slug).catch(swallowAs("deployments: load deployment", null)))?.ownerScopeId;
const ev = {
at: Date.now(),
principalId: viewer,
@@ -983,7 +983,7 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
else deps.auditLog?.record(ev);
}
if (reach.status === "denied" && ctx.method === "POST" && pathname === REQUEST_ACCESS_PATH) {
- const d = await app.getDeployment(slug).catch(() => null);
+ const d = await app.getDeployment(slug).catch(swallowAs("deployments: load deployment", null));
if (!d) {
sendJson(res, 404, { error: "not_found" });
return true;
diff --git a/src/api/routes/slack-composio.ts b/src/api/routes/slack-composio.ts
index e153506c4..db2076e79 100644
--- a/src/api/routes/slack-composio.ts
+++ b/src/api/routes/slack-composio.ts
@@ -1,5 +1,5 @@
import { createExactSecretValueMasker } from "../../security/secret-masking.ts";
-import { redactSecrets } from "../../harness/redact-secrets.ts";
+import { redactSecrets } from "../../../plugins/chassis/src/redact-secrets.ts";
import { errMessage } from "../../util/errors.ts";
import { personIds, samePerson } from "../../directory/person.ts";
import { composioUserIds, credential, request as composioRequest } from "./composio.ts";
diff --git a/src/api/routes/slack-native.ts b/src/api/routes/slack-native.ts
index b3d8d183e..631e32b4f 100644
--- a/src/api/routes/slack-native.ts
+++ b/src/api/routes/slack-native.ts
@@ -1,5 +1,5 @@
import { createExactSecretValueMasker } from "../../security/secret-masking.ts";
-import { redactSecrets } from "../../harness/redact-secrets.ts";
+import { redactSecrets } from "../../../plugins/chassis/src/redact-secrets.ts";
import { errMessage } from "../../util/errors.ts";
import { ErrorCode, type WebAPIPlatformError, type AuthTestResponse } from "@slack/web-api";
import { slackWebClient } from "../../slack/web-client.ts";
diff --git a/src/api/routes/turns.ts b/src/api/routes/turns.ts
index e46105f98..5efad1a96 100644
--- a/src/api/routes/turns.ts
+++ b/src/api/routes/turns.ts
@@ -3,6 +3,7 @@ import type { ClientToolDeclaration, TurnOrigin, TurnRequest } from "../../types
import { resolveTurnOrigin } from "../../core/turn-origin.ts";
import { samePerson } from "../../directory/person.ts";
import { sendJson } from "../http.ts";
+import { swallowAs } from "../../util/errors.ts";
import { isObj } from "./shared.ts";
import { type ApiCtx, type Route } from "./route.ts";
@@ -302,7 +303,7 @@ async function postTurnMetrics(ctx: ApiCtx): Promise<void> {
...(deliverMs !== undefined ? { deliverMs } : {}),
...(slackInflightMs !== undefined ? { slackInflightMs } : {}),
})
- .catch(() => undefined);
+ .catch(swallowAs("turn metrics: record delivery timing", undefined));
return sendJson(res, 200, { ok: true });
}
diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.ts
index fdf1470dd..aa90dfaa5 100644
--- a/src/api/slack-core-client.ts
+++ b/src/api/slack-core-client.ts
@@ -536,7 +536,7 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien
...(pick.latencyMs != null ? { latencyMs: pick.latencyMs } : {}),
createdAt: Date.now(),
})
- .catch(() => {});
+ .catch(swallowAs("slack: record ack emoji pick", undefined));
},
async fulfillContextRequest(id, outcome) {
diff --git a/src/connectors/oauth-flow-store.ts b/src/connectors/oauth-flow-store.ts
index b965bd459..8edb0bb2d 100644
--- a/src/connectors/oauth-flow-store.ts
+++ b/src/connectors/oauth-flow-store.ts
@@ -1,6 +1,7 @@
import { randomBytes } from "node:crypto";
import type { DurableMap } from "../persistence/durable-map.ts";
import type { OAuthState } from "./oauth.ts";
+import { swallowAs } from "../util/errors.ts";
/**
* The authorize `state` parameter has to survive a provider round trip, and
@@ -31,7 +32,7 @@ export function createOAuthFlowStore(
return flowId;
},
async finish(flowId, now) {
- const rec = await backing.take(flowId).catch(() => null);
+ const rec = await backing.take(flowId).catch(swallowAs("oauth flow: take state", null));
if (!rec) return null;
if ((now ?? clock()) - rec.issuedAt > ttl) return null;
return rec;
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 687b577a3..75d366fd1 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -611,8 +611,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (!managedGroupRef) return true;
const expected = new Set(input.sessionParticipantIds ?? []);
const [current, version] = await Promise.all([
- deps.managedGroups!.members(managedGroupRef).catch(() => undefined),
- deps.managedGroups!.version(managedGroupRef).catch(() => undefined),
+ deps.managedGroups!.members(managedGroupRef).catch(swallowAs("managed group roster: members", undefined)),
+ deps.managedGroups!.version(managedGroupRef).catch(swallowAs("managed group roster: version", undefined)),
]);
return (
!!current &&
@@ -806,12 +806,14 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
hasUnscreenableAttachment = true;
continue;
}
- const opened = await blobTransfer.open(attachment.blobId).catch(() => null);
+ const opened = await blobTransfer
+ .open(attachment.blobId)
+ .catch(swallowAs("attachment screening: open blob", null));
if (!opened || opened.sizeBytes > MAX_AUTO_ATTACHMENT_SCREEN_BYTES) {
hasUnscreenableAttachment = true;
continue;
}
- const data = await collectBlob(opened.stream).catch(() => null);
+ const data = await collectBlob(opened.stream).catch(swallowAs("attachment screening: read blob", null));
if (!data || data.length > MAX_AUTO_ATTACHMENT_SCREEN_BYTES || data.includes(0)) {
hasUnscreenableAttachment = true;
continue;
@@ -1168,7 +1170,11 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const snapshot = structuredClone(entry);
const screenSkill = async () => {
const bundles = structuredClone(
- deps.skillBundles ? await loadActiveBundles(deps.skillBundles, [snapshot]).catch(() => null) : [],
+ deps.skillBundles
+ ? await loadActiveBundles(deps.skillBundles, [snapshot]).catch(
+ swallowAs("skill screening: load bundles", null),
+ )
+ : [],
);
const payload = JSON.stringify({ manifest: snapshot.skill!.manifest, bundles });
const key = hashId([skill.scopeId, skill.id, payload], 64);
diff --git a/src/core/orchestrator/surface-tools.ts b/src/core/orchestrator/surface-tools.ts
index 4c81a59dd..8f0f98611 100644
--- a/src/core/orchestrator/surface-tools.ts
+++ b/src/core/orchestrator/surface-tools.ts
@@ -37,7 +37,7 @@ import {
} from "../attachments.ts";
import { parseBotLedger, type BotPolicy, type ChannelPolicy } from "../../surface-cache/channel-policy-store.ts";
import { isoFromTs } from "../../util/message-tag.ts";
-import { errMessage } from "../../util/errors.ts";
+import { errMessage, swallowAs } from "../../util/errors.ts";
import { adminSessionUrl } from "../../util/admin-links.ts";
import { headLooksLikeText, replaceThreadSegment, type TurnPostKeys } from "./turn-helpers.ts";
import type { OrchestratorDeps, OrchestratorInput } from "./types.ts";
@@ -197,7 +197,9 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
const container = currentDestination.target ?? conversation.channelRef ?? conversation.threadRef;
if (!deps.surfaceCache || !container) return coverageSince;
const cacheContainer = currentDestination.type === "slack" ? container.split(":")[0]! : container;
- const st = await deps.surfaceCache.containerState(cacheContainer).catch(() => null);
+ const st = await deps.surfaceCache
+ .containerState(cacheContainer)
+ .catch(swallowAs("surface cache: container coverage", null));
coverageSince = st?.oldestTs ? isoFromTs(st.oldestTs) || undefined : undefined;
return coverageSince;
};
diff --git a/src/credentials/secret-drop.ts b/src/credentials/secret-drop.ts
index 14e6d558b..5f2b958f1 100644
--- a/src/credentials/secret-drop.ts
+++ b/src/credentials/secret-drop.ts
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import type { DurableMap } from "../persistence/durable-map.ts";
import type { Destination, ScopeId } from "../types.ts";
import type { GrantMode } from "./keychain.ts";
+import { swallowAs } from "../util/errors.ts";
export interface SecretDropField {
key: string;
@@ -66,7 +67,7 @@ export function createSecretDropStore(
const out: SecretDropRecord[] = [];
for (const [id, r] of await backing.entries()) {
if (at - r.createdAt > ttl) {
- void backing.delete(id).catch(() => {});
+ void backing.delete(id).catch(swallowAs("secret drop: delete expired drop", undefined));
continue;
}
if (
diff --git a/src/cron/job-queue.ts b/src/cron/job-queue.ts
index 6e7278d43..ce41e851e 100644
--- a/src/cron/job-queue.ts
+++ b/src/cron/job-queue.ts
@@ -1,6 +1,6 @@
import { PgBoss } from "pg-boss";
import { createPgPool, type PgPool } from "../persistence/pg-pool.ts";
-import { errMessage } from "../util/errors.ts";
+import { errMessage, swallowAs } from "../util/errors.ts";
export interface CronFireJob {
cronId: string;
@@ -71,9 +71,13 @@ export function createPgBossCronQueue(
);
} catch (e) {
if (initialized) {
- await boss.offWork(FIRE_QUEUE, { wait: false }).catch(() => {});
+ await boss
+ .offWork(FIRE_QUEUE, { wait: false })
+ .catch(swallowAs("cron queue: stop worker after failed start", undefined));
} else {
- await boss.stop({ close: true, graceful: false }).catch(() => {});
+ await boss
+ .stop({ close: true, graceful: false })
+ .catch(swallowAs("cron queue: stop after failed start", undefined));
await closePool();
}
throw e;
diff --git a/src/deploy/aws-deploy-provider.ts b/src/deploy/aws-deploy-provider.ts
index b9d8b421f..604edfb9a 100644
--- a/src/deploy/aws-deploy-provider.ts
+++ b/src/deploy/aws-deploy-provider.ts
@@ -9,7 +9,7 @@ import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts"
import { createNoopAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";
import { createKeyedQueue, sleep } from "../util/async.ts";
import { shq } from "../util/shell.ts";
-import { execFailure, swallow } from "../util/errors.ts";
+import { execFailure, swallow, swallowAs } from "../util/errors.ts";
import {
appEnv,
appGone,
@@ -288,7 +288,9 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
}
if (made.code !== 0) throw new Error(`data snapshot tar failed (code ${made.code}): ${made.stderr.slice(0, 200)}`);
const tar = await readAbsBytes(id, endpoint, tarPath);
- await execRaw(id, endpoint, `rm -f ${shq(tarPath)}`, 30).catch(() => {});
+ await execRaw(id, endpoint, `rm -f ${shq(tarPath)}`, 30).catch(
+ swallowAs("aws-deploy: remove data snapshot tar", undefined),
+ );
if (!tar?.length) throw new Error("data snapshot read-back empty");
await s3.send(new PutObjectCommand({ Bucket: dataBucket, Key: dataKeyFor(deploymentId), Body: tar }));
return true;
@@ -380,7 +382,9 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
next = await launchBody(d.id, d.alwaysOn);
const replacement = next;
await store.put(d.id, { ...stored, replacementMicrovmId: replacement.id });
- await ensureRunning(stored.microvmId, stored.endpoint, desc).catch(() => {});
+ await ensureRunning(stored.microvmId, stored.endpoint, desc).catch(
+ swallowAs("aws-deploy: keep old body running during replacement", undefined),
+ );
const defer = async (
label: string,
e: unknown,
@@ -613,7 +617,9 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
await refreshLitestream(d.id, cur.microvmId, cur.endpoint);
await store.put(d.id, { ...cur, dataCredsAtMs: Date.now() });
} catch (e) {
- await store.put(d.id, { ...cur, dataCredsAtMs: failureBackoffStamp() }).catch(() => {});
+ await store
+ .put(d.id, { ...cur, dataCredsAtMs: failureBackoffStamp() })
+ .catch(swallowAs("aws-deploy: stamp litestream creds backoff", undefined));
throw e;
}
}).catch((e) => swallow("aws-deploy: litestream creds refresh", e));
diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.ts
index 3efa8843f..774f8ed69 100644
--- a/src/deploy/deploy-service.ts
+++ b/src/deploy/deploy-service.ts
@@ -25,7 +25,7 @@ import type { DeployProfile, DeployProvider } from "./deploy-provider.ts";
import { createNoopLeaderLease, type LeaderLease } from "../persistence/leader-lease.ts";
import { createNoopAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";
import { createKeyedQueue } from "../util/async.ts";
-import { errMessage, reportFailure, swallow } from "../util/errors.ts";
+import { errMessage, reportFailure, swallow, swallowAs } from "../util/errors.ts";
export interface DeployFile {
path: string;
@@ -372,7 +372,9 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
});
const endpoint = await applyVersion(d.id, d.versions[0]!);
await markVersionRunning(d.id, d.versions[0]!.version, endpoint);
- void deps.appPublished?.(input.createdBy, d.id, d.versions[0]!.version).catch(() => {});
+ void deps
+ .appPublished?.(input.createdBy, d.id, d.versions[0]!.version)
+ .catch(swallowAs("deploy: app published hook", undefined));
deps.auditLog.record({
at: Date.now(),
principalId: input.createdBy,
@@ -403,7 +405,9 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
});
const endpoint = await applyVersion(id, v, before.appliedVersion ?? before.currentVersion, input.alwaysOn);
await markVersionRunning(id, v.version, endpoint);
- void deps.appPublished?.(before.createdBy, id, v.version).catch(() => {});
+ void deps
+ .appPublished?.(before.createdBy, id, v.version)
+ .catch(swallowAs("deploy: app published hook", undefined));
deps.auditLog.record({
at: Date.now(),
principalId: before.createdBy,
@@ -643,7 +647,9 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
if (!v) return result;
const endpoint = await applyVersion(id, v, before.appliedVersion ?? before.currentVersion);
await markVersionRunning(id, v.version, endpoint);
- void deps.appPublished?.(before.createdBy, id, v.version).catch(() => {});
+ void deps
+ .appPublished?.(before.createdBy, id, v.version)
+ .catch(swallowAs("deploy: app published hook", undefined));
deps.auditLog.record({
at: Date.now(),
principalId: before.createdBy,
diff --git a/src/deploy/shared-deploy-provider.ts b/src/deploy/shared-deploy-provider.ts
index 64316a32c..d2f8b955f 100644
--- a/src/deploy/shared-deploy-provider.ts
+++ b/src/deploy/shared-deploy-provider.ts
@@ -2,7 +2,7 @@ import { LRUCache } from "lru-cache";
import type { ExecResult } from "../sandbox/sandbox.ts";
import { shq } from "../util/shell.ts";
import { errMessage, swallow } from "../util/errors.ts";
-import { redactSecrets } from "../harness/redact-secrets.ts";
+import { redactSecrets } from "../../plugins/chassis/src/redact-secrets.ts";
import { createSecretValueMasker } from "../security/secret-masking.ts";
import type { Deployment } from "./deploy-store.ts";
import { normalizeRelPath, readTree } from "./deploy-fs.ts";
diff --git a/src/deploy/viewer-session.ts b/src/deploy/viewer-session.ts
index 35cbff45e..953fae3dc 100644
--- a/src/deploy/viewer-session.ts
+++ b/src/deploy/viewer-session.ts
@@ -59,7 +59,7 @@ function readCookies(header: string | undefined, name: string): string[] {
try {
out.push(decodeURIComponent(p.slice(name.length + 1)));
} catch (error) {
- void error;
+ if (!(error instanceof URIError)) throw error;
}
}
return out;
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 184e1a5d3..76f2162b4 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -22,7 +22,7 @@ import { MemoryFactsMissing } from "../memory/facts.ts";
import { MemoryDisclosureDenied } from "../memory/disclosure.ts";
import { computerVerdict } from "../sandbox/sandbox.ts";
import { redactCommand } from "../sandbox/exec-process-session.ts";
-import { redactSecrets } from "./redact-secrets.ts";
+import { redactSecrets } from "../../plugins/chassis/src/redact-secrets.ts";
import { isObj } from "../util/objects.ts";
import { BOT_MODES } from "../surface-cache/channel-policy-store.ts";
import { WEBHOOK_SCHEMES } from "../webhooks/verifiers.ts";
diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.ts
index d6677c276..08ed1b76e 100644
--- a/src/harness/claude-harness.ts
+++ b/src/harness/claude-harness.ts
@@ -31,7 +31,7 @@ import {
} from "../model/pi-models.ts";
import { startSignalPoll, type RunSignalStore } from "../runs/run-signal-store.ts";
import type { ScopeId } from "../types.ts";
-import { swallow } from "../util/errors.ts";
+import { swallow, swallowAs } from "../util/errors.ts";
import { summarizeHistory } from "./history-summary.ts";
import { defineHarness, type Harness, type HarnessTurnInput, type HarnessTurnResult } from "./harness.ts";
import { buildDetectionPrompt, parseDetectVerdict, renderDetectPrompt } from "./pi-harness.ts";
@@ -497,7 +497,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
if (fromUser && reason) stopReason ??= reason;
interrupted = true;
queue.close();
- await sdkQuery.interrupt().catch(() => undefined);
+ await sdkQuery.interrupt().catch(swallowAs("claude harness: interrupt query", undefined));
controller.abort();
};
terminateProvider = () => {
diff --git a/src/loops/inbox-source-refresh.ts b/src/loops/inbox-source-refresh.ts
index 8210c9d01..eaeb5ef0a 100644
--- a/src/loops/inbox-source-refresh.ts
+++ b/src/loops/inbox-source-refresh.ts
@@ -2,7 +2,7 @@ import { LRUCache } from "lru-cache";
import { personalScope, type LoopItem } from "../types.ts";
import type { FeatureFlagStore } from "../feature-flags.ts";
import type { ErrorLog } from "../admin/error-log.ts";
-import { redactSecrets } from "../harness/redact-secrets.ts";
+import { redactSecrets } from "../../plugins/chassis/src/redact-secrets.ts";
import { errMessage } from "../util/errors.ts";
import type { LoopItemLedger } from "./item-ledger.ts";
import { isResolved } from "./ledger-view.ts";
diff --git a/src/loops/sources/slack.ts b/src/loops/sources/slack.ts
index 87e1f133c..6140bd08d 100644
--- a/src/loops/sources/slack.ts
+++ b/src/loops/sources/slack.ts
@@ -78,7 +78,10 @@ function itemReactions(item: LoopItem): string[] {
}
export function slackUserClientFactory(apiUrl?: string): (token: string) => SlackUserClient {
- const options = apiUrl ? { slackApiUrl: normalizeSlackApiUrl(apiUrl) } : {};
+ const options = {
+ attachOriginalToWebAPIRequestError: false,
+ ...(apiUrl ? { slackApiUrl: normalizeSlackApiUrl(apiUrl) } : {}),
+ };
return (token) => new WebClient(token, options);
}
diff --git a/src/skills/pack-fetcher.ts b/src/skills/pack-fetcher.ts
index 20133c3f7..a184c633e 100644
--- a/src/skills/pack-fetcher.ts
+++ b/src/skills/pack-fetcher.ts
@@ -6,7 +6,7 @@ import { join, relative, sep } from "node:path";
import { lookup as dnsLookup } from "node:dns/promises";
import { isIP } from "node:net";
import { credentialRequestHeaders, type CredentialInjection } from "../credentials/keychain.ts";
-import { errMessage } from "../util/errors.ts";
+import { errMessage, swallowAs } from "../util/errors.ts";
import { isPrivateNetworkIp } from "../util/network.ts";
import { isProbablyBinary } from "./seed.ts";
import type { FetchedRepo, RepoFile } from "./ingest.ts";
@@ -263,7 +263,7 @@ export function createGitFetcher(opts: GitFetcherOptions = {}): SkillPackFetcher
const files = await readTree(repoDir);
return { commit, files };
} finally {
- await rm(work, { recursive: true, force: true }).catch(() => {});
+ await rm(work, { recursive: true, force: true }).catch(swallowAs("skill pack: remove temp clone", undefined));
}
},
@@ -285,7 +285,7 @@ export function createGitFetcher(opts: GitFetcherOptions = {}): SkillPackFetcher
if (!SHA_RE.test(sha)) throw new Error(`could not resolve ref "${target}" for skill pack`);
return sha;
} finally {
- await rm(work, { recursive: true, force: true }).catch(() => {});
+ await rm(work, { recursive: true, force: true }).catch(swallowAs("skill pack: remove temp clone", undefined));
}
},
};
diff --git a/src/slack/deferred-ack.ts b/src/slack/deferred-ack.ts
index 6f35dc53e..945ebb689 100644
--- a/src/slack/deferred-ack.ts
+++ b/src/slack/deferred-ack.ts
@@ -130,7 +130,10 @@ export function createDeferredAckReceiver(opts: DeferredAckReceiverOptions): Rec
const client = new SocketModeClient({
appToken: opts.appToken,
logLevel: parseLogLevel(opts.logLevel),
- ...(opts.slackApiUrl ? { clientOptions: { slackApiUrl: opts.slackApiUrl } } : {}),
+ clientOptions: {
+ attachOriginalToWebAPIRequestError: false,
+ ...(opts.slackApiUrl ? { slackApiUrl: opts.slackApiUrl } : {}),
+ },
});
let app: BoltApp | undefined;
diff --git a/src/slack/events.ts b/src/slack/events.ts
index 494beb954..972d7b01c 100644
--- a/src/slack/events.ts
+++ b/src/slack/events.ts
@@ -364,7 +364,10 @@ export function registerSlackEvents(
const e = parseLifecycleEvent(event);
if (deduper.seen(dedupeKey({ event_id: parseEventId(body), channel: e.channel, ts: e.eventTs }))) return;
if (e.user === ids.botUserId) {
- if (e.channel && deps.backfillHistory) await deps.backfillHistory(client, e.channel).catch(() => {});
+ if (e.channel && deps.backfillHistory)
+ await deps
+ .backfillHistory(client, e.channel)
+ .catch(swallowAs("slack: backfill history on bot join", undefined));
if (allowActor) {
await forceDirectorySync(client);
return;
diff --git a/src/slack/index.ts b/src/slack/index.ts
index 7d1d2fa88..6be638304 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -73,7 +73,11 @@ export async function startSlackPlugin(
const APP_TOKEN = cfg.appToken;
const SLACK_API_URL = cfg.apiUrl ? normalizeSlackApiUrl(cfg.apiUrl) : undefined;
const TRUSTED_FILE_HOST = SLACK_API_URL ? new URL(SLACK_API_URL).hostname : undefined;
- const CLIENT_OPTIONS = { ...NO_RETRY, ...(SLACK_API_URL ? { slackApiUrl: SLACK_API_URL } : {}) } as const;
+ const CLIENT_OPTIONS = {
+ ...NO_RETRY,
+ attachOriginalToWebAPIRequestError: false,
+ ...(SLACK_API_URL ? { slackApiUrl: SLACK_API_URL } : {}),
+ } as const;
const IDENTITY_TOKENS: Record<string, string | undefined> = {
copilot: cfg.copilotBotToken,
};
@@ -394,7 +398,8 @@ export async function startSlackPlugin(
try {
const actor = await directory.classifyActor(client, msg.senderSlackId);
if (actor.externalId.includes("@")) senderEmail = actor.externalId;
- } catch {
+ } catch (e) {
+ swallow("slack: classify inbox message sender", e);
senderEmail = undefined;
}
}
@@ -406,7 +411,7 @@ export async function startSlackPlugin(
...(msg.text ? { text: msg.text } : {}),
...(senderEmail ? { senderEmail } : {}),
});
- })().catch(() => {});
+ })().catch((e) => swallow("slack: forward message to inbox", e));
};
registerSlackEvents(app, {
handler,
diff --git a/src/slack/presenters.ts b/src/slack/presenters.ts
index 591095140..cf5c5177e 100644
--- a/src/slack/presenters.ts
+++ b/src/slack/presenters.ts
@@ -1,3 +1,5 @@
+import { swallow } from "../util/errors.ts";
+
export const DEFAULT_ACK_REACTIONS = ["eyes", "mag", "hourglass_flowing_sand", "telescope", "saluting_face"] as const;
export const CURATED_ACK_EMOJI = [
@@ -83,7 +85,7 @@ export function createAckPresenter(deps: {
const randomEmoji = (): string =>
candidates[Math.min(candidates.length - 1, Math.floor(random() * candidates.length))]!;
let pickResult: string | undefined;
- void deps.emojiPick?.then((v) => (pickResult = v)).catch(() => undefined);
+ void deps.emojiPick?.then((v) => (pickResult = v)).catch((e) => swallow("slack: pick ack emoji", e));
let emoji = "";
let reactionApplied = false;
let reactionCancelled = false;
@@ -92,7 +94,7 @@ export function createAckPresenter(deps: {
let sawFirstBlock = false;
let chain: Promise<void> = Promise.resolve();
const enqueue = (op: () => Promise<void>): void => {
- chain = chain.then(op).catch(() => {});
+ chain = chain.then(op).catch((e) => swallow("slack: ack presenter step", e));
};
const timer = setTimeout(() => {
if (deps.taskManaged || settled || ackPosted || reactionCancelled) return;
diff --git a/src/slack/task-ack.ts b/src/slack/task-ack.ts
index 9eba58744..ced783a9d 100644
--- a/src/slack/task-ack.ts
+++ b/src/slack/task-ack.ts
@@ -51,7 +51,10 @@ export function createTaskAcknowledgements(
if (!state) {
if (next?.existing) return true;
const emoji = next?.pick
- ? await Promise.race([next.pick().catch(() => undefined), sleep(1500).then(() => undefined)])
+ ? await Promise.race([
+ next.pick().catch(swallowAs("slack: pick task ack emoji", undefined)),
+ sleep(1500).then(() => undefined),
+ ])
: undefined;
if (leaseLost) return false;
await store.putIfAbsent(runId, {
diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.ts
index ee5cabc7f..9273dc181 100644
--- a/src/slack/turn-handler.ts
+++ b/src/slack/turn-handler.ts
@@ -394,7 +394,9 @@ export function createTurnHandler(deps: {
try {
await core.reportRunEditRef(queuedRunId, ts);
} catch (error) {
- await client.chat.delete({ channel: inc.channel, ts }).catch(() => {});
+ await client.chat
+ .delete({ channel: inc.channel, ts })
+ .catch(swallowAs("slack: delete status message after edit-ref failure", undefined));
throw error;
}
}
diff --git a/src/surfaces/slack-managed.ts b/src/surfaces/slack-managed.ts
index f2d1a3f1d..d23fc79a9 100644
--- a/src/surfaces/slack-managed.ts
+++ b/src/surfaces/slack-managed.ts
@@ -11,6 +11,7 @@ import {
} from "../slack/deferred-ack.ts";
import { sendJson } from "../api/http.ts";
import { isBearerSecret } from "../auth/source-auth.ts";
+import { swallow, swallowAs } from "../util/errors.ts";
export function createManagedSlack(opts: {
serviceUrl: string;
@@ -91,7 +92,7 @@ export function createManagedSlack(opts: {
if ((req.url ?? "").split("?")[0] === "/v1/slack/managed/installation") {
if (req.method === "DELETE") {
await opts.store.disableManaged(input.installId);
- void opts.reconcile?.().catch(() => undefined);
+ void opts.reconcile?.().catch(swallowAs("slack-managed: reconcile installation", undefined));
return sendJson(res, 200, { ok: true });
}
if (
@@ -118,7 +119,7 @@ export function createManagedSlack(opts: {
...(typeof input.teamName === "string" ? { teamName: input.teamName } : {}),
});
if (!accepted) return sendJson(res, 409, { error: "installation_conflict" });
- void opts.reconcile?.().catch(() => undefined);
+ void opts.reconcile?.().catch(swallowAs("slack-managed: reconcile installation", undefined));
const ready = active?.installId === input.installId;
return sendJson(res, ready ? 200 : 202, { ok: true, ready });
}
@@ -158,7 +159,10 @@ export function createManagedSlack(opts: {
})
.then(
() => gate.persisted(),
- () => gate.failed("delivery failed"),
+ (e: unknown) => {
+ swallow("slack-managed: process event", e);
+ gate.failed("delivery failed");
+ },
);
});
},
diff --git a/src/triggers/edit-notice.ts b/src/triggers/edit-notice.ts
index e6df11302..6c5ba26e7 100644
--- a/src/triggers/edit-notice.ts
+++ b/src/triggers/edit-notice.ts
@@ -103,7 +103,7 @@ export async function notifyOwnerOfCronEdit(
const [kind, scopeRef] = String(cron.ownerScopeId).split(":", 2) as [string, string | undefined];
const place =
kind === "channel" && scopeRef && sink.channelName
- ? await sink.channelName(scopeRef).catch(() => undefined)
+ ? await sink.channelName(scopeRef).catch(reportFailureAs("cron edit notice: channel name lookup", undefined))
: undefined;
await sink.enqueueDelivery({
destination: principalDestination(cron.owner, args.editorId),
diff --git a/src/wiring.ts b/src/wiring.ts
index 0178da3d8..0baeba3a3 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -2385,7 +2385,10 @@ export function buildApp(
const inboxRealtime = createInboxRealtime({
loops: loopStore,
items: loopItems,
- requestFire: (loopId) => void loopFire.fire(loopId, `loop:${loopId}:slack-event:${Date.now()}`).catch(() => {}),
+ requestFire: (loopId) =>
+ void loopFire
+ .fire(loopId, `loop:${loopId}:slack-event:${Date.now()}`)
+ .catch(swallowAs("inbox loop: slack event fire", undefined)),
});
const keychainApprovals = keychain
? createKeychainApprovals({
diff --git a/superserve/templates/qm-agent.ts b/superserve/templates/qm-agent.ts
index 498792439..f91f5f6a6 100644
--- a/superserve/templates/qm-agent.ts
+++ b/superserve/templates/qm-agent.ts
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
import { join } from "node:path";
import { parseArgs } from "node:util";
import { BuildError, Template, type BuildStep, type TemplateInfo } from "@superserve/sdk";
+import { swallowAs } from "../../src/util/errors.ts";
import {
REPO_ROOT,
requireRelease,
@@ -228,7 +229,10 @@ async function main(): Promise<void> {
if (args.wait) console.log(`[qm-agent] ready: ${describe(await waitForBuild(existing))}`);
return;
}
- if (existing.latestBuildId) await existing.cancelBuild(existing.latestBuildId).catch(() => undefined);
+ if (existing.latestBuildId)
+ await existing
+ .cancelBuild(existing.latestBuildId)
+ .catch(swallowAs("qm-agent: cancel in-flight build", undefined));
}
console.log(`[qm-agent] deleting existing template (${existing.status}${args.force ? ", --force" : ""})`);
await existing.delete();
diff --git a/test/errors.test.ts b/test/errors.test.ts
index a9b401fe0..616d18a41 100644
--- a/test/errors.test.ts
+++ b/test/errors.test.ts
@@ -206,3 +206,23 @@ test("field enumeration failures preserve the message and stack", () => {
});
assert.equal(errDetail(hostile), errDetail(error));
});
+
+test("error fields redact credentials in nested keys, raw request headers and urls", () => {
+ const error = Object.assign(new Error("A request error occurred: connect ECONNREFUSED"), {
+ code: "slack_webapi_request_error",
+ token: "xoxb-top-level",
+ original: {
+ config: {
+ url: "https://slack.test/api/chat.delete?token=xoxb-in-url",
+ headers: { Authorization: "Bearer xoxb-nested", "x-api-key": "k-header", Accept: "application/json" },
+ },
+ request: { _header: "POST /api/chat.delete HTTP/1.1\r\nAuthorization: Bearer xoxb-raw\r\n\r\n" },
+ credentials: { accessKeyId: "AKIAEXAMPLE", secretAccessKey: "s3cr3t", sessionToken: "sess" },
+ },
+ });
+ const detail = errDetail(error);
+ for (const secret of ["xoxb", "k-header", "s3cr3t", 'sess"']) assert.ok(!detail.includes(secret), secret);
+ assert.match(detail, /code=slack_webapi_request_error/);
+ assert.match(detail, /"Accept":"application\/json"/);
+ assert.match(detail, /connect ECONNREFUSED/);
+});
diff --git a/test/live-slack/scenarios-sandbox-providers.ts b/test/live-slack/scenarios-sandbox-providers.ts
index 29360774f..3fec922c9 100644
--- a/test/live-slack/scenarios-sandbox-providers.ts
+++ b/test/live-slack/scenarios-sandbox-providers.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import type { SandboxBackendName } from "../../src/sandbox/sandbox-routing.ts";
-import { redactSecrets } from "../../src/harness/redact-secrets.ts";
+import { redactSecrets } from "../../plugins/chassis/src/redact-secrets.ts";
import { isObj } from "../../src/util/objects.ts";
import { headSlice, tailSlice } from "../../src/util/text.ts";
import type { Scenario } from "./harness.ts";
diff --git a/test/web-ui-delivery-poll.test.ts b/test/web-ui-delivery-poll.test.ts
new file mode 100644
index 000000000..913d72fdf
--- /dev/null
+++ b/test/web-ui-delivery-poll.test.ts
@@ -0,0 +1,57 @@
+import { test, after } from "node:test";
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+
+let deliveriesStatus = 503;
+const acked: string[] = [];
+const core = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://core");
+ if (req.method === "GET" && url.pathname === "/v1/deliveries" && url.searchParams.get("type") === "web") {
+ res.writeHead(deliveriesStatus, { "content-type": "application/json" });
+ res.end(
+ deliveriesStatus === 200
+ ? JSON.stringify({ deliveries: [{ id: "d1", createdAt: 0, destination: { target: "web:nobody:t1" } }] })
+ : JSON.stringify({ error: "unavailable" }),
+ );
+ return;
+ }
+ if (req.method === "POST" && url.pathname.startsWith("/v1/deliveries/")) {
+ acked.push(url.pathname);
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ok: true }));
+ return;
+ }
+ res.writeHead(404);
+ res.end();
+});
+core.listen(0);
+process.env.CORE_API_URL = `http://localhost:${(core.address() as AddressInfo).port}`;
+process.env.CORE_SIGNING_SECRET = "core-signing-secret".repeat(3);
+process.env.WEB_UI_PRINCIPALS = "";
+const { drainWebDeliveries } = await import("../plugins/web-ui/server/index.ts");
+
+after(() => new Promise<void>((r) => core.close(() => r())));
+
+test("web delivery poll warns once per outage and logs recovery", async (t) => {
+ const lines: string[] = [];
+ const record = (...args: unknown[]) => void lines.push(String(args[0]));
+ t.mock.method(console, "warn", record);
+ t.mock.method(console, "log", record);
+ const pollLines = () => lines.filter((line) => line.includes("web delivery poll"));
+
+ for (let i = 0; i < 3; i++) await drainWebDeliveries();
+ assert.equal(pollLines().length, 1);
+ assert.match(pollLines()[0]!, /^\[swallowed\] web-ui: web delivery poll.*http 503/);
+
+ deliveriesStatus = 200;
+ await drainWebDeliveries();
+ await drainWebDeliveries();
+ assert.deepEqual(pollLines().slice(1), ["[web-ui] web delivery poll recovered"]);
+ assert.deepEqual(acked, ["/v1/deliveries/d1/ack", "/v1/deliveries/d1/ack"]);
+
+ deliveriesStatus = 500;
+ await drainWebDeliveries();
+ assert.equal(pollLines().length, 3);
+ assert.match(pollLines()[2]!, /http 500/);
+});