@agent-native/dispatch 0.40.16-nightly-20261007154213 → 0.40.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -14
- package/dist/actions/provider-api-register.d.ts +4 -4
- package/dist/server/lib/thread-debug-store.d.ts +1 -0
- package/dist/server/lib/thread-debug-store.d.ts.map +1 -1
- package/dist/server/lib/thread-debug-store.js +13 -1
- package/dist/server/lib/thread-debug-store.js.map +1 -1
- package/package.json +4 -4
- package/src/server/lib/thread-debug-store.spec.ts +32 -1
- package/src/server/lib/thread-debug-store.ts +14 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
# @agent-native/dispatch
|
|
2
2
|
|
|
3
|
-
## 0.40.16
|
|
3
|
+
## 0.40.16
|
|
4
4
|
|
|
5
5
|
### Patch Changes
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
- Updated dependencies [
|
|
10
|
-
- Updated dependencies
|
|
11
|
-
- Updated dependencies [
|
|
12
|
-
- @agent-native/
|
|
13
|
-
- @agent-native/toolkit@0.203.1-nightly-20261007154213
|
|
7
|
+
- Release all public npm packages with a patch version bump.
|
|
8
|
+
- 69d237c: Thread Debug lets owners and admins of the observability super organization (`AGENT_NATIVE_OBSERVABILITY_SUPER_ORG_ID`) inspect threads from every user and organization, including cross-app sources whose users are not in the Dispatch organization.
|
|
9
|
+
- Updated dependencies [b717c70]
|
|
10
|
+
- Updated dependencies
|
|
11
|
+
- Updated dependencies [2842af8]
|
|
12
|
+
- @agent-native/toolkit@0.203.1
|
|
14
13
|
|
|
15
14
|
## 0.40.15
|
|
16
15
|
|
|
@@ -1169,10 +1168,4 @@
|
|
|
1169
1168
|
|
|
1170
1169
|
- 904b67c: Retry workspace embed-session minting with the shared A2A secret when a target rejects org-secret authentication, with redacted mint diagnostics. Keep SSO fanout limited to canonical and explicitly registered own-origin apps; path-mounted workspace apps remain same-origin with Dispatch and keep their existing ambient session behavior, so this narrows fanout targets but is not origin isolation.
|
|
1171
1170
|
|
|
1172
|
-
## 0.27.9
|
|
1173
|
-
|
|
1174
|
-
### Patch Changes
|
|
1175
|
-
|
|
1176
|
-
- d525c66: Harden embedded workspace authentication across hosts and prevent unauthorized session-location reads.
|
|
1177
|
-
|
|
1178
1171
|
For the full list of releases, see the [changelog archive](./changelog/archive/CHANGELOG.md).
|
|
@@ -66,39 +66,39 @@ declare const _default: import("node_modules/@agent-native/core/dist").ActionDef
|
|
|
66
66
|
label?: undefined;
|
|
67
67
|
} | {
|
|
68
68
|
id?: undefined;
|
|
69
|
-
count?: undefined;
|
|
70
69
|
message?: undefined;
|
|
71
70
|
deleted?: undefined;
|
|
72
71
|
providers?: undefined;
|
|
72
|
+
count?: undefined;
|
|
73
73
|
found: boolean;
|
|
74
74
|
provider: import("node_modules/@agent-native/core/dist/provider-api").CustomProviderConfig;
|
|
75
75
|
registered?: undefined;
|
|
76
76
|
label?: undefined;
|
|
77
77
|
} | {
|
|
78
|
-
count?: undefined;
|
|
79
78
|
message?: undefined;
|
|
80
79
|
deleted?: undefined;
|
|
81
80
|
providers?: undefined;
|
|
81
|
+
count?: undefined;
|
|
82
82
|
provider?: undefined;
|
|
83
83
|
found: boolean;
|
|
84
84
|
id: string;
|
|
85
85
|
registered?: undefined;
|
|
86
86
|
label?: undefined;
|
|
87
87
|
} | {
|
|
88
|
-
count?: undefined;
|
|
89
88
|
message?: undefined;
|
|
90
89
|
found?: undefined;
|
|
91
90
|
providers?: undefined;
|
|
91
|
+
count?: undefined;
|
|
92
92
|
provider?: undefined;
|
|
93
93
|
deleted: boolean;
|
|
94
94
|
id: string;
|
|
95
95
|
registered?: undefined;
|
|
96
96
|
label?: undefined;
|
|
97
97
|
} | {
|
|
98
|
-
count?: undefined;
|
|
99
98
|
deleted?: undefined;
|
|
100
99
|
found?: undefined;
|
|
101
100
|
providers?: undefined;
|
|
101
|
+
count?: undefined;
|
|
102
102
|
provider?: undefined;
|
|
103
103
|
registered: boolean;
|
|
104
104
|
id: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-debug-store.d.ts","sourceRoot":"","sources":["../../../src/server/lib/thread-debug-store.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"thread-debug-store.d.ts","sourceRoot":"","sources":["../../../src/server/lib/thread-debug-store.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,kBAAkB,EACxB,MAAM,iCAAiC,CAAC;AAwBzC,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,SAAS,GAAG,KAAK,GAAG,YAAY,CAAC;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;IACnB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,aAAa,EAAE,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,WAAW;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;IAClB,QAAQ,EAAE,OAAO,CAAC;IAClB,aAAa,EAAE,OAAO,CAAC;IACvB,YAAY,EAAE,MAAM,EAAE,CAAC;CACxB;AA0CD,QAAA,MAAM,yBAAyB,YAAI,SAAS,EAAE,SAAS,EAAE,WAAW,CAAU,CAAC;AAE/E,MAAM,MAAM,qBAAqB,GAAG,CAAC,OAAO,yBAAyB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/E,KAAK,6BAA6B,GAC9B,IAAI,GACJ,cAAc,GACd,aAAa,GACb,aAAa,CAAC;AAsflB,wBAAsB,sBAAsB,IAAI,OAAO,CAAC;IACtD,MAAM,EAAE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AI;QACJ,cAAc;;;QAGd,WAAW;QACX,KAAK;QACL,aAAa;;;QAGb,EAAE;QACF,UAAU;QACV,KAAK;QACL,OAAO;QACP,YAAY;QACZ,SAAS;QACT,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAiBT,SAAS;QACT,KAAK;;;;;;GAOV"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { fail } from "@agent-native/core/action";
|
|
2
2
|
import { classifyAgentFailure, } from "@agent-native/core/agent/engine";
|
|
3
3
|
import { createDbExec, getDbExec } from "@agent-native/core/db";
|
|
4
|
+
import { getAppConfig } from "@agent-native/core/server";
|
|
4
5
|
import { ForbiddenError } from "@agent-native/core/sharing";
|
|
5
6
|
import { isDispatchEnvironmentAdmin } from "./admin-config.js";
|
|
6
7
|
import { currentOrgId, currentOwnerEmail } from "./dispatch-store.js";
|
|
@@ -320,7 +321,12 @@ async function resolveDebugAccess() {
|
|
|
320
321
|
const orgId = currentOrgId();
|
|
321
322
|
const role = await viewerOrgRole(orgId, viewerEmail);
|
|
322
323
|
const envAdmin = isDispatchEnvironmentAdmin(viewerEmail);
|
|
323
|
-
const
|
|
324
|
+
const orgAdmin = role === "owner" || role === "admin";
|
|
325
|
+
const canInspectAll = envAdmin || orgAdmin;
|
|
326
|
+
// Remote sources keep their own org rosters, so Dispatch membership cannot
|
|
327
|
+
// scope them; the observability super org is the one cross-org review grant.
|
|
328
|
+
const superOrgId = getAppConfig().observability.superOrgId;
|
|
329
|
+
const superOrg = Boolean(orgId && orgAdmin && superOrgId === orgId);
|
|
324
330
|
const memberEmails = canInspectAll
|
|
325
331
|
? await currentOrgMembers(orgId)
|
|
326
332
|
: [viewerEmail];
|
|
@@ -329,6 +335,7 @@ async function resolveDebugAccess() {
|
|
|
329
335
|
orgId,
|
|
330
336
|
role,
|
|
331
337
|
envAdmin,
|
|
338
|
+
superOrg,
|
|
332
339
|
canInspectAll,
|
|
333
340
|
memberEmails: memberEmails.length > 0 ? memberEmails : [viewerEmail],
|
|
334
341
|
};
|
|
@@ -351,6 +358,7 @@ function ownerScope(access, ownerEmail, column = "owner_email") {
|
|
|
351
358
|
}
|
|
352
359
|
if (requested && requested !== "*") {
|
|
353
360
|
if (access.orgId &&
|
|
361
|
+
!access.superOrg &&
|
|
354
362
|
!access.memberEmails.some((email) => email.toLowerCase() === requested.toLowerCase())) {
|
|
355
363
|
fail("The requested owner is not a member of the current organization.", {
|
|
356
364
|
errorCode: "forbidden",
|
|
@@ -363,6 +371,9 @@ function ownerScope(access, ownerEmail, column = "owner_email") {
|
|
|
363
371
|
label: requested,
|
|
364
372
|
};
|
|
365
373
|
}
|
|
374
|
+
if (access.superOrg) {
|
|
375
|
+
return { sql: "1 = 1", args: [], label: "all organizations" };
|
|
376
|
+
}
|
|
366
377
|
if (access.envAdmin && !access.orgId) {
|
|
367
378
|
return { sql: "1 = 1", args: [], label: "all users" };
|
|
368
379
|
}
|
|
@@ -439,6 +450,7 @@ export async function listThreadDebugSources() {
|
|
|
439
450
|
orgId: access.orgId,
|
|
440
451
|
role: access.role,
|
|
441
452
|
envAdmin: access.envAdmin,
|
|
453
|
+
superOrg: access.superOrg,
|
|
442
454
|
canInspectAll: access.canInspectAll,
|
|
443
455
|
memberCount: access.memberEmails.length,
|
|
444
456
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-debug-store.js","sourceRoot":"","sources":["../../../src/server/lib/thread-debug-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,2BAA2B,CAAC;AACjD,OAAO,EACL,oBAAoB,GAErB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAe,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAE5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAA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,CAAC,OAAO,IAAI,EAAE,CAAC;YAClC,YAAY,EAAE,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC;YAC5C,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC;YACtC,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC;SACvC;QACD,MAAM,EAAE;YACN,WAAW;YACX,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;YACxB,KAAK,EAAE,aAAa;SACrB;QACD,QAAQ,EAAE,iBAAiB,CAAC,UAAU,CAAC;QACvC,KAAK,EAAG,UAAkB,EAAE,MAAM,IAAI,IAAI;QAC1C,SAAS,EAAE,KAAK,CAAC,OAAO,CAAE,UAAkB,EAAE,UAAU,CAAC;YACvD,CAAC,CAAE,UAAkB,CAAC,UAAU;YAChC,CAAC,CAAC,EAAE;QACN,cAAc,EAAG,UAAkB,EAAE,cAAc,IAAI,EAAE;QACzD,UAAU;QACV,aAAa,EAAE,GAAG,CAAC,WAAW,IAAI,EAAE;QACpC,IAAI;QACJ,MAAM,EAAE;YACN,SAAS,EAAE,gBAAgB;YAC3B,KAAK,EAAE,aAAa;SACrB;QACD,QAAQ,EAAE,YAAY;QACtB,YAAY,EAAE,gBAAgB;QAC9B,KAAK,EAAE,QAAQ;QACf,WAAW,EAAE,cAAc;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["import { fail } from \"@agent-native/core/action\";\nimport {\n classifyAgentFailure,\n type AgentFailureRegime,\n} from \"@agent-native/core/agent/engine\";\nimport { createDbExec, getDbExec, type DbExec } from \"@agent-native/core/db\";\nimport { ForbiddenError } from \"@agent-native/core/sharing\";\n\nimport { isDispatchEnvironmentAdmin } from \"./admin-config.js\";\nimport { currentOrgId, currentOwnerEmail } from \"./dispatch-store.js\";\n\nconst CONFIG_ENV_KEY = \"AGENT_NATIVE_THREAD_DEBUG_DATABASES\";\nconst MAX_RAW_PREVIEW_CHARS = 1_500;\nconst DEFAULT_SEARCH_LIMIT = 25;\nconst MAX_SEARCH_LIMIT = 100;\nconst DEFAULT_RUN_LIMIT = 20;\nconst DEFAULT_EVENT_LIMIT = 600;\nconst DEFAULT_TRACE_SPAN_LIMIT = 500;\n\ninterface ThreadDebugSourceConfig {\n id: string;\n label: string;\n kind: \"current\" | \"env\" | \"configured\";\n databaseUrl?: string;\n databaseUrlEnv?: string | null;\n}\n\nexport interface ThreadDebugSource {\n id: string;\n label: string;\n kind: \"current\" | \"env\" | \"configured\";\n current: boolean;\n connected: boolean;\n databaseUrlEnv: string | null;\n canInspectAll: boolean;\n}\n\nexport interface DebugAccess {\n viewerEmail: string;\n orgId: string | null;\n role: string | null;\n envAdmin: boolean;\n canInspectAll: boolean;\n memberEmails: string[];\n}\n\ninterface OwnerScope {\n sql: string;\n args: unknown[];\n label: string;\n}\n\ninterface ChatThreadRow {\n id: string;\n owner_email: string;\n title: string | null;\n preview: string | null;\n thread_data: string | null;\n message_count: number | string | null;\n created_at: number | string;\n updated_at: number | string;\n}\n\ninterface AgentRunRow {\n id: string;\n thread_id: string;\n status: string;\n abort_reason?: string | null;\n started_at: number | string;\n completed_at?: number | string | null;\n heartbeat_at?: number | string | null;\n turn_id?: string | null;\n last_progress_at?: number | string | null;\n error_code?: string | null;\n error_detail?: string | null;\n terminal_reason?: string | null;\n dispatch_mode?: string | null;\n worker_stage?: string | null;\n diag_stage?: string | null;\n peak_rss_mb?: number | string | null;\n in_flight_since?: number | string | null;\n dispatch_payload?: string | null;\n}\n\nconst execCache = new Map<string, Promise<DbExec>>();\n\nconst UNSUCCESSFUL_RUN_STATUSES = [\"errored\", \"aborted\", \"truncated\"] as const;\n\nexport type AgentRunFailureStatus = (typeof UNSUCCESSFUL_RUN_STATUSES)[number];\n\ntype ThreadDebugSourceHealthStatus =\n | \"ok\"\n | \"disconnected\"\n | \"unsupported\"\n | \"unavailable\";\n\ninterface AgentRunFailureRow extends AgentRunRow {\n debug_owner_email: string;\n debug_thread_title?: string | null;\n debug_thread_preview?: string | null;\n debug_terminal_event_data?: string | null;\n}\n\nclass UnsupportedThreadDebugSchemaError extends Error {\n readonly code = \"thread_debug_schema_unsupported\";\n\n constructor(readonly table: string) {\n super(`This database does not have the required \"${table}\" table.`);\n this.name = \"UnsupportedThreadDebugSchemaError\";\n }\n}\n\nfunction escapeLike(value: string): string {\n return value.replace(/([\\\\%_])/g, \"\\\\$1\");\n}\n\nfunction missingTableName(error: unknown): string | null {\n const message = String((error as Error)?.message ?? error);\n const patterns = [\n /relation\\s+[\"'`](?:(?:public)\\.)?([a-zA-Z_][\\w$]*)[\"'`]\\s+does not exist/i,\n /table\\s+[\"'`](?:[^\"'`.]+\\.)?([a-zA-Z_][\\w$]*)[\"'`]\\s+does(?:n't| not)\\s+exist/i,\n ];\n for (const pattern of patterns) {\n const match = message.match(pattern);\n if (match?.[1]) return match[1].toLowerCase();\n }\n return null;\n}\n\nfunction isMissingTableError(error: unknown): boolean {\n return missingTableName(error) !== null;\n}\n\nasync function optionalRows<T = Record<string, unknown>>(\n exec: DbExec,\n sql: string,\n args: unknown[] = [],\n): Promise<T[]> {\n try {\n return (await exec.execute({ sql, args })).rows as T[];\n } catch (error) {\n if (isMissingTableError(error)) return [];\n throw error;\n }\n}\n\nasync function queryRows<T = Record<string, unknown>>(\n exec: DbExec,\n sql: string,\n args: unknown[] = [],\n): Promise<T[]> {\n try {\n return (await exec.execute({ sql, args })).rows as T[];\n } catch (error) {\n const missingTable = missingTableName(error);\n if (missingTable) {\n throw new UnsupportedThreadDebugSchemaError(missingTable);\n }\n throw error;\n }\n}\n\nfunction numberField(value: unknown): number {\n const parsed = Number(value ?? 0);\n return Number.isFinite(parsed) ? parsed : 0;\n}\n\nfunction nullableNumberField(value: unknown): number | null {\n if (value == null) return null;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction safeJsonParse<T>(value: unknown, fallback: T): T {\n if (value == null || value === \"\") return fallback;\n try {\n return JSON.parse(\n typeof value === \"string\" ? value : JSON.stringify(value),\n ) as T;\n } catch {\n return fallback;\n }\n}\n\nfunction safeJsonStringify(value: unknown): string {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n}\n\nfunction textFromContent(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((part: any) => {\n if (part?.type === \"text\" && typeof part.text === \"string\") {\n return part.text;\n }\n if (part?.type === \"tool-call\") {\n const name = part.toolName ?? part.name ?? \"tool\";\n return `[tool:${name}] ${safeJsonStringify(part.args ?? part.input ?? {})}`;\n }\n if (part?.type === \"tool-result\") {\n return `[tool-result:${part.toolName ?? part.toolCallId ?? \"tool\"}] ${\n typeof part.content === \"string\"\n ? part.content\n : safeJsonStringify(part.content)\n }`;\n }\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction normalizeMessages(threadData: any) {\n const messages = Array.isArray(threadData?.messages)\n ? threadData.messages\n : [];\n return messages.map((entry: any, index: number) => {\n const message = entry?.message ?? entry;\n const content = message?.content;\n const contentParts = Array.isArray(content) ? content : [];\n return {\n index,\n id: typeof message?.id === \"string\" ? message.id : null,\n role: typeof message?.role === \"string\" ? message.role : \"unknown\",\n createdAt: message?.createdAt ?? null,\n status: message?.status ?? null,\n text: textFromContent(content),\n contentParts,\n attachments: Array.isArray(message?.attachments)\n ? message.attachments\n : [],\n metadata: message?.metadata ?? null,\n parentId: entry?.parentId ?? null,\n };\n });\n}\n\nfunction snippetFor(row: ChatThreadRow, query: string): string {\n const raw = `${row.title ?? \"\"}\\n${row.preview ?? \"\"}\\n${row.thread_data ?? \"\"}`;\n const compact = raw.replace(/\\s+/g, \" \").trim();\n if (!query.trim()) {\n return compact.slice(0, MAX_RAW_PREVIEW_CHARS);\n }\n const lower = compact.toLowerCase();\n const needle = query.trim().toLowerCase();\n const match = lower.indexOf(needle);\n if (match === -1) return compact.slice(0, MAX_RAW_PREVIEW_CHARS);\n const start = Math.max(0, match - 160);\n const end = Math.min(compact.length, match + needle.length + 320);\n const prefix = start > 0 ? \"...\" : \"\";\n const suffix = end < compact.length ? \"...\" : \"\";\n return `${prefix}${compact.slice(start, end)}${suffix}`;\n}\n\nfunction envPrefixForSourceId(sourceId: string): string {\n return sourceId.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\");\n}\n\nfunction sourceIdFromEnvPrefix(prefix: string): string {\n return prefix.toLowerCase().replace(/_/g, \"-\");\n}\n\nfunction labelFromSourceId(sourceId: string): string {\n return sourceId\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction currentDatabaseUrlEnv(): string | null {\n const appName = process.env.APP_NAME?.toUpperCase().replace(/-/g, \"_\");\n if (appName && process.env[`${appName}_DATABASE_URL`]) {\n return `${appName}_DATABASE_URL`;\n }\n return process.env.DATABASE_URL ? \"DATABASE_URL\" : null;\n}\n\nfunction parseConfiguredSources(): ThreadDebugSourceConfig[] {\n const raw = process.env[CONFIG_ENV_KEY];\n if (!raw) return [];\n const parsed = safeJsonParse<any>(raw, null);\n const entries = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\"\n ? Object.entries(parsed).map(([id, value]) => ({ id, ...(value as any) }))\n : [];\n\n return entries\n .map((entry: any): ThreadDebugSourceConfig | null => {\n const id = typeof entry?.id === \"string\" ? entry.id.trim() : \"\";\n if (!id) return null;\n const databaseUrlEnv =\n typeof entry.databaseUrlEnv === \"string\"\n ? entry.databaseUrlEnv.trim()\n : null;\n const databaseUrl =\n typeof entry.databaseUrl === \"string\" && entry.databaseUrl.trim()\n ? entry.databaseUrl.trim()\n : databaseUrlEnv\n ? process.env[databaseUrlEnv]\n : undefined;\n return {\n id,\n label:\n typeof entry.label === \"string\" && entry.label.trim()\n ? entry.label.trim()\n : labelFromSourceId(id),\n kind: \"configured\",\n databaseUrl,\n databaseUrlEnv,\n };\n })\n .filter((source): source is ThreadDebugSourceConfig => Boolean(source));\n}\n\nfunction discoverEnvSources(): ThreadDebugSourceConfig[] {\n const ignored = new Set([\n \"DATABASE_URL\",\n \"NETLIFY_DATABASE_URL\",\n \"NETLIFY_DATABASE_URL_UNPOOLED\",\n ]);\n const currentAppPrefix = process.env.APP_NAME?.toUpperCase().replace(\n /-/g,\n \"_\",\n );\n const sources: ThreadDebugSourceConfig[] = [];\n for (const [key, value] of Object.entries(process.env)) {\n if (!value || !key.endsWith(\"_DATABASE_URL\")) continue;\n if (ignored.has(key) || key.endsWith(\"_UNPOOLED_DATABASE_URL\")) continue;\n const prefix = key.slice(0, -\"_DATABASE_URL\".length);\n if (!prefix || prefix === \"NETLIFY\") continue;\n if (currentAppPrefix && prefix === currentAppPrefix) continue;\n const id = sourceIdFromEnvPrefix(prefix);\n sources.push({\n id,\n label: labelFromSourceId(id),\n kind: \"env\",\n databaseUrl: value,\n databaseUrlEnv: key,\n });\n }\n return sources;\n}\n\nfunction sourceConfigs(): ThreadDebugSourceConfig[] {\n const byId = new Map<string, ThreadDebugSourceConfig>();\n byId.set(\"current\", {\n id: \"current\",\n label: \"Current Dispatch DB\",\n kind: \"current\",\n databaseUrlEnv: currentDatabaseUrlEnv(),\n });\n for (const source of discoverEnvSources()) byId.set(source.id, source);\n for (const source of parseConfiguredSources()) byId.set(source.id, source);\n return [...byId.values()];\n}\n\nfunction resolveSourceConfig(sourceId = \"current\"): ThreadDebugSourceConfig {\n const normalized = sourceId.trim() || \"current\";\n const direct = sourceConfigs().find((source) => source.id === normalized);\n if (direct) {\n if (direct.kind !== \"current\" && !direct.databaseUrl) {\n // A configured source whose URL env var is unset is a deploy\n // misconfiguration: untyped on purpose, so the boundary captures it.\n throw new Error(\n `Thread debug source \"${normalized}\" is configured but disconnected.`,\n );\n }\n return direct;\n }\n\n const prefix = envPrefixForSourceId(normalized);\n const databaseUrlEnv = `${prefix}_DATABASE_URL`;\n const databaseUrl = process.env[databaseUrlEnv];\n if (!databaseUrl) {\n fail(`Thread debug source \"${normalized}\" is not configured.`, {\n errorCode: \"thread_debug_source_not_configured\",\n statusCode: 404,\n });\n }\n return {\n id: normalized,\n label: labelFromSourceId(normalized),\n kind: \"env\",\n databaseUrl,\n databaseUrlEnv,\n };\n}\n\nasync function execForSource(source: ThreadDebugSourceConfig): Promise<DbExec> {\n if (source.kind === \"current\") return getDbExec();\n if (!source.databaseUrl) {\n throw new Error(\n `Thread debug source \"${source.id}\" is configured but disconnected.`,\n );\n }\n const cacheKey = source.databaseUrl;\n if (!execCache.has(cacheKey)) {\n execCache.set(\n cacheKey,\n createDbExec({\n url: source.databaseUrl,\n }),\n );\n }\n return execCache.get(cacheKey)!;\n}\n\nasync function currentDbRows<T = Record<string, unknown>>(\n sql: string,\n args: unknown[] = [],\n): Promise<T[]> {\n return optionalRows<T>(getDbExec(), sql, args);\n}\n\nasync function viewerOrgRole(\n orgId: string | null,\n viewerEmail: string,\n): Promise<string | null> {\n if (!orgId) return null;\n const rows = await currentDbRows<{ role?: string }>(\n `SELECT role FROM org_members\n WHERE org_id = ? AND LOWER(email) = ?\n AND federation_removal_pending_at IS NULL\n LIMIT 1`,\n [orgId, viewerEmail.toLowerCase()],\n );\n return typeof rows[0]?.role === \"string\" ? rows[0].role : null;\n}\n\nasync function currentOrgMembers(orgId: string | null): Promise<string[]> {\n if (!orgId) return [];\n const rows = await currentDbRows<{ email?: string }>(\n `SELECT email FROM org_members\n WHERE org_id = ? AND federation_removal_pending_at IS NULL`,\n [orgId],\n );\n return rows.map((row) => String(row.email ?? \"\").trim()).filter(Boolean);\n}\n\nasync function resolveDebugAccess(): Promise<DebugAccess> {\n const viewerEmail = currentOwnerEmail();\n const orgId = currentOrgId();\n const role = await viewerOrgRole(orgId, viewerEmail);\n const envAdmin = isDispatchEnvironmentAdmin(viewerEmail);\n const canInspectAll = envAdmin || role === \"owner\" || role === \"admin\";\n const memberEmails = canInspectAll\n ? await currentOrgMembers(orgId)\n : [viewerEmail];\n return {\n viewerEmail,\n orgId,\n role,\n envAdmin,\n canInspectAll,\n memberEmails: memberEmails.length > 0 ? memberEmails : [viewerEmail],\n };\n}\n\nfunction assertSourceAccess(\n source: ThreadDebugSourceConfig,\n access: DebugAccess,\n) {\n if (source.kind === \"current\") return;\n if (!access.canInspectAll) {\n throw new ForbiddenError(\n \"Only Dispatch admins can inspect thread databases from other apps.\",\n );\n }\n}\n\nfunction ownerScope(\n access: DebugAccess,\n ownerEmail?: string,\n column = \"owner_email\",\n): OwnerScope {\n const requested = ownerEmail?.trim();\n if (!access.canInspectAll) {\n return {\n sql: `${column} = ?`,\n args: [access.viewerEmail],\n label: access.viewerEmail,\n };\n }\n\n if (requested && requested !== \"*\") {\n if (\n access.orgId &&\n !access.memberEmails.some(\n (email) => email.toLowerCase() === requested.toLowerCase(),\n )\n ) {\n fail(\"The requested owner is not a member of the current organization.\", {\n errorCode: \"forbidden\",\n statusCode: 403,\n });\n }\n return {\n sql: `${column} = ?`,\n args: [requested],\n label: requested,\n };\n }\n\n if (access.envAdmin && !access.orgId) {\n return { sql: \"1 = 1\", args: [], label: \"all users\" };\n }\n\n const emails = access.memberEmails;\n if (emails.length === 0) {\n return {\n sql: `${column} = ?`,\n args: [access.viewerEmail],\n label: access.viewerEmail,\n };\n }\n const placeholders = emails.map(() => \"?\").join(\", \");\n return {\n sql: `${column} IN (${placeholders})`,\n args: emails,\n label: access.orgId ? \"current organization\" : \"all users\",\n };\n}\n\nfunction serializeThreadSummary(row: ChatThreadRow, query = \"\") {\n return {\n id: String(row.id),\n ownerEmail: String(row.owner_email ?? \"\"),\n title: String(row.title ?? \"\"),\n preview: String(row.preview ?? \"\"),\n messageCount: numberField(row.message_count),\n createdAt: numberField(row.created_at),\n updatedAt: numberField(row.updated_at),\n snippet: snippetFor(row, query),\n };\n}\n\nfunction serializeRun(row: AgentRunRow, events: any[] = []) {\n return {\n id: String(row.id),\n threadId: String(row.thread_id),\n turnId: row.turn_id ? String(row.turn_id) : null,\n status: String(row.status),\n abortReason: row.abort_reason ? String(row.abort_reason) : null,\n errorCode: row.error_code ? String(row.error_code) : null,\n errorDetail: row.error_detail ? String(row.error_detail) : null,\n terminalReason: row.terminal_reason ? String(row.terminal_reason) : null,\n startedAt: numberField(row.started_at),\n completedAt: nullableNumberField(row.completed_at),\n heartbeatAt: nullableNumberField(row.heartbeat_at),\n lastProgressAt: nullableNumberField(row.last_progress_at),\n dispatchMode: row.dispatch_mode ? String(row.dispatch_mode) : null,\n workerStage: row.worker_stage ? String(row.worker_stage) : null,\n diagStage: row.diag_stage ? String(row.diag_stage) : null,\n peakRssMb: nullableNumberField(row.peak_rss_mb),\n inFlightSince: nullableNumberField(row.in_flight_since),\n hasDispatchPayload:\n row.dispatch_payload !== null &&\n row.dispatch_payload !== undefined &&\n String(row.dispatch_payload).length > 0,\n events,\n };\n}\n\nfunction parseRunEvent(row: Record<string, unknown>) {\n const raw =\n typeof row.event_data === \"string\"\n ? row.event_data\n : JSON.stringify(row.event_data ?? \"\");\n return {\n runId:\n typeof row.run_id === \"string\" || typeof row.run_id === \"number\"\n ? String(row.run_id)\n : \"\",\n seq: numberField(row.seq),\n event: safeJsonParse(raw, { type: \"unparseable\", raw }),\n rawEventData: raw,\n };\n}\n\nexport async function listThreadDebugSources(): Promise<{\n access: Omit<DebugAccess, \"memberEmails\" | \"envAdmin\"> & {\n envAdmin: boolean;\n memberCount: number;\n };\n sources: ThreadDebugSource[];\n}> {\n const access = await resolveDebugAccess();\n return {\n access: {\n viewerEmail: access.viewerEmail,\n orgId: access.orgId,\n role: access.role,\n envAdmin: access.envAdmin,\n canInspectAll: access.canInspectAll,\n memberCount: access.memberEmails.length,\n },\n sources: sourceConfigs().map((source) => ({\n id: source.id,\n label: source.label,\n kind: source.kind,\n current: source.kind === \"current\",\n connected: source.kind === \"current\" || Boolean(source.databaseUrl),\n databaseUrlEnv: source.databaseUrlEnv ?? null,\n canInspectAll: access.canInspectAll,\n })),\n };\n}\n\nfunction publicSource(source: ThreadDebugSourceConfig) {\n return {\n id: source.id,\n label: source.label,\n kind: source.kind,\n databaseUrlEnv: source.databaseUrlEnv ?? null,\n };\n}\n\nfunction parseTerminalEvent(value: unknown): Record<string, unknown> | null {\n if (value == null || value === \"\") return null;\n try {\n const parsed = JSON.parse(\n typeof value === \"string\" ? value : JSON.stringify(value),\n );\n return parsed && typeof parsed === \"object\"\n ? (parsed as Record<string, unknown>)\n : { type: \"unparseable\" };\n } catch {\n return { type: \"unparseable\" };\n }\n}\n\nfunction serializeRunFailure(\n row: AgentRunFailureRow,\n source: ThreadDebugSourceConfig,\n) {\n const startedAt = numberField(row.started_at);\n const completedAt = nullableNumberField(row.completed_at);\n const terminalEvent = parseTerminalEvent(row.debug_terminal_event_data);\n const failureTaxonomy = classifyAgentFailure({\n runId: row.id,\n errorCode: row.error_code,\n errorDetail: row.error_detail,\n terminalReason: row.terminal_reason,\n terminalEvent,\n });\n return {\n source: publicSource(source),\n id: String(row.id),\n threadId: String(row.thread_id),\n turnId: row.turn_id ? String(row.turn_id) : null,\n ownerEmail: String(row.debug_owner_email ?? \"\"),\n threadTitle: String(row.debug_thread_title ?? \"\"),\n threadPreview: String(row.debug_thread_preview ?? \"\"),\n status: String(row.status) as AgentRunFailureStatus,\n abortReason: row.abort_reason ? String(row.abort_reason) : null,\n errorCode: row.error_code ? String(row.error_code) : null,\n errorDetail: row.error_detail ? String(row.error_detail) : null,\n terminalReason: row.terminal_reason ? String(row.terminal_reason) : null,\n startedAt,\n completedAt,\n heartbeatAt: nullableNumberField(row.heartbeat_at),\n lastProgressAt: nullableNumberField(row.last_progress_at),\n durationMs: completedAt == null ? null : completedAt - startedAt,\n dispatchMode: row.dispatch_mode ? String(row.dispatch_mode) : null,\n workerStage: row.worker_stage ? String(row.worker_stage) : null,\n diagStage: row.diag_stage ? String(row.diag_stage) : null,\n peakRssMb: nullableNumberField(row.peak_rss_mb),\n terminalEvent,\n regime: failureTaxonomy.regime,\n failureTaxonomy,\n };\n}\n\nfunction sourceHealth(\n source: ThreadDebugSourceConfig,\n status: ThreadDebugSourceHealthStatus,\n failureCount: number,\n errorCode:\n | null\n | \"thread_debug_source_disconnected\"\n | \"thread_debug_schema_unsupported\"\n | \"thread_debug_source_unavailable\",\n) {\n return {\n source: publicSource(source),\n status,\n failureCount,\n errorCode,\n };\n}\n\nasync function failuresForSource(\n source: ThreadDebugSourceConfig,\n scope: OwnerScope,\n input: {\n status: AgentRunFailureStatus | \"all\";\n regime: AgentFailureRegime | \"all\";\n cutoff: number;\n limit: number;\n },\n) {\n const exec = await execForSource(source);\n const statuses =\n input.status === \"all\" ? [...UNSUCCESSFUL_RUN_STATUSES] : [input.status];\n const statusPlaceholders = statuses.map(() => \"?\").join(\", \");\n const regimeClause =\n input.regime === \"scheduled\"\n ? \"AND r.id LIKE 'job-%'\"\n : input.regime === \"interactive\"\n ? \"AND r.id NOT LIKE 'job-%'\"\n : \"\";\n const rows = await queryRows<AgentRunFailureRow>(\n exec,\n `SELECT r.*,\n t.owner_email AS debug_owner_email,\n t.title AS debug_thread_title,\n t.preview AS debug_thread_preview,\n (\n SELECT e.event_data\n FROM agent_run_events e\n WHERE e.run_id = r.id\n ORDER BY e.seq DESC\n LIMIT 1\n ) AS debug_terminal_event_data\n FROM agent_runs r\n JOIN chat_threads t ON t.id = r.thread_id\n WHERE r.status IN (${statusPlaceholders})\n AND ${scope.sql}\n ${regimeClause}\n AND COALESCE(r.completed_at, r.started_at) >= ?\n ORDER BY COALESCE(r.completed_at, r.started_at) DESC, r.id DESC\n LIMIT ?`,\n [...statuses, ...scope.args, input.cutoff, input.limit],\n );\n return rows.map((row) => serializeRunFailure(row, source));\n}\n\nexport async function listAgentRunFailures(input: {\n sourceId?: string;\n ownerEmail?: string;\n status?: AgentRunFailureStatus | \"all\";\n regime?: AgentFailureRegime | \"all\";\n lookbackHours?: number;\n limit?: number;\n}) {\n const access = await resolveDebugAccess();\n const requestedSourceId = input.sourceId?.trim() || \"all\";\n const status = input.status ?? \"all\";\n const regime = input.regime ?? \"all\";\n const lookbackHours = Math.max(1, Math.min(720, input.lookbackHours ?? 168));\n const limit = Math.max(1, Math.min(100, input.limit ?? DEFAULT_SEARCH_LIMIT));\n const scope = ownerScope(access, input.ownerEmail, \"t.owner_email\");\n const cutoff = Date.now() - lookbackHours * 60 * 60 * 1000;\n\n let sources: ThreadDebugSourceConfig[];\n if (requestedSourceId === \"all\") {\n sources = sourceConfigs().filter(\n (source) => source.kind === \"current\" || access.canInspectAll,\n );\n } else {\n const configured = sourceConfigs().find(\n (source) => source.id === requestedSourceId,\n );\n const source = configured ?? resolveSourceConfig(requestedSourceId);\n assertSourceAccess(source, access);\n if (source.kind !== \"current\" && !source.databaseUrl) {\n throw new Error(\n `Thread debug source \"${requestedSourceId}\" is configured but disconnected.`,\n );\n }\n sources = [source];\n }\n\n const results = await Promise.all(\n sources.map(async (source) => {\n if (source.kind !== \"current\" && !source.databaseUrl) {\n return {\n failures: [] as ReturnType<typeof serializeRunFailure>[],\n health: sourceHealth(\n source,\n \"disconnected\",\n 0,\n \"thread_debug_source_disconnected\",\n ),\n };\n }\n try {\n const failures = await failuresForSource(source, scope, {\n status,\n regime,\n cutoff,\n limit,\n });\n return {\n failures,\n health: sourceHealth(source, \"ok\", failures.length, null),\n };\n } catch (error) {\n if (error instanceof UnsupportedThreadDebugSchemaError) {\n return {\n failures: [] as ReturnType<typeof serializeRunFailure>[],\n health: sourceHealth(\n source,\n \"unsupported\",\n 0,\n \"thread_debug_schema_unsupported\",\n ),\n };\n }\n return {\n failures: [] as ReturnType<typeof serializeRunFailure>[],\n health: sourceHealth(\n source,\n \"unavailable\",\n 0,\n \"thread_debug_source_unavailable\",\n ),\n };\n }\n }),\n );\n\n const failures = results\n .flatMap((result) => result.failures)\n .sort(\n (a, b) =>\n (b.completedAt ?? b.startedAt) - (a.completedAt ?? a.startedAt) ||\n b.id.localeCompare(a.id) ||\n b.source.id.localeCompare(a.source.id),\n )\n .slice(0, limit);\n\n return {\n sourceId: requestedSourceId,\n status,\n regime,\n lookbackHours,\n limit,\n count: failures.length,\n partial: results.some((result) => result.health.status !== \"ok\"),\n access: {\n viewerEmail: access.viewerEmail,\n scope: scope.label,\n canInspectAll: access.canInspectAll,\n },\n sources: results.map((result) => result.health),\n failures,\n };\n}\n\nexport async function searchAgentThreads(input: {\n sourceId?: string;\n query?: string;\n ownerEmail?: string;\n limit?: number;\n}) {\n const source = resolveSourceConfig(input.sourceId ?? \"current\");\n const access = await resolveDebugAccess();\n assertSourceAccess(source, access);\n const exec = await execForSource(source);\n const limit = Math.max(\n 1,\n Math.min(MAX_SEARCH_LIMIT, input.limit ?? DEFAULT_SEARCH_LIMIT),\n );\n const q = input.query?.trim() ?? \"\";\n const scope = ownerScope(access, input.ownerEmail);\n const where = [scope.sql];\n const args: unknown[] = [...scope.args];\n const runThreadIds = q\n ? (\n await optionalRows<{ thread_id: string }>(\n exec,\n \"SELECT thread_id FROM agent_runs WHERE id = ? LIMIT 1\",\n [q],\n )\n )\n .map((row) => String(row.thread_id ?? \"\").trim())\n .filter(Boolean)\n : [];\n if (q) {\n const pattern = \"%\" + escapeLike(q.toLowerCase()) + \"%\";\n const runIdClause =\n runThreadIds.length > 0\n ? \" OR id IN (\" + runThreadIds.map(() => \"?\").join(\", \") + \")\"\n : \"\";\n where.push(\n \"(LOWER(title) LIKE ? ESCAPE '\\\\' OR LOWER(preview) LIKE ? ESCAPE '\\\\' OR LOWER(owner_email) LIKE ? ESCAPE '\\\\' OR LOWER(thread_data) LIKE ? ESCAPE '\\\\'\" +\n runIdClause +\n \")\",\n );\n args.push(pattern, pattern, pattern, pattern);\n args.push(...runThreadIds);\n }\n args.push(limit);\n\n const rows = await optionalRows<ChatThreadRow>(\n exec,\n `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at\n FROM chat_threads\n WHERE ${where.join(\" AND \")}\n ORDER BY updated_at DESC\n LIMIT ?`,\n args,\n );\n return {\n source: {\n id: source.id,\n label: source.label,\n kind: source.kind,\n databaseUrlEnv: source.databaseUrlEnv ?? null,\n },\n access: {\n viewerEmail: access.viewerEmail,\n scope: scope.label,\n canInspectAll: access.canInspectAll,\n },\n query: q,\n count: rows.length,\n threads: rows.map((row) => serializeThreadSummary(row, q)),\n };\n}\n\nexport async function getAgentThreadDebug(input: {\n sourceId?: string;\n threadId?: string;\n runId?: string;\n ownerEmail?: string;\n maxRuns?: number;\n maxEvents?: number;\n maxTraceSpans?: number;\n}) {\n const source = resolveSourceConfig(input.sourceId ?? \"current\");\n const access = await resolveDebugAccess();\n assertSourceAccess(source, access);\n const exec = await execForSource(source);\n const scope = ownerScope(access, input.ownerEmail);\n const requestedId = input.runId?.trim() || input.threadId?.trim() || \"\";\n if (!requestedId) {\n fail(\"A thread ID or request/run ID is required.\", {\n errorCode: \"thread_id_required\",\n statusCode: 400,\n });\n }\n\n let rows = await queryRows<ChatThreadRow>(\n exec,\n `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at\n FROM chat_threads\n WHERE id = ? AND ${scope.sql}\n LIMIT 1`,\n [input.threadId?.trim() || requestedId, ...scope.args],\n );\n let resolvedRunId = input.runId?.trim() || null;\n\n if (!rows[0]) {\n const runRows = await optionalRows<{ id: string; thread_id: string }>(\n exec,\n `SELECT id, thread_id\n FROM agent_runs\n WHERE id = ?\n LIMIT 1`,\n [requestedId],\n );\n const threadId = runRows[0]?.thread_id\n ? String(runRows[0].thread_id).trim()\n : \"\";\n if (threadId) {\n rows = await queryRows<ChatThreadRow>(\n exec,\n `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at\n FROM chat_threads\n WHERE id = ? AND ${scope.sql}\n LIMIT 1`,\n [threadId, ...scope.args],\n );\n if (rows[0]) resolvedRunId = requestedId;\n }\n }\n\n const row = rows[0];\n if (!row) {\n fail(`Thread or request/run ID \"${requestedId}\" was not found.`, {\n errorCode: \"not_found\",\n statusCode: 404,\n });\n }\n\n const threadData = safeJsonParse<Record<string, unknown>>(\n row.thread_data,\n {},\n );\n const maxRuns = Math.max(1, Math.min(50, input.maxRuns ?? DEFAULT_RUN_LIMIT));\n const maxEvents = Math.max(\n 1,\n Math.min(2_000, input.maxEvents ?? DEFAULT_EVENT_LIMIT),\n );\n const maxTraceSpans = Math.max(\n 1,\n Math.min(2_000, input.maxTraceSpans ?? DEFAULT_TRACE_SPAN_LIMIT),\n );\n\n let runRows = await optionalRows<AgentRunRow>(\n exec,\n `SELECT r.*\n FROM agent_runs r\n WHERE r.thread_id = ?\n ORDER BY r.started_at DESC\n LIMIT ?`,\n [row.id, maxRuns],\n );\n\n // A deep-linked run can be older than the most recent `maxRuns` runs; fetch\n // it explicitly so the inspector opens the run someone was sent to debug\n // instead of silently falling back to the latest one.\n if (resolvedRunId && !runRows.some((run) => run.id === resolvedRunId)) {\n const lookupRunRows = await optionalRows<AgentRunRow>(\n exec,\n `SELECT r.*\n FROM agent_runs r\n WHERE r.thread_id = ? AND r.id = ?\n LIMIT 1`,\n [row.id, resolvedRunId],\n );\n if (lookupRunRows[0]) {\n runRows = [...runRows, lookupRunRows[0]].sort(\n (a, b) => Number(b.started_at) - Number(a.started_at),\n );\n }\n }\n\n const runs = [];\n for (const run of runRows) {\n const eventRows = await optionalRows<Record<string, unknown>>(\n exec,\n `SELECT run_id, seq, event_data\n FROM agent_run_events\n WHERE run_id = ?\n ORDER BY seq ASC\n LIMIT ?`,\n [run.id, maxEvents],\n );\n runs.push(serializeRun(run, eventRows.map(parseRunEvent)));\n }\n\n const runIds = runRows.map((run) => run.id);\n const runPlaceholders = runIds.map(() => \"?\").join(\", \");\n const traceSummaryRows = await optionalRows<Record<string, unknown>>(\n exec,\n runIds.length > 0\n ? `SELECT *\n FROM agent_trace_summaries\n WHERE thread_id = ? OR run_id IN (${runPlaceholders})\n ORDER BY created_at DESC\n LIMIT 50`\n : `SELECT *\n FROM agent_trace_summaries\n WHERE thread_id = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n runIds.length > 0 ? [row.id, ...runIds] : [row.id],\n );\n const traceSpanRows = await optionalRows<Record<string, unknown>>(\n exec,\n runIds.length > 0\n ? `SELECT *\n FROM agent_trace_spans\n WHERE thread_id = ? OR run_id IN (${runPlaceholders})\n ORDER BY created_at ASC\n LIMIT ?`\n : `SELECT *\n FROM agent_trace_spans\n WHERE thread_id = ?\n ORDER BY created_at ASC\n LIMIT ?`,\n runIds.length > 0\n ? [row.id, ...runIds, maxTraceSpans]\n : [row.id, maxTraceSpans],\n );\n const feedbackRows = await optionalRows<Record<string, unknown>>(\n exec,\n `SELECT *\n FROM agent_feedback\n WHERE thread_id = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n [row.id],\n );\n const satisfactionRows = await optionalRows<Record<string, unknown>>(\n exec,\n `SELECT *\n FROM agent_satisfaction_scores\n WHERE thread_id = ?\n ORDER BY computed_at DESC\n LIMIT 10`,\n [row.id],\n );\n const evalRows = await optionalRows<Record<string, unknown>>(\n exec,\n runIds.length > 0\n ? `SELECT *\n FROM agent_evals\n WHERE thread_id = ? OR run_id IN (${runPlaceholders})\n ORDER BY created_at DESC\n LIMIT 50`\n : `SELECT *\n FROM agent_evals\n WHERE thread_id = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n runIds.length > 0 ? [row.id, ...runIds] : [row.id],\n );\n const checkpointRows = await optionalRows<Record<string, unknown>>(\n exec,\n `SELECT id, thread_id, run_id, commit_sha, message, created_at\n FROM agent_checkpoints\n WHERE thread_id = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n [row.id],\n );\n\n return {\n source: {\n id: source.id,\n label: source.label,\n kind: source.kind,\n databaseUrlEnv: source.databaseUrlEnv ?? null,\n },\n access: {\n viewerEmail: access.viewerEmail,\n scope: scope.label,\n canInspectAll: access.canInspectAll,\n },\n thread: {\n id: String(row.id),\n ownerEmail: String(row.owner_email ?? \"\"),\n title: String(row.title ?? \"\"),\n preview: String(row.preview ?? \"\"),\n messageCount: numberField(row.message_count),\n createdAt: numberField(row.created_at),\n updatedAt: numberField(row.updated_at),\n },\n lookup: {\n requestedId,\n threadId: String(row.id),\n runId: resolvedRunId,\n },\n messages: normalizeMessages(threadData),\n debug: (threadData as any)?._debug ?? null,\n debugRuns: Array.isArray((threadData as any)?._debugRuns)\n ? (threadData as any)._debugRuns\n : [],\n queuedMessages: (threadData as any)?.queuedMessages ?? [],\n threadData,\n rawThreadData: row.thread_data ?? \"\",\n runs,\n traces: {\n summaries: traceSummaryRows,\n spans: traceSpanRows,\n },\n feedback: feedbackRows,\n satisfaction: satisfactionRows,\n evals: evalRows,\n checkpoints: checkpointRows,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"thread-debug-store.js","sourceRoot":"","sources":["../../../src/server/lib/thread-debug-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,2BAA2B,CAAC;AACjD,OAAO,EACL,oBAAoB,GAErB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAe,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAE5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAEtE,MAAM,cAAc,GAAG,qCAAqC,CAAC;AAC7D,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAoErC,MAAM,SAAS,GAAG,IAAI,GAAG,EAA2B,CAAC;AAErD,MAAM,yBAAyB,GAAG,CAAC,SAAS,EAAE,SAAS,EAAE,WAAW,CAAU,CAAC;AAiB/E,MAAM,iCAAkC,SAAQ,KAAK;IAG9B,KAAK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C,OAAO,IAAI,EAAE,CAAC;YAClC,YAAY,EAAE,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC;YAC5C,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC;YACtC,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC;SACvC;QACD,MAAM,EAAE;YACN,WAAW;YACX,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;YACxB,KAAK,EAAE,aAAa;SACrB;QACD,QAAQ,EAAE,iBAAiB,CAAC,UAAU,CAAC;QACvC,KAAK,EAAG,UAAkB,EAAE,MAAM,IAAI,IAAI;QAC1C,SAAS,EAAE,KAAK,CAAC,OAAO,CAAE,UAAkB,EAAE,UAAU,CAAC;YACvD,CAAC,CAAE,UAAkB,CAAC,UAAU;YAChC,CAAC,CAAC,EAAE;QACN,cAAc,EAAG,UAAkB,EAAE,cAAc,IAAI,EAAE;QACzD,UAAU;QACV,aAAa,EAAE,GAAG,CAAC,WAAW,IAAI,EAAE;QACpC,IAAI;QACJ,MAAM,EAAE;YACN,SAAS,EAAE,gBAAgB;YAC3B,KAAK,EAAE,aAAa;SACrB;QACD,QAAQ,EAAE,YAAY;QACtB,YAAY,EAAE,gBAAgB;QAC9B,KAAK,EAAE,QAAQ;QACf,WAAW,EAAE,cAAc;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["import { fail } from \"@agent-native/core/action\";\nimport {\n classifyAgentFailure,\n type AgentFailureRegime,\n} from \"@agent-native/core/agent/engine\";\nimport { createDbExec, getDbExec, type DbExec } from \"@agent-native/core/db\";\nimport { getAppConfig } from \"@agent-native/core/server\";\nimport { ForbiddenError } from \"@agent-native/core/sharing\";\n\nimport { isDispatchEnvironmentAdmin } from \"./admin-config.js\";\nimport { currentOrgId, currentOwnerEmail } from \"./dispatch-store.js\";\n\nconst CONFIG_ENV_KEY = \"AGENT_NATIVE_THREAD_DEBUG_DATABASES\";\nconst MAX_RAW_PREVIEW_CHARS = 1_500;\nconst DEFAULT_SEARCH_LIMIT = 25;\nconst MAX_SEARCH_LIMIT = 100;\nconst DEFAULT_RUN_LIMIT = 20;\nconst DEFAULT_EVENT_LIMIT = 600;\nconst DEFAULT_TRACE_SPAN_LIMIT = 500;\n\ninterface ThreadDebugSourceConfig {\n id: string;\n label: string;\n kind: \"current\" | \"env\" | \"configured\";\n databaseUrl?: string;\n databaseUrlEnv?: string | null;\n}\n\nexport interface ThreadDebugSource {\n id: string;\n label: string;\n kind: \"current\" | \"env\" | \"configured\";\n current: boolean;\n connected: boolean;\n databaseUrlEnv: string | null;\n canInspectAll: boolean;\n}\n\nexport interface DebugAccess {\n viewerEmail: string;\n orgId: string | null;\n role: string | null;\n envAdmin: boolean;\n superOrg: boolean;\n canInspectAll: boolean;\n memberEmails: string[];\n}\n\ninterface OwnerScope {\n sql: string;\n args: unknown[];\n label: string;\n}\n\ninterface ChatThreadRow {\n id: string;\n owner_email: string;\n title: string | null;\n preview: string | null;\n thread_data: string | null;\n message_count: number | string | null;\n created_at: number | string;\n updated_at: number | string;\n}\n\ninterface AgentRunRow {\n id: string;\n thread_id: string;\n status: string;\n abort_reason?: string | null;\n started_at: number | string;\n completed_at?: number | string | null;\n heartbeat_at?: number | string | null;\n turn_id?: string | null;\n last_progress_at?: number | string | null;\n error_code?: string | null;\n error_detail?: string | null;\n terminal_reason?: string | null;\n dispatch_mode?: string | null;\n worker_stage?: string | null;\n diag_stage?: string | null;\n peak_rss_mb?: number | string | null;\n in_flight_since?: number | string | null;\n dispatch_payload?: string | null;\n}\n\nconst execCache = new Map<string, Promise<DbExec>>();\n\nconst UNSUCCESSFUL_RUN_STATUSES = [\"errored\", \"aborted\", \"truncated\"] as const;\n\nexport type AgentRunFailureStatus = (typeof UNSUCCESSFUL_RUN_STATUSES)[number];\n\ntype ThreadDebugSourceHealthStatus =\n | \"ok\"\n | \"disconnected\"\n | \"unsupported\"\n | \"unavailable\";\n\ninterface AgentRunFailureRow extends AgentRunRow {\n debug_owner_email: string;\n debug_thread_title?: string | null;\n debug_thread_preview?: string | null;\n debug_terminal_event_data?: string | null;\n}\n\nclass UnsupportedThreadDebugSchemaError extends Error {\n readonly code = \"thread_debug_schema_unsupported\";\n\n constructor(readonly table: string) {\n super(`This database does not have the required \"${table}\" table.`);\n this.name = \"UnsupportedThreadDebugSchemaError\";\n }\n}\n\nfunction escapeLike(value: string): string {\n return value.replace(/([\\\\%_])/g, \"\\\\$1\");\n}\n\nfunction missingTableName(error: unknown): string | null {\n const message = String((error as Error)?.message ?? error);\n const patterns = [\n /relation\\s+[\"'`](?:(?:public)\\.)?([a-zA-Z_][\\w$]*)[\"'`]\\s+does not exist/i,\n /table\\s+[\"'`](?:[^\"'`.]+\\.)?([a-zA-Z_][\\w$]*)[\"'`]\\s+does(?:n't| not)\\s+exist/i,\n ];\n for (const pattern of patterns) {\n const match = message.match(pattern);\n if (match?.[1]) return match[1].toLowerCase();\n }\n return null;\n}\n\nfunction isMissingTableError(error: unknown): boolean {\n return missingTableName(error) !== null;\n}\n\nasync function optionalRows<T = Record<string, unknown>>(\n exec: DbExec,\n sql: string,\n args: unknown[] = [],\n): Promise<T[]> {\n try {\n return (await exec.execute({ sql, args })).rows as T[];\n } catch (error) {\n if (isMissingTableError(error)) return [];\n throw error;\n }\n}\n\nasync function queryRows<T = Record<string, unknown>>(\n exec: DbExec,\n sql: string,\n args: unknown[] = [],\n): Promise<T[]> {\n try {\n return (await exec.execute({ sql, args })).rows as T[];\n } catch (error) {\n const missingTable = missingTableName(error);\n if (missingTable) {\n throw new UnsupportedThreadDebugSchemaError(missingTable);\n }\n throw error;\n }\n}\n\nfunction numberField(value: unknown): number {\n const parsed = Number(value ?? 0);\n return Number.isFinite(parsed) ? parsed : 0;\n}\n\nfunction nullableNumberField(value: unknown): number | null {\n if (value == null) return null;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction safeJsonParse<T>(value: unknown, fallback: T): T {\n if (value == null || value === \"\") return fallback;\n try {\n return JSON.parse(\n typeof value === \"string\" ? value : JSON.stringify(value),\n ) as T;\n } catch {\n return fallback;\n }\n}\n\nfunction safeJsonStringify(value: unknown): string {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n}\n\nfunction textFromContent(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((part: any) => {\n if (part?.type === \"text\" && typeof part.text === \"string\") {\n return part.text;\n }\n if (part?.type === \"tool-call\") {\n const name = part.toolName ?? part.name ?? \"tool\";\n return `[tool:${name}] ${safeJsonStringify(part.args ?? part.input ?? {})}`;\n }\n if (part?.type === \"tool-result\") {\n return `[tool-result:${part.toolName ?? part.toolCallId ?? \"tool\"}] ${\n typeof part.content === \"string\"\n ? part.content\n : safeJsonStringify(part.content)\n }`;\n }\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction normalizeMessages(threadData: any) {\n const messages = Array.isArray(threadData?.messages)\n ? threadData.messages\n : [];\n return messages.map((entry: any, index: number) => {\n const message = entry?.message ?? entry;\n const content = message?.content;\n const contentParts = Array.isArray(content) ? content : [];\n return {\n index,\n id: typeof message?.id === \"string\" ? message.id : null,\n role: typeof message?.role === \"string\" ? message.role : \"unknown\",\n createdAt: message?.createdAt ?? null,\n status: message?.status ?? null,\n text: textFromContent(content),\n contentParts,\n attachments: Array.isArray(message?.attachments)\n ? message.attachments\n : [],\n metadata: message?.metadata ?? null,\n parentId: entry?.parentId ?? null,\n };\n });\n}\n\nfunction snippetFor(row: ChatThreadRow, query: string): string {\n const raw = `${row.title ?? \"\"}\\n${row.preview ?? \"\"}\\n${row.thread_data ?? \"\"}`;\n const compact = raw.replace(/\\s+/g, \" \").trim();\n if (!query.trim()) {\n return compact.slice(0, MAX_RAW_PREVIEW_CHARS);\n }\n const lower = compact.toLowerCase();\n const needle = query.trim().toLowerCase();\n const match = lower.indexOf(needle);\n if (match === -1) return compact.slice(0, MAX_RAW_PREVIEW_CHARS);\n const start = Math.max(0, match - 160);\n const end = Math.min(compact.length, match + needle.length + 320);\n const prefix = start > 0 ? \"...\" : \"\";\n const suffix = end < compact.length ? \"...\" : \"\";\n return `${prefix}${compact.slice(start, end)}${suffix}`;\n}\n\nfunction envPrefixForSourceId(sourceId: string): string {\n return sourceId.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\");\n}\n\nfunction sourceIdFromEnvPrefix(prefix: string): string {\n return prefix.toLowerCase().replace(/_/g, \"-\");\n}\n\nfunction labelFromSourceId(sourceId: string): string {\n return sourceId\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction currentDatabaseUrlEnv(): string | null {\n const appName = process.env.APP_NAME?.toUpperCase().replace(/-/g, \"_\");\n if (appName && process.env[`${appName}_DATABASE_URL`]) {\n return `${appName}_DATABASE_URL`;\n }\n return process.env.DATABASE_URL ? \"DATABASE_URL\" : null;\n}\n\nfunction parseConfiguredSources(): ThreadDebugSourceConfig[] {\n const raw = process.env[CONFIG_ENV_KEY];\n if (!raw) return [];\n const parsed = safeJsonParse<any>(raw, null);\n const entries = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\"\n ? Object.entries(parsed).map(([id, value]) => ({ id, ...(value as any) }))\n : [];\n\n return entries\n .map((entry: any): ThreadDebugSourceConfig | null => {\n const id = typeof entry?.id === \"string\" ? entry.id.trim() : \"\";\n if (!id) return null;\n const databaseUrlEnv =\n typeof entry.databaseUrlEnv === \"string\"\n ? entry.databaseUrlEnv.trim()\n : null;\n const databaseUrl =\n typeof entry.databaseUrl === \"string\" && entry.databaseUrl.trim()\n ? entry.databaseUrl.trim()\n : databaseUrlEnv\n ? process.env[databaseUrlEnv]\n : undefined;\n return {\n id,\n label:\n typeof entry.label === \"string\" && entry.label.trim()\n ? entry.label.trim()\n : labelFromSourceId(id),\n kind: \"configured\",\n databaseUrl,\n databaseUrlEnv,\n };\n })\n .filter((source): source is ThreadDebugSourceConfig => Boolean(source));\n}\n\nfunction discoverEnvSources(): ThreadDebugSourceConfig[] {\n const ignored = new Set([\n \"DATABASE_URL\",\n \"NETLIFY_DATABASE_URL\",\n \"NETLIFY_DATABASE_URL_UNPOOLED\",\n ]);\n const currentAppPrefix = process.env.APP_NAME?.toUpperCase().replace(\n /-/g,\n \"_\",\n );\n const sources: ThreadDebugSourceConfig[] = [];\n for (const [key, value] of Object.entries(process.env)) {\n if (!value || !key.endsWith(\"_DATABASE_URL\")) continue;\n if (ignored.has(key) || key.endsWith(\"_UNPOOLED_DATABASE_URL\")) continue;\n const prefix = key.slice(0, -\"_DATABASE_URL\".length);\n if (!prefix || prefix === \"NETLIFY\") continue;\n if (currentAppPrefix && prefix === currentAppPrefix) continue;\n const id = sourceIdFromEnvPrefix(prefix);\n sources.push({\n id,\n label: labelFromSourceId(id),\n kind: \"env\",\n databaseUrl: value,\n databaseUrlEnv: key,\n });\n }\n return sources;\n}\n\nfunction sourceConfigs(): ThreadDebugSourceConfig[] {\n const byId = new Map<string, ThreadDebugSourceConfig>();\n byId.set(\"current\", {\n id: \"current\",\n label: \"Current Dispatch DB\",\n kind: \"current\",\n databaseUrlEnv: currentDatabaseUrlEnv(),\n });\n for (const source of discoverEnvSources()) byId.set(source.id, source);\n for (const source of parseConfiguredSources()) byId.set(source.id, source);\n return [...byId.values()];\n}\n\nfunction resolveSourceConfig(sourceId = \"current\"): ThreadDebugSourceConfig {\n const normalized = sourceId.trim() || \"current\";\n const direct = sourceConfigs().find((source) => source.id === normalized);\n if (direct) {\n if (direct.kind !== \"current\" && !direct.databaseUrl) {\n // A configured source whose URL env var is unset is a deploy\n // misconfiguration: untyped on purpose, so the boundary captures it.\n throw new Error(\n `Thread debug source \"${normalized}\" is configured but disconnected.`,\n );\n }\n return direct;\n }\n\n const prefix = envPrefixForSourceId(normalized);\n const databaseUrlEnv = `${prefix}_DATABASE_URL`;\n const databaseUrl = process.env[databaseUrlEnv];\n if (!databaseUrl) {\n fail(`Thread debug source \"${normalized}\" is not configured.`, {\n errorCode: \"thread_debug_source_not_configured\",\n statusCode: 404,\n });\n }\n return {\n id: normalized,\n label: labelFromSourceId(normalized),\n kind: \"env\",\n databaseUrl,\n databaseUrlEnv,\n };\n}\n\nasync function execForSource(source: ThreadDebugSourceConfig): Promise<DbExec> {\n if (source.kind === \"current\") return getDbExec();\n if (!source.databaseUrl) {\n throw new Error(\n `Thread debug source \"${source.id}\" is configured but disconnected.`,\n );\n }\n const cacheKey = source.databaseUrl;\n if (!execCache.has(cacheKey)) {\n execCache.set(\n cacheKey,\n createDbExec({\n url: source.databaseUrl,\n }),\n );\n }\n return execCache.get(cacheKey)!;\n}\n\nasync function currentDbRows<T = Record<string, unknown>>(\n sql: string,\n args: unknown[] = [],\n): Promise<T[]> {\n return optionalRows<T>(getDbExec(), sql, args);\n}\n\nasync function viewerOrgRole(\n orgId: string | null,\n viewerEmail: string,\n): Promise<string | null> {\n if (!orgId) return null;\n const rows = await currentDbRows<{ role?: string }>(\n `SELECT role FROM org_members\n WHERE org_id = ? AND LOWER(email) = ?\n AND federation_removal_pending_at IS NULL\n LIMIT 1`,\n [orgId, viewerEmail.toLowerCase()],\n );\n return typeof rows[0]?.role === \"string\" ? rows[0].role : null;\n}\n\nasync function currentOrgMembers(orgId: string | null): Promise<string[]> {\n if (!orgId) return [];\n const rows = await currentDbRows<{ email?: string }>(\n `SELECT email FROM org_members\n WHERE org_id = ? AND federation_removal_pending_at IS NULL`,\n [orgId],\n );\n return rows.map((row) => String(row.email ?? \"\").trim()).filter(Boolean);\n}\n\nasync function resolveDebugAccess(): Promise<DebugAccess> {\n const viewerEmail = currentOwnerEmail();\n const orgId = currentOrgId();\n const role = await viewerOrgRole(orgId, viewerEmail);\n const envAdmin = isDispatchEnvironmentAdmin(viewerEmail);\n const orgAdmin = role === \"owner\" || role === \"admin\";\n const canInspectAll = envAdmin || orgAdmin;\n // Remote sources keep their own org rosters, so Dispatch membership cannot\n // scope them; the observability super org is the one cross-org review grant.\n const superOrgId = getAppConfig().observability.superOrgId;\n const superOrg = Boolean(orgId && orgAdmin && superOrgId === orgId);\n const memberEmails = canInspectAll\n ? await currentOrgMembers(orgId)\n : [viewerEmail];\n return {\n viewerEmail,\n orgId,\n role,\n envAdmin,\n superOrg,\n canInspectAll,\n memberEmails: memberEmails.length > 0 ? memberEmails : [viewerEmail],\n };\n}\n\nfunction assertSourceAccess(\n source: ThreadDebugSourceConfig,\n access: DebugAccess,\n) {\n if (source.kind === \"current\") return;\n if (!access.canInspectAll) {\n throw new ForbiddenError(\n \"Only Dispatch admins can inspect thread databases from other apps.\",\n );\n }\n}\n\nfunction ownerScope(\n access: DebugAccess,\n ownerEmail?: string,\n column = \"owner_email\",\n): OwnerScope {\n const requested = ownerEmail?.trim();\n if (!access.canInspectAll) {\n return {\n sql: `${column} = ?`,\n args: [access.viewerEmail],\n label: access.viewerEmail,\n };\n }\n\n if (requested && requested !== \"*\") {\n if (\n access.orgId &&\n !access.superOrg &&\n !access.memberEmails.some(\n (email) => email.toLowerCase() === requested.toLowerCase(),\n )\n ) {\n fail(\"The requested owner is not a member of the current organization.\", {\n errorCode: \"forbidden\",\n statusCode: 403,\n });\n }\n return {\n sql: `${column} = ?`,\n args: [requested],\n label: requested,\n };\n }\n\n if (access.superOrg) {\n return { sql: \"1 = 1\", args: [], label: \"all organizations\" };\n }\n if (access.envAdmin && !access.orgId) {\n return { sql: \"1 = 1\", args: [], label: \"all users\" };\n }\n\n const emails = access.memberEmails;\n if (emails.length === 0) {\n return {\n sql: `${column} = ?`,\n args: [access.viewerEmail],\n label: access.viewerEmail,\n };\n }\n const placeholders = emails.map(() => \"?\").join(\", \");\n return {\n sql: `${column} IN (${placeholders})`,\n args: emails,\n label: access.orgId ? \"current organization\" : \"all users\",\n };\n}\n\nfunction serializeThreadSummary(row: ChatThreadRow, query = \"\") {\n return {\n id: String(row.id),\n ownerEmail: String(row.owner_email ?? \"\"),\n title: String(row.title ?? \"\"),\n preview: String(row.preview ?? \"\"),\n messageCount: numberField(row.message_count),\n createdAt: numberField(row.created_at),\n updatedAt: numberField(row.updated_at),\n snippet: snippetFor(row, query),\n };\n}\n\nfunction serializeRun(row: AgentRunRow, events: any[] = []) {\n return {\n id: String(row.id),\n threadId: String(row.thread_id),\n turnId: row.turn_id ? String(row.turn_id) : null,\n status: String(row.status),\n abortReason: row.abort_reason ? String(row.abort_reason) : null,\n errorCode: row.error_code ? String(row.error_code) : null,\n errorDetail: row.error_detail ? String(row.error_detail) : null,\n terminalReason: row.terminal_reason ? String(row.terminal_reason) : null,\n startedAt: numberField(row.started_at),\n completedAt: nullableNumberField(row.completed_at),\n heartbeatAt: nullableNumberField(row.heartbeat_at),\n lastProgressAt: nullableNumberField(row.last_progress_at),\n dispatchMode: row.dispatch_mode ? String(row.dispatch_mode) : null,\n workerStage: row.worker_stage ? String(row.worker_stage) : null,\n diagStage: row.diag_stage ? String(row.diag_stage) : null,\n peakRssMb: nullableNumberField(row.peak_rss_mb),\n inFlightSince: nullableNumberField(row.in_flight_since),\n hasDispatchPayload:\n row.dispatch_payload !== null &&\n row.dispatch_payload !== undefined &&\n String(row.dispatch_payload).length > 0,\n events,\n };\n}\n\nfunction parseRunEvent(row: Record<string, unknown>) {\n const raw =\n typeof row.event_data === \"string\"\n ? row.event_data\n : JSON.stringify(row.event_data ?? \"\");\n return {\n runId:\n typeof row.run_id === \"string\" || typeof row.run_id === \"number\"\n ? String(row.run_id)\n : \"\",\n seq: numberField(row.seq),\n event: safeJsonParse(raw, { type: \"unparseable\", raw }),\n rawEventData: raw,\n };\n}\n\nexport async function listThreadDebugSources(): Promise<{\n access: Omit<DebugAccess, \"memberEmails\" | \"envAdmin\"> & {\n envAdmin: boolean;\n memberCount: number;\n };\n sources: ThreadDebugSource[];\n}> {\n const access = await resolveDebugAccess();\n return {\n access: {\n viewerEmail: access.viewerEmail,\n orgId: access.orgId,\n role: access.role,\n envAdmin: access.envAdmin,\n superOrg: access.superOrg,\n canInspectAll: access.canInspectAll,\n memberCount: access.memberEmails.length,\n },\n sources: sourceConfigs().map((source) => ({\n id: source.id,\n label: source.label,\n kind: source.kind,\n current: source.kind === \"current\",\n connected: source.kind === \"current\" || Boolean(source.databaseUrl),\n databaseUrlEnv: source.databaseUrlEnv ?? null,\n canInspectAll: access.canInspectAll,\n })),\n };\n}\n\nfunction publicSource(source: ThreadDebugSourceConfig) {\n return {\n id: source.id,\n label: source.label,\n kind: source.kind,\n databaseUrlEnv: source.databaseUrlEnv ?? null,\n };\n}\n\nfunction parseTerminalEvent(value: unknown): Record<string, unknown> | null {\n if (value == null || value === \"\") return null;\n try {\n const parsed = JSON.parse(\n typeof value === \"string\" ? value : JSON.stringify(value),\n );\n return parsed && typeof parsed === \"object\"\n ? (parsed as Record<string, unknown>)\n : { type: \"unparseable\" };\n } catch {\n return { type: \"unparseable\" };\n }\n}\n\nfunction serializeRunFailure(\n row: AgentRunFailureRow,\n source: ThreadDebugSourceConfig,\n) {\n const startedAt = numberField(row.started_at);\n const completedAt = nullableNumberField(row.completed_at);\n const terminalEvent = parseTerminalEvent(row.debug_terminal_event_data);\n const failureTaxonomy = classifyAgentFailure({\n runId: row.id,\n errorCode: row.error_code,\n errorDetail: row.error_detail,\n terminalReason: row.terminal_reason,\n terminalEvent,\n });\n return {\n source: publicSource(source),\n id: String(row.id),\n threadId: String(row.thread_id),\n turnId: row.turn_id ? String(row.turn_id) : null,\n ownerEmail: String(row.debug_owner_email ?? \"\"),\n threadTitle: String(row.debug_thread_title ?? \"\"),\n threadPreview: String(row.debug_thread_preview ?? \"\"),\n status: String(row.status) as AgentRunFailureStatus,\n abortReason: row.abort_reason ? String(row.abort_reason) : null,\n errorCode: row.error_code ? String(row.error_code) : null,\n errorDetail: row.error_detail ? String(row.error_detail) : null,\n terminalReason: row.terminal_reason ? String(row.terminal_reason) : null,\n startedAt,\n completedAt,\n heartbeatAt: nullableNumberField(row.heartbeat_at),\n lastProgressAt: nullableNumberField(row.last_progress_at),\n durationMs: completedAt == null ? null : completedAt - startedAt,\n dispatchMode: row.dispatch_mode ? String(row.dispatch_mode) : null,\n workerStage: row.worker_stage ? String(row.worker_stage) : null,\n diagStage: row.diag_stage ? String(row.diag_stage) : null,\n peakRssMb: nullableNumberField(row.peak_rss_mb),\n terminalEvent,\n regime: failureTaxonomy.regime,\n failureTaxonomy,\n };\n}\n\nfunction sourceHealth(\n source: ThreadDebugSourceConfig,\n status: ThreadDebugSourceHealthStatus,\n failureCount: number,\n errorCode:\n | null\n | \"thread_debug_source_disconnected\"\n | \"thread_debug_schema_unsupported\"\n | \"thread_debug_source_unavailable\",\n) {\n return {\n source: publicSource(source),\n status,\n failureCount,\n errorCode,\n };\n}\n\nasync function failuresForSource(\n source: ThreadDebugSourceConfig,\n scope: OwnerScope,\n input: {\n status: AgentRunFailureStatus | \"all\";\n regime: AgentFailureRegime | \"all\";\n cutoff: number;\n limit: number;\n },\n) {\n const exec = await execForSource(source);\n const statuses =\n input.status === \"all\" ? [...UNSUCCESSFUL_RUN_STATUSES] : [input.status];\n const statusPlaceholders = statuses.map(() => \"?\").join(\", \");\n const regimeClause =\n input.regime === \"scheduled\"\n ? \"AND r.id LIKE 'job-%'\"\n : input.regime === \"interactive\"\n ? \"AND r.id NOT LIKE 'job-%'\"\n : \"\";\n const rows = await queryRows<AgentRunFailureRow>(\n exec,\n `SELECT r.*,\n t.owner_email AS debug_owner_email,\n t.title AS debug_thread_title,\n t.preview AS debug_thread_preview,\n (\n SELECT e.event_data\n FROM agent_run_events e\n WHERE e.run_id = r.id\n ORDER BY e.seq DESC\n LIMIT 1\n ) AS debug_terminal_event_data\n FROM agent_runs r\n JOIN chat_threads t ON t.id = r.thread_id\n WHERE r.status IN (${statusPlaceholders})\n AND ${scope.sql}\n ${regimeClause}\n AND COALESCE(r.completed_at, r.started_at) >= ?\n ORDER BY COALESCE(r.completed_at, r.started_at) DESC, r.id DESC\n LIMIT ?`,\n [...statuses, ...scope.args, input.cutoff, input.limit],\n );\n return rows.map((row) => serializeRunFailure(row, source));\n}\n\nexport async function listAgentRunFailures(input: {\n sourceId?: string;\n ownerEmail?: string;\n status?: AgentRunFailureStatus | \"all\";\n regime?: AgentFailureRegime | \"all\";\n lookbackHours?: number;\n limit?: number;\n}) {\n const access = await resolveDebugAccess();\n const requestedSourceId = input.sourceId?.trim() || \"all\";\n const status = input.status ?? \"all\";\n const regime = input.regime ?? \"all\";\n const lookbackHours = Math.max(1, Math.min(720, input.lookbackHours ?? 168));\n const limit = Math.max(1, Math.min(100, input.limit ?? DEFAULT_SEARCH_LIMIT));\n const scope = ownerScope(access, input.ownerEmail, \"t.owner_email\");\n const cutoff = Date.now() - lookbackHours * 60 * 60 * 1000;\n\n let sources: ThreadDebugSourceConfig[];\n if (requestedSourceId === \"all\") {\n sources = sourceConfigs().filter(\n (source) => source.kind === \"current\" || access.canInspectAll,\n );\n } else {\n const configured = sourceConfigs().find(\n (source) => source.id === requestedSourceId,\n );\n const source = configured ?? resolveSourceConfig(requestedSourceId);\n assertSourceAccess(source, access);\n if (source.kind !== \"current\" && !source.databaseUrl) {\n throw new Error(\n `Thread debug source \"${requestedSourceId}\" is configured but disconnected.`,\n );\n }\n sources = [source];\n }\n\n const results = await Promise.all(\n sources.map(async (source) => {\n if (source.kind !== \"current\" && !source.databaseUrl) {\n return {\n failures: [] as ReturnType<typeof serializeRunFailure>[],\n health: sourceHealth(\n source,\n \"disconnected\",\n 0,\n \"thread_debug_source_disconnected\",\n ),\n };\n }\n try {\n const failures = await failuresForSource(source, scope, {\n status,\n regime,\n cutoff,\n limit,\n });\n return {\n failures,\n health: sourceHealth(source, \"ok\", failures.length, null),\n };\n } catch (error) {\n if (error instanceof UnsupportedThreadDebugSchemaError) {\n return {\n failures: [] as ReturnType<typeof serializeRunFailure>[],\n health: sourceHealth(\n source,\n \"unsupported\",\n 0,\n \"thread_debug_schema_unsupported\",\n ),\n };\n }\n return {\n failures: [] as ReturnType<typeof serializeRunFailure>[],\n health: sourceHealth(\n source,\n \"unavailable\",\n 0,\n \"thread_debug_source_unavailable\",\n ),\n };\n }\n }),\n );\n\n const failures = results\n .flatMap((result) => result.failures)\n .sort(\n (a, b) =>\n (b.completedAt ?? b.startedAt) - (a.completedAt ?? a.startedAt) ||\n b.id.localeCompare(a.id) ||\n b.source.id.localeCompare(a.source.id),\n )\n .slice(0, limit);\n\n return {\n sourceId: requestedSourceId,\n status,\n regime,\n lookbackHours,\n limit,\n count: failures.length,\n partial: results.some((result) => result.health.status !== \"ok\"),\n access: {\n viewerEmail: access.viewerEmail,\n scope: scope.label,\n canInspectAll: access.canInspectAll,\n },\n sources: results.map((result) => result.health),\n failures,\n };\n}\n\nexport async function searchAgentThreads(input: {\n sourceId?: string;\n query?: string;\n ownerEmail?: string;\n limit?: number;\n}) {\n const source = resolveSourceConfig(input.sourceId ?? \"current\");\n const access = await resolveDebugAccess();\n assertSourceAccess(source, access);\n const exec = await execForSource(source);\n const limit = Math.max(\n 1,\n Math.min(MAX_SEARCH_LIMIT, input.limit ?? DEFAULT_SEARCH_LIMIT),\n );\n const q = input.query?.trim() ?? \"\";\n const scope = ownerScope(access, input.ownerEmail);\n const where = [scope.sql];\n const args: unknown[] = [...scope.args];\n const runThreadIds = q\n ? (\n await optionalRows<{ thread_id: string }>(\n exec,\n \"SELECT thread_id FROM agent_runs WHERE id = ? LIMIT 1\",\n [q],\n )\n )\n .map((row) => String(row.thread_id ?? \"\").trim())\n .filter(Boolean)\n : [];\n if (q) {\n const pattern = \"%\" + escapeLike(q.toLowerCase()) + \"%\";\n const runIdClause =\n runThreadIds.length > 0\n ? \" OR id IN (\" + runThreadIds.map(() => \"?\").join(\", \") + \")\"\n : \"\";\n where.push(\n \"(LOWER(title) LIKE ? ESCAPE '\\\\' OR LOWER(preview) LIKE ? ESCAPE '\\\\' OR LOWER(owner_email) LIKE ? ESCAPE '\\\\' OR LOWER(thread_data) LIKE ? ESCAPE '\\\\'\" +\n runIdClause +\n \")\",\n );\n args.push(pattern, pattern, pattern, pattern);\n args.push(...runThreadIds);\n }\n args.push(limit);\n\n const rows = await optionalRows<ChatThreadRow>(\n exec,\n `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at\n FROM chat_threads\n WHERE ${where.join(\" AND \")}\n ORDER BY updated_at DESC\n LIMIT ?`,\n args,\n );\n return {\n source: {\n id: source.id,\n label: source.label,\n kind: source.kind,\n databaseUrlEnv: source.databaseUrlEnv ?? null,\n },\n access: {\n viewerEmail: access.viewerEmail,\n scope: scope.label,\n canInspectAll: access.canInspectAll,\n },\n query: q,\n count: rows.length,\n threads: rows.map((row) => serializeThreadSummary(row, q)),\n };\n}\n\nexport async function getAgentThreadDebug(input: {\n sourceId?: string;\n threadId?: string;\n runId?: string;\n ownerEmail?: string;\n maxRuns?: number;\n maxEvents?: number;\n maxTraceSpans?: number;\n}) {\n const source = resolveSourceConfig(input.sourceId ?? \"current\");\n const access = await resolveDebugAccess();\n assertSourceAccess(source, access);\n const exec = await execForSource(source);\n const scope = ownerScope(access, input.ownerEmail);\n const requestedId = input.runId?.trim() || input.threadId?.trim() || \"\";\n if (!requestedId) {\n fail(\"A thread ID or request/run ID is required.\", {\n errorCode: \"thread_id_required\",\n statusCode: 400,\n });\n }\n\n let rows = await queryRows<ChatThreadRow>(\n exec,\n `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at\n FROM chat_threads\n WHERE id = ? AND ${scope.sql}\n LIMIT 1`,\n [input.threadId?.trim() || requestedId, ...scope.args],\n );\n let resolvedRunId = input.runId?.trim() || null;\n\n if (!rows[0]) {\n const runRows = await optionalRows<{ id: string; thread_id: string }>(\n exec,\n `SELECT id, thread_id\n FROM agent_runs\n WHERE id = ?\n LIMIT 1`,\n [requestedId],\n );\n const threadId = runRows[0]?.thread_id\n ? String(runRows[0].thread_id).trim()\n : \"\";\n if (threadId) {\n rows = await queryRows<ChatThreadRow>(\n exec,\n `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at\n FROM chat_threads\n WHERE id = ? AND ${scope.sql}\n LIMIT 1`,\n [threadId, ...scope.args],\n );\n if (rows[0]) resolvedRunId = requestedId;\n }\n }\n\n const row = rows[0];\n if (!row) {\n fail(`Thread or request/run ID \"${requestedId}\" was not found.`, {\n errorCode: \"not_found\",\n statusCode: 404,\n });\n }\n\n const threadData = safeJsonParse<Record<string, unknown>>(\n row.thread_data,\n {},\n );\n const maxRuns = Math.max(1, Math.min(50, input.maxRuns ?? DEFAULT_RUN_LIMIT));\n const maxEvents = Math.max(\n 1,\n Math.min(2_000, input.maxEvents ?? DEFAULT_EVENT_LIMIT),\n );\n const maxTraceSpans = Math.max(\n 1,\n Math.min(2_000, input.maxTraceSpans ?? DEFAULT_TRACE_SPAN_LIMIT),\n );\n\n let runRows = await optionalRows<AgentRunRow>(\n exec,\n `SELECT r.*\n FROM agent_runs r\n WHERE r.thread_id = ?\n ORDER BY r.started_at DESC\n LIMIT ?`,\n [row.id, maxRuns],\n );\n\n // A deep-linked run can be older than the most recent `maxRuns` runs; fetch\n // it explicitly so the inspector opens the run someone was sent to debug\n // instead of silently falling back to the latest one.\n if (resolvedRunId && !runRows.some((run) => run.id === resolvedRunId)) {\n const lookupRunRows = await optionalRows<AgentRunRow>(\n exec,\n `SELECT r.*\n FROM agent_runs r\n WHERE r.thread_id = ? AND r.id = ?\n LIMIT 1`,\n [row.id, resolvedRunId],\n );\n if (lookupRunRows[0]) {\n runRows = [...runRows, lookupRunRows[0]].sort(\n (a, b) => Number(b.started_at) - Number(a.started_at),\n );\n }\n }\n\n const runs = [];\n for (const run of runRows) {\n const eventRows = await optionalRows<Record<string, unknown>>(\n exec,\n `SELECT run_id, seq, event_data\n FROM agent_run_events\n WHERE run_id = ?\n ORDER BY seq ASC\n LIMIT ?`,\n [run.id, maxEvents],\n );\n runs.push(serializeRun(run, eventRows.map(parseRunEvent)));\n }\n\n const runIds = runRows.map((run) => run.id);\n const runPlaceholders = runIds.map(() => \"?\").join(\", \");\n const traceSummaryRows = await optionalRows<Record<string, unknown>>(\n exec,\n runIds.length > 0\n ? `SELECT *\n FROM agent_trace_summaries\n WHERE thread_id = ? OR run_id IN (${runPlaceholders})\n ORDER BY created_at DESC\n LIMIT 50`\n : `SELECT *\n FROM agent_trace_summaries\n WHERE thread_id = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n runIds.length > 0 ? [row.id, ...runIds] : [row.id],\n );\n const traceSpanRows = await optionalRows<Record<string, unknown>>(\n exec,\n runIds.length > 0\n ? `SELECT *\n FROM agent_trace_spans\n WHERE thread_id = ? OR run_id IN (${runPlaceholders})\n ORDER BY created_at ASC\n LIMIT ?`\n : `SELECT *\n FROM agent_trace_spans\n WHERE thread_id = ?\n ORDER BY created_at ASC\n LIMIT ?`,\n runIds.length > 0\n ? [row.id, ...runIds, maxTraceSpans]\n : [row.id, maxTraceSpans],\n );\n const feedbackRows = await optionalRows<Record<string, unknown>>(\n exec,\n `SELECT *\n FROM agent_feedback\n WHERE thread_id = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n [row.id],\n );\n const satisfactionRows = await optionalRows<Record<string, unknown>>(\n exec,\n `SELECT *\n FROM agent_satisfaction_scores\n WHERE thread_id = ?\n ORDER BY computed_at DESC\n LIMIT 10`,\n [row.id],\n );\n const evalRows = await optionalRows<Record<string, unknown>>(\n exec,\n runIds.length > 0\n ? `SELECT *\n FROM agent_evals\n WHERE thread_id = ? OR run_id IN (${runPlaceholders})\n ORDER BY created_at DESC\n LIMIT 50`\n : `SELECT *\n FROM agent_evals\n WHERE thread_id = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n runIds.length > 0 ? [row.id, ...runIds] : [row.id],\n );\n const checkpointRows = await optionalRows<Record<string, unknown>>(\n exec,\n `SELECT id, thread_id, run_id, commit_sha, message, created_at\n FROM agent_checkpoints\n WHERE thread_id = ?\n ORDER BY created_at DESC\n LIMIT 50`,\n [row.id],\n );\n\n return {\n source: {\n id: source.id,\n label: source.label,\n kind: source.kind,\n databaseUrlEnv: source.databaseUrlEnv ?? null,\n },\n access: {\n viewerEmail: access.viewerEmail,\n scope: scope.label,\n canInspectAll: access.canInspectAll,\n },\n thread: {\n id: String(row.id),\n ownerEmail: String(row.owner_email ?? \"\"),\n title: String(row.title ?? \"\"),\n preview: String(row.preview ?? \"\"),\n messageCount: numberField(row.message_count),\n createdAt: numberField(row.created_at),\n updatedAt: numberField(row.updated_at),\n },\n lookup: {\n requestedId,\n threadId: String(row.id),\n runId: resolvedRunId,\n },\n messages: normalizeMessages(threadData),\n debug: (threadData as any)?._debug ?? null,\n debugRuns: Array.isArray((threadData as any)?._debugRuns)\n ? (threadData as any)._debugRuns\n : [],\n queuedMessages: (threadData as any)?.queuedMessages ?? [],\n threadData,\n rawThreadData: row.thread_data ?? \"\",\n runs,\n traces: {\n summaries: traceSummaryRows,\n spans: traceSpanRows,\n },\n feedback: feedbackRows,\n satisfaction: satisfactionRows,\n evals: evalRows,\n checkpoints: checkpointRows,\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-native/dispatch",
|
|
3
|
-
"version": "0.40.16
|
|
3
|
+
"version": "0.40.16",
|
|
4
4
|
"description": "Dispatch — workspace control plane for agent-native apps. Vault, integrations, destinations, scheduled jobs, and cross-app delegation, shipped as a single drop-in package.",
|
|
5
5
|
"homepage": "https://github.com/BuilderIO/agent-native#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
"tailwind-merge": "^3.5.0",
|
|
90
90
|
"vaul": "^1.1.2",
|
|
91
91
|
"zod": "^4.3.6",
|
|
92
|
-
"@agent-native/toolkit": "0.203.1
|
|
92
|
+
"@agent-native/toolkit": "0.203.1"
|
|
93
93
|
},
|
|
94
94
|
"devDependencies": {
|
|
95
95
|
"@react-router/dev": "^8.1.0",
|
|
@@ -103,10 +103,10 @@
|
|
|
103
103
|
"typescript-7": "npm:typescript@^7.0.2",
|
|
104
104
|
"vite": "8.1.0",
|
|
105
105
|
"vitest": "^4.1.5",
|
|
106
|
-
"@agent-native/core": "0.203.1
|
|
106
|
+
"@agent-native/core": "0.203.1"
|
|
107
107
|
},
|
|
108
108
|
"peerDependencies": {
|
|
109
|
-
"@agent-native/core": "0.
|
|
109
|
+
"@agent-native/core": ">=0.198.6",
|
|
110
110
|
"react": ">=19.2.7",
|
|
111
111
|
"react-dom": ">=19.2.7",
|
|
112
112
|
"react-router": ">=8"
|
|
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
|
|
|
11
11
|
workspaceOwnerEmails: [] as string[],
|
|
12
12
|
defaultOwnerEmail: undefined as string | undefined,
|
|
13
13
|
},
|
|
14
|
+
superOrgId: undefined as string | undefined,
|
|
14
15
|
}));
|
|
15
16
|
|
|
16
17
|
vi.mock("@agent-native/core/db", () => ({
|
|
@@ -19,7 +20,10 @@ vi.mock("@agent-native/core/db", () => ({
|
|
|
19
20
|
}));
|
|
20
21
|
|
|
21
22
|
vi.mock("@agent-native/core/server", () => ({
|
|
22
|
-
getAppConfig: () => ({
|
|
23
|
+
getAppConfig: () => ({
|
|
24
|
+
dispatch: mocks.dispatchConfig,
|
|
25
|
+
observability: { superOrgId: mocks.superOrgId },
|
|
26
|
+
}),
|
|
23
27
|
}));
|
|
24
28
|
|
|
25
29
|
vi.mock("./dispatch-store.js", () => ({
|
|
@@ -113,6 +117,7 @@ describe("thread-debug-store", () => {
|
|
|
113
117
|
mocks.dispatchConfig.adminEmails = [];
|
|
114
118
|
mocks.dispatchConfig.workspaceOwnerEmails = [];
|
|
115
119
|
mocks.dispatchConfig.defaultOwnerEmail = undefined;
|
|
120
|
+
mocks.superOrgId = undefined;
|
|
116
121
|
mocks.currentExecute.mockReset();
|
|
117
122
|
mocks.createDbExec.mockReset();
|
|
118
123
|
mocks.currentExecute.mockImplementation(async ({ sql, args }) => ({
|
|
@@ -427,6 +432,32 @@ describe("thread-debug-store", () => {
|
|
|
427
432
|
expect(mocks.createDbExec).not.toHaveBeenCalled();
|
|
428
433
|
});
|
|
429
434
|
|
|
435
|
+
it("lets super-org admins inspect owners outside the Dispatch roster", async () => {
|
|
436
|
+
mocks.orgId = "super-org";
|
|
437
|
+
mocks.superOrgId = "super-org";
|
|
438
|
+
mocks.currentExecute.mockImplementation(async ({ sql, args }) => {
|
|
439
|
+
if (sql.includes("SELECT role FROM org_members")) {
|
|
440
|
+
return { rows: [{ role: "admin" }] };
|
|
441
|
+
}
|
|
442
|
+
if (sql.includes("SELECT email FROM org_members")) {
|
|
443
|
+
return { rows: [{ email: "owner@example.com" }] };
|
|
444
|
+
}
|
|
445
|
+
if (sql.includes("FROM chat_threads")) {
|
|
446
|
+
return {
|
|
447
|
+
rows:
|
|
448
|
+
sql.includes("1 = 1") && args[0] === "thread-1"
|
|
449
|
+
? [{ ...thread, owner_email: "outsider@example.com" }]
|
|
450
|
+
: [],
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
return { rows: rowsForThreadLookup(sql, args) };
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
const result = await getAgentThreadDebug({ threadId: "thread-1" });
|
|
457
|
+
|
|
458
|
+
expect(result.thread.ownerEmail).toBe("outsider@example.com");
|
|
459
|
+
});
|
|
460
|
+
|
|
430
461
|
it("keeps explicit remote sources admin-only", async () => {
|
|
431
462
|
vi.stubEnv("REMOTE_DATABASE_URL", "postgres://remote/db");
|
|
432
463
|
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
type AgentFailureRegime,
|
|
5
5
|
} from "@agent-native/core/agent/engine";
|
|
6
6
|
import { createDbExec, getDbExec, type DbExec } from "@agent-native/core/db";
|
|
7
|
+
import { getAppConfig } from "@agent-native/core/server";
|
|
7
8
|
import { ForbiddenError } from "@agent-native/core/sharing";
|
|
8
9
|
|
|
9
10
|
import { isDispatchEnvironmentAdmin } from "./admin-config.js";
|
|
@@ -40,6 +41,7 @@ export interface DebugAccess {
|
|
|
40
41
|
orgId: string | null;
|
|
41
42
|
role: string | null;
|
|
42
43
|
envAdmin: boolean;
|
|
44
|
+
superOrg: boolean;
|
|
43
45
|
canInspectAll: boolean;
|
|
44
46
|
memberEmails: string[];
|
|
45
47
|
}
|
|
@@ -449,7 +451,12 @@ async function resolveDebugAccess(): Promise<DebugAccess> {
|
|
|
449
451
|
const orgId = currentOrgId();
|
|
450
452
|
const role = await viewerOrgRole(orgId, viewerEmail);
|
|
451
453
|
const envAdmin = isDispatchEnvironmentAdmin(viewerEmail);
|
|
452
|
-
const
|
|
454
|
+
const orgAdmin = role === "owner" || role === "admin";
|
|
455
|
+
const canInspectAll = envAdmin || orgAdmin;
|
|
456
|
+
// Remote sources keep their own org rosters, so Dispatch membership cannot
|
|
457
|
+
// scope them; the observability super org is the one cross-org review grant.
|
|
458
|
+
const superOrgId = getAppConfig().observability.superOrgId;
|
|
459
|
+
const superOrg = Boolean(orgId && orgAdmin && superOrgId === orgId);
|
|
453
460
|
const memberEmails = canInspectAll
|
|
454
461
|
? await currentOrgMembers(orgId)
|
|
455
462
|
: [viewerEmail];
|
|
@@ -458,6 +465,7 @@ async function resolveDebugAccess(): Promise<DebugAccess> {
|
|
|
458
465
|
orgId,
|
|
459
466
|
role,
|
|
460
467
|
envAdmin,
|
|
468
|
+
superOrg,
|
|
461
469
|
canInspectAll,
|
|
462
470
|
memberEmails: memberEmails.length > 0 ? memberEmails : [viewerEmail],
|
|
463
471
|
};
|
|
@@ -492,6 +500,7 @@ function ownerScope(
|
|
|
492
500
|
if (requested && requested !== "*") {
|
|
493
501
|
if (
|
|
494
502
|
access.orgId &&
|
|
503
|
+
!access.superOrg &&
|
|
495
504
|
!access.memberEmails.some(
|
|
496
505
|
(email) => email.toLowerCase() === requested.toLowerCase(),
|
|
497
506
|
)
|
|
@@ -508,6 +517,9 @@ function ownerScope(
|
|
|
508
517
|
};
|
|
509
518
|
}
|
|
510
519
|
|
|
520
|
+
if (access.superOrg) {
|
|
521
|
+
return { sql: "1 = 1", args: [], label: "all organizations" };
|
|
522
|
+
}
|
|
511
523
|
if (access.envAdmin && !access.orgId) {
|
|
512
524
|
return { sql: "1 = 1", args: [], label: "all users" };
|
|
513
525
|
}
|
|
@@ -598,6 +610,7 @@ export async function listThreadDebugSources(): Promise<{
|
|
|
598
610
|
orgId: access.orgId,
|
|
599
611
|
role: access.role,
|
|
600
612
|
envAdmin: access.envAdmin,
|
|
613
|
+
superOrg: access.superOrg,
|
|
601
614
|
canInspectAll: access.canInspectAll,
|
|
602
615
|
memberCount: access.memberEmails.length,
|
|
603
616
|
},
|