@agent-native/dispatch 0.20.4 → 0.22.0
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/dist/actions/get-agent-thread-debug.d.ts +2 -0
- package/dist/actions/provider-api-register.d.ts +7 -7
- package/dist/actions/search-agent-threads.js +2 -2
- package/dist/actions/search-agent-threads.js.map +1 -1
- package/dist/actions/start-workspace-app-creation.js +1 -1
- package/dist/actions/start-workspace-app-creation.js.map +1 -1
- package/dist/components/create-app-popover.d.ts.map +1 -1
- package/dist/components/create-app-popover.js +5 -71
- package/dist/components/create-app-popover.js.map +1 -1
- package/dist/components/layout/HeaderActions.d.ts +1 -17
- package/dist/components/layout/HeaderActions.d.ts.map +1 -1
- package/dist/components/layout/HeaderActions.js +1 -51
- package/dist/components/layout/HeaderActions.js.map +1 -1
- package/dist/components/layout/Layout.d.ts +23 -1
- package/dist/components/layout/Layout.d.ts.map +1 -1
- package/dist/components/layout/Layout.js +707 -18
- package/dist/components/layout/Layout.js.map +1 -1
- package/dist/components/ui/dialog.d.ts +1 -19
- package/dist/components/ui/dialog.d.ts.map +1 -1
- package/dist/components/ui/dialog.js +1 -22
- package/dist/components/ui/dialog.js.map +1 -1
- package/dist/components/ui/dropdown-menu.d.ts +1 -27
- package/dist/components/ui/dropdown-menu.d.ts.map +1 -1
- package/dist/components/ui/dropdown-menu.js +1 -35
- package/dist/components/ui/dropdown-menu.js.map +1 -1
- package/dist/components/ui/popover.d.ts +2 -1
- package/dist/components/ui/popover.d.ts.map +1 -1
- package/dist/components/ui/popover.js +2 -1
- package/dist/components/ui/popover.js.map +1 -1
- package/dist/components/ui/select.d.ts +1 -13
- package/dist/components/ui/select.d.ts.map +1 -1
- package/dist/components/ui/select.js +1 -26
- package/dist/components/ui/select.js.map +1 -1
- package/dist/hooks/use-mobile.d.ts +1 -1
- package/dist/hooks/use-mobile.d.ts.map +1 -1
- package/dist/hooks/use-mobile.js +1 -15
- package/dist/hooks/use-mobile.js.map +1 -1
- package/dist/lib/automation-display.js +1 -1
- package/dist/lib/automation-display.js.map +1 -1
- package/dist/lib/workspace-apps.d.ts +6 -0
- package/dist/lib/workspace-apps.d.ts.map +1 -1
- package/dist/lib/workspace-apps.js +21 -0
- package/dist/lib/workspace-apps.js.map +1 -1
- package/dist/routes/pages/settings.d.ts.map +1 -1
- package/dist/routes/pages/settings.js +21 -1
- package/dist/routes/pages/settings.js.map +1 -1
- package/dist/routes/pages/thread-debug.d.ts.map +1 -1
- package/dist/routes/pages/thread-debug.js +288 -118
- package/dist/routes/pages/thread-debug.js.map +1 -1
- package/dist/server/lib/app-creation-store.d.ts.map +1 -1
- package/dist/server/lib/app-creation-store.js +13 -0
- package/dist/server/lib/app-creation-store.js.map +1 -1
- package/dist/server/lib/thread-debug-store.d.ts +2 -0
- package/dist/server/lib/thread-debug-store.d.ts.map +1 -1
- package/dist/server/lib/thread-debug-store.js +6 -2
- package/dist/server/lib/thread-debug-store.js.map +1 -1
- package/dist/server/plugins/agent-chat.js +1 -0
- package/dist/server/plugins/agent-chat.js.map +1 -1
- package/dist/server/plugins/integrations.js +1 -1
- package/dist/server/plugins/integrations.js.map +1 -1
- package/package.json +3 -3
- package/src/actions/search-agent-threads.ts +2 -2
- package/src/actions/start-workspace-app-creation.ts +1 -1
- package/src/components/create-app-popover.spec.tsx +22 -0
- package/src/components/create-app-popover.tsx +30 -94
- package/src/components/layout/HeaderActions.tsx +1 -84
- package/src/components/layout/Layout.spec.tsx +35 -10
- package/src/components/layout/Layout.tsx +1394 -74
- package/src/components/ui/dialog.tsx +1 -120
- package/src/components/ui/dropdown-menu.tsx +1 -198
- package/src/components/ui/popover.tsx +3 -1
- package/src/components/ui/select.tsx +1 -158
- package/src/hooks/use-mobile.tsx +1 -21
- package/src/lib/automation-display.spec.ts +1 -1
- package/src/lib/automation-display.ts +1 -1
- package/src/lib/workspace-apps.ts +24 -0
- package/src/routes/pages/settings.tsx +72 -0
- package/src/routes/pages/thread-debug.spec.tsx +103 -5
- package/src/routes/pages/thread-debug.tsx +1051 -451
- package/src/server/lib/app-creation-store.spec.ts +13 -0
- package/src/server/lib/app-creation-store.ts +13 -0
- package/src/server/lib/mcp-gateway.spec.ts +18 -0
- package/src/server/lib/thread-debug-store.spec.ts +17 -0
- package/src/server/lib/thread-debug-store.ts +9 -2
- package/src/server/plugins/agent-chat.ts +1 -0
- package/src/server/plugins/integrations.ts +1 -1
- package/src/styles/dispatch.css +29 -0
|
@@ -177,6 +177,8 @@ export declare function getAgentThreadDebug(input: {
|
|
|
177
177
|
workerStage: string | null;
|
|
178
178
|
diagStage: string | null;
|
|
179
179
|
peakRssMb: number | null;
|
|
180
|
+
inFlightSince: number | null;
|
|
181
|
+
hasDispatchPayload: boolean;
|
|
180
182
|
events: any[];
|
|
181
183
|
}[];
|
|
182
184
|
traces: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-debug-store.d.ts","sourceRoot":"","sources":["../../../src/server/lib/thread-debug-store.ts"],"names":[],"mappings":"AAAA,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,oBAAoB,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,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,aAAa,EAAE,OAAO,CAAC;IACvB,YAA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AAS;QACT,KAAK;;;;;;GAOV"}
|
|
@@ -433,6 +433,10 @@ function serializeRun(row, events = []) {
|
|
|
433
433
|
workerStage: row.worker_stage ? String(row.worker_stage) : null,
|
|
434
434
|
diagStage: row.diag_stage ? String(row.diag_stage) : null,
|
|
435
435
|
peakRssMb: nullableNumberField(row.peak_rss_mb),
|
|
436
|
+
inFlightSince: nullableNumberField(row.in_flight_since),
|
|
437
|
+
hasDispatchPayload: row.dispatch_payload !== null &&
|
|
438
|
+
row.dispatch_payload !== undefined &&
|
|
439
|
+
String(row.dispatch_payload).length > 0,
|
|
436
440
|
events,
|
|
437
441
|
};
|
|
438
442
|
}
|
|
@@ -662,10 +666,10 @@ export async function searchAgentThreads(input) {
|
|
|
662
666
|
const runIdClause = runThreadIds.length > 0
|
|
663
667
|
? " OR id IN (" + runThreadIds.map(() => "?").join(", ") + ")"
|
|
664
668
|
: "";
|
|
665
|
-
where.push("(LOWER(title) LIKE ? ESCAPE '\\' OR LOWER(preview) LIKE ? ESCAPE '\\' OR LOWER(thread_data) LIKE ? ESCAPE '\\'" +
|
|
669
|
+
where.push("(LOWER(title) LIKE ? ESCAPE '\\' OR LOWER(preview) LIKE ? ESCAPE '\\' OR LOWER(owner_email) LIKE ? ESCAPE '\\' OR LOWER(thread_data) LIKE ? ESCAPE '\\'" +
|
|
666
670
|
runIdClause +
|
|
667
671
|
")");
|
|
668
|
-
args.push(pattern, pattern, pattern);
|
|
672
|
+
args.push(pattern, pattern, pattern, pattern);
|
|
669
673
|
args.push(...runThreadIds);
|
|
670
674
|
}
|
|
671
675
|
args.push(limit);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-debug-store.js","sourceRoot":"","sources":["../../../src/server/lib/thread-debug-store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,GAErB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAe,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAA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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 { 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 databaseAuthToken?: string;\n databaseUrlEnv?: string | null;\n databaseAuthTokenEnv?: 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 databaseAuthTokenEnv: 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}\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 envEmails(name: string): string[] {\n return (process.env[name] ?? \"\")\n .split(\",\")\n .map((value) => value.trim().toLowerCase())\n .filter(Boolean);\n}\n\nfunction escapeLike(value: string): string {\n return value.replace(/([\\\\%_])/g, \"\\\\$1\");\n}\n\nfunction isEnvAdmin(email: string): boolean {\n const normalized = email.trim().toLowerCase();\n return [\n ...envEmails(\"DISPATCH_ADMIN_EMAILS\"),\n ...envEmails(\"WORKSPACE_OWNER_EMAIL\"),\n ...envEmails(\"DISPATCH_DEFAULT_OWNER_EMAIL\"),\n ].includes(normalized);\n}\n\nfunction missingTableName(error: unknown): string | null {\n const message = String((error as Error)?.message ?? error);\n const patterns = [\n /no such table:\\s*(?:(?:main|public)\\.)?[\"'`]?([a-zA-Z_][\\w$]*)/i,\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 /unknown table\\s+[\"'`]?(?:[^\"'`.\\s]+\\.)?([a-zA-Z_][\\w$]*)/i,\n /undefined table[^a-zA-Z_]+(?:[^.\\s]+\\.)?([a-zA-Z_][\\w$]*)/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(String(value)) 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 databaseAuthTokenEnv =\n typeof entry.databaseAuthTokenEnv === \"string\"\n ? entry.databaseAuthTokenEnv.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 databaseAuthToken:\n typeof entry.databaseAuthToken === \"string\"\n ? entry.databaseAuthToken\n : databaseAuthTokenEnv\n ? process.env[databaseAuthTokenEnv]\n : undefined,\n databaseUrlEnv,\n databaseAuthTokenEnv,\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 const tokenEnv = `${prefix}_DATABASE_AUTH_TOKEN`;\n sources.push({\n id,\n label: labelFromSourceId(id),\n kind: \"env\",\n databaseUrl: value,\n databaseAuthToken: process.env[tokenEnv],\n databaseUrlEnv: key,\n databaseAuthTokenEnv: process.env[tokenEnv] ? tokenEnv : null,\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 databaseAuthTokenEnv: process.env.DATABASE_AUTH_TOKEN\n ? \"DATABASE_AUTH_TOKEN\"\n : null,\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 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 throw new Error(`Thread debug source \"${normalized}\" is not configured.`);\n }\n const tokenEnv = `${prefix}_DATABASE_AUTH_TOKEN`;\n return {\n id: normalized,\n label: labelFromSourceId(normalized),\n kind: \"env\",\n databaseUrl,\n databaseAuthToken: process.env[tokenEnv],\n databaseUrlEnv,\n databaseAuthTokenEnv: process.env[tokenEnv] ? tokenEnv : null,\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${source.databaseAuthToken ?? \"\"}`;\n if (!execCache.has(cacheKey)) {\n execCache.set(\n cacheKey,\n createDbExec({\n url: source.databaseUrl,\n authToken: source.databaseAuthToken,\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 WHERE org_id = ? AND LOWER(email) = ? 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 WHERE org_id = ?`,\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 = isEnvAdmin(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 throw new Error(\n \"The requested owner is not a member of the current organization.\",\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 events,\n };\n}\n\nfunction parseRunEvent(row: Record<string, unknown>) {\n const raw = String(row.event_data ?? \"\");\n return {\n runId: String(row.run_id ?? \"\"),\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 databaseAuthTokenEnv: source.databaseAuthTokenEnv ?? 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(String(value));\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(thread_data) LIKE ? ESCAPE '\\\\'\" +\n runIdClause +\n \")\",\n );\n args.push(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 throw new Error(\"A thread ID or request/run ID is required.\");\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 throw new Error(`Thread or request/run ID \"${requestedId}\" was not found.`);\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 const 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 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,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,YAAY,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAEtE,MAAM,cAAc,GAAG,qCAAqC,CAAC;AAC7D,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,oBA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":["import {\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 { 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 databaseAuthToken?: string;\n databaseUrlEnv?: string | null;\n databaseAuthTokenEnv?: 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 databaseAuthTokenEnv: 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 envEmails(name: string): string[] {\n return (process.env[name] ?? \"\")\n .split(\",\")\n .map((value) => value.trim().toLowerCase())\n .filter(Boolean);\n}\n\nfunction escapeLike(value: string): string {\n return value.replace(/([\\\\%_])/g, \"\\\\$1\");\n}\n\nfunction isEnvAdmin(email: string): boolean {\n const normalized = email.trim().toLowerCase();\n return [\n ...envEmails(\"DISPATCH_ADMIN_EMAILS\"),\n ...envEmails(\"WORKSPACE_OWNER_EMAIL\"),\n ...envEmails(\"DISPATCH_DEFAULT_OWNER_EMAIL\"),\n ].includes(normalized);\n}\n\nfunction missingTableName(error: unknown): string | null {\n const message = String((error as Error)?.message ?? error);\n const patterns = [\n /no such table:\\s*(?:(?:main|public)\\.)?[\"'`]?([a-zA-Z_][\\w$]*)/i,\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 /unknown table\\s+[\"'`]?(?:[^\"'`.\\s]+\\.)?([a-zA-Z_][\\w$]*)/i,\n /undefined table[^a-zA-Z_]+(?:[^.\\s]+\\.)?([a-zA-Z_][\\w$]*)/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(String(value)) 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 databaseAuthTokenEnv =\n typeof entry.databaseAuthTokenEnv === \"string\"\n ? entry.databaseAuthTokenEnv.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 databaseAuthToken:\n typeof entry.databaseAuthToken === \"string\"\n ? entry.databaseAuthToken\n : databaseAuthTokenEnv\n ? process.env[databaseAuthTokenEnv]\n : undefined,\n databaseUrlEnv,\n databaseAuthTokenEnv,\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 const tokenEnv = `${prefix}_DATABASE_AUTH_TOKEN`;\n sources.push({\n id,\n label: labelFromSourceId(id),\n kind: \"env\",\n databaseUrl: value,\n databaseAuthToken: process.env[tokenEnv],\n databaseUrlEnv: key,\n databaseAuthTokenEnv: process.env[tokenEnv] ? tokenEnv : null,\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 databaseAuthTokenEnv: process.env.DATABASE_AUTH_TOKEN\n ? \"DATABASE_AUTH_TOKEN\"\n : null,\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 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 throw new Error(`Thread debug source \"${normalized}\" is not configured.`);\n }\n const tokenEnv = `${prefix}_DATABASE_AUTH_TOKEN`;\n return {\n id: normalized,\n label: labelFromSourceId(normalized),\n kind: \"env\",\n databaseUrl,\n databaseAuthToken: process.env[tokenEnv],\n databaseUrlEnv,\n databaseAuthTokenEnv: process.env[tokenEnv] ? tokenEnv : null,\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${source.databaseAuthToken ?? \"\"}`;\n if (!execCache.has(cacheKey)) {\n execCache.set(\n cacheKey,\n createDbExec({\n url: source.databaseUrl,\n authToken: source.databaseAuthToken,\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 WHERE org_id = ? AND LOWER(email) = ? 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 WHERE org_id = ?`,\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 = isEnvAdmin(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 throw new Error(\n \"The requested owner is not a member of the current organization.\",\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 = String(row.event_data ?? \"\");\n return {\n runId: String(row.run_id ?? \"\"),\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 databaseAuthTokenEnv: source.databaseAuthTokenEnv ?? 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(String(value));\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 throw new Error(\"A thread ID or request/run ID is required.\");\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 throw new Error(`Thread or request/run ID \"${requestedId}\" was not found.`);\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 const 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 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"]}
|
|
@@ -62,6 +62,7 @@ Use the standard workspace primitives:
|
|
|
62
62
|
- Hosted/connected A2A neighbors such as Analytics and Content come from the available-apps context or list-connected-agents. list-workspace-apps only inventories apps mounted inside this workspace deployment; never use a missing row there to conclude that a connected agent is unavailable.
|
|
63
63
|
- When answering whether a mounted workspace app exposes an agent card or A2A endpoint, call list-workspace-apps with includeAgentCards=true. If you have not requested that probe, absence of agent-card fields means unchecked, not unavailable.
|
|
64
64
|
- When creating a new workspace app, create a separate app under apps/<app-id> with apps/<app-id>/package.json including a concise generated description, mount it at /<app-id>, use relative /<app-id> links, never hardcode localhost or dev ports, use shadcn/ui with @tabler/icons-react rather than lucide-react, and ensure the React Router client entry preserves APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath(). There is no separate workspace app registry to edit.
|
|
65
|
+
- When an explicit app-creation request already includes a source brief or a concrete repeatable workflow, call start-workspace-app-creation without asking non-blocking product or UX questions. Choose recommended defaults, let the Builder handoff record assumptions, and ask only for authorization, credentials, a destructive action, an ambiguous target workspace, or a genuinely missing workflow.
|
|
65
66
|
- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind.
|
|
66
67
|
- Treat first-party apps such as Mail, Calendar, Analytics, Brain, Assets, and Dispatch as existing hosted/connected neighbors available through links and A2A/default connected agents. Do not create wrapper apps, child apps, nested routes, or cloned template copies just to give a new app access to them; build only the genuinely new workflow and delegate cross-app work to those existing apps.
|
|
67
68
|
- Integration grants are not provider capability limits. For ad hoc provider inspection, querying, reporting, or troubleshooting, call provider-api-catalog/provider-api-docs, then provider-api-request against the provider's real HTTP API. Use connectionId for a specific shared grant and accountId for a specific OAuth account. Never expose secret values or silently widen app access while doing this.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-chat.js","sourceRoot":"","sources":["../../../src/server/plugins/agent-chat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAElE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,MAAM,kBAAkB,GAAG;IACzB,aAAa;IACb,qBAAqB;IACrB,uBAAuB;IACvB,SAAS;IACT,UAAU;IACV,0BAA0B;IAC1B,2BAA2B;IAC3B,2BAA2B;IAC3B,oBAAoB;IACpB,sBAAsB;IACtB,qBAAqB;IACrB,mBAAmB;IACnB,oBAAoB;IACpB,aAAa;IACb,8BAA8B;IAC9B,oCAAoC;IACpC,sBAAsB;IACtB,mBAAmB;IACnB,sBAAsB;IACtB,sBAAsB;IACtB,UAAU;CACX,CAAC;AAEF,eAAe,qBAAqB,CAAC;IACnC,KAAK,EAAE,UAAU;IACjB,qBAAqB,EAAE,IAAI;IAC3B,gBAAgB,EAAE,kBAAkB;IACpC,GAAG,EAAE;QACH,gBAAgB,EAAE;YAChB,oCAAoC;YACpC,8BAA8B;SAC/B;KACF;IACD,0EAA0E;IAC1E,2EAA2E;IAC3E,2EAA2E;IAC3E,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;QAC5B,MAAM,GAAG,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;QACvC,OAAO,GAAG,CAAC,KAAK,CAAC;IACnB,CAAC;IACD,2EAA2E;IAC3E,2EAA2E;IAC3E,wEAAwE;IACxE,OAAO,EAAE,eAAe;IACxB,aAAa,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE;IAC1C,YAAY,EAAE
|
|
1
|
+
{"version":3,"file":"agent-chat.js","sourceRoot":"","sources":["../../../src/server/plugins/agent-chat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAElE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,MAAM,kBAAkB,GAAG;IACzB,aAAa;IACb,qBAAqB;IACrB,uBAAuB;IACvB,SAAS;IACT,UAAU;IACV,0BAA0B;IAC1B,2BAA2B;IAC3B,2BAA2B;IAC3B,oBAAoB;IACpB,sBAAsB;IACtB,qBAAqB;IACrB,mBAAmB;IACnB,oBAAoB;IACpB,aAAa;IACb,8BAA8B;IAC9B,oCAAoC;IACpC,sBAAsB;IACtB,mBAAmB;IACnB,sBAAsB;IACtB,sBAAsB;IACtB,UAAU;CACX,CAAC;AAEF,eAAe,qBAAqB,CAAC;IACnC,KAAK,EAAE,UAAU;IACjB,qBAAqB,EAAE,IAAI;IAC3B,gBAAgB,EAAE,kBAAkB;IACpC,GAAG,EAAE;QACH,gBAAgB,EAAE;YAChB,oCAAoC;YACpC,8BAA8B;SAC/B;KACF;IACD,0EAA0E;IAC1E,2EAA2E;IAC3E,2EAA2E;IAC3E,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;QAC5B,MAAM,GAAG,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;QACvC,OAAO,GAAG,CAAC,KAAK,CAAC;IACnB,CAAC;IACD,2EAA2E;IAC3E,2EAA2E;IAC3E,wEAAwE;IACxE,OAAO,EAAE,eAAe;IACxB,aAAa,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE;IAC1C,YAAY,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;4EAyB4D;CAC3E,CAAC,CAAC","sourcesContent":["import { getOrgContext } from \"@agent-native/core/org\";\nimport { createAgentChatPlugin } from \"@agent-native/core/server\";\n\nimport { dispatchActions } from \"../../actions/index.js\";\n\nconst INITIAL_TOOL_NAMES = [\n \"view-screen\",\n \"list-workspace-apps\",\n \"list-connected-agents\",\n \"ask_app\",\n \"open_app\",\n \"list-workspace-resources\",\n \"create-workspace-resource\",\n \"update-workspace-resource\",\n \"list-vault-secrets\",\n \"request-vault-secret\",\n \"create-vault-secret\",\n \"list-destinations\",\n \"upsert-destination\",\n \"list-dreams\",\n \"start-workspace-app-creation\",\n \"list-available-workspace-templates\",\n \"provider-api-catalog\",\n \"provider-api-docs\",\n \"provider-api-request\",\n \"query-staged-dataset\",\n \"navigate\",\n];\n\nexport default createAgentChatPlugin({\n appId: \"dispatch\",\n durableBackgroundRuns: true,\n initialToolNames: INITIAL_TOOL_NAMES,\n mcp: {\n connectorCatalog: [\n \"resolve-integration-source-context\",\n \"start-workspace-app-creation\",\n ],\n },\n // Without this, AGENT_ORG_ID is never set on agent action calls and every\n // row written through the frontend (vault secrets, destinations, workspace\n // resources) lands with org_id=NULL — breaking data isolation across orgs.\n resolveOrgId: async (event) => {\n const ctx = await getOrgContext(event);\n return ctx.orgId;\n },\n // Read actions directly from the package's own action map rather than from\n // a build-time-generated `.generated/actions-registry.ts` (the latter is a\n // template-only construct that the Vite plugin emits next to actions/).\n actions: dispatchActions,\n codeExecution: { production: \"sandboxed\" },\n systemPrompt: `You are the central dispatch for this workspace.\n\nDefault posture:\n- Treat Slack and Telegram as shared entrypoints into the workspace.\n- Heavily delegate domain work to specialized agents through A2A when another app owns the job.\n- Keep durable memory and operating instructions in resources rather than ephemeral chat.\n- Prefer replying in the current external thread unless the user explicitly asks you to send to a saved destination.\n\nUse the standard workspace primitives:\n- Read and update resources like AGENTS.md, LEARNINGS.md, jobs/*.md, agents/*.md, and remote-agents/*.json when appropriate.\n- Use recurring jobs for scheduled behavior.\n- Use custom agent profiles in agents/*.md for local spawned work and remote-agents/*.json for remote A2A apps.\n- You receive a compact available-apps block with sibling workspace app names and descriptions. Use it to pick the right A2A target, and call list-connected-agents or tool-search only when you need fresh details.\n- Hosted/connected A2A neighbors such as Analytics and Content come from the available-apps context or list-connected-agents. list-workspace-apps only inventories apps mounted inside this workspace deployment; never use a missing row there to conclude that a connected agent is unavailable.\n- When answering whether a mounted workspace app exposes an agent card or A2A endpoint, call list-workspace-apps with includeAgentCards=true. If you have not requested that probe, absence of agent-card fields means unchecked, not unavailable.\n- When creating a new workspace app, create a separate app under apps/<app-id> with apps/<app-id>/package.json including a concise generated description, mount it at /<app-id>, use relative /<app-id> links, never hardcode localhost or dev ports, use shadcn/ui with @tabler/icons-react rather than lucide-react, and ensure the React Router client entry preserves APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath(). There is no separate workspace app registry to edit.\n- When an explicit app-creation request already includes a source brief or a concrete repeatable workflow, call start-workspace-app-creation without asking non-blocking product or UX questions. Choose recommended defaults, let the Builder handoff record assumptions, and ask only for authorization, credentials, a destructive action, an ambiguous target workspace, or a genuinely missing workflow.\n- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible \"Chat\", \"Starter\", \"Blank app\", or \"New app\" UI behind.\n- Treat first-party apps such as Mail, Calendar, Analytics, Brain, Assets, and Dispatch as existing hosted/connected neighbors available through links and A2A/default connected agents. Do not create wrapper apps, child apps, nested routes, or cloned template copies just to give a new app access to them; build only the genuinely new workflow and delegate cross-app work to those existing apps.\n- Integration grants are not provider capability limits. For ad hoc provider inspection, querying, reporting, or troubleshooting, call provider-api-catalog/provider-api-docs, then provider-api-request against the provider's real HTTP API. Use connectionId for a specific shared grant and accountId for a specific OAuth account. Never expose secret values or silently widen app access while doing this.\n- For broad provider searches, joins, classification, corpus counts, or absence claims, fetch every relevant page or an explicitly bounded cohort, stage/save large responses with stageAs/saveToFile/fetchAllPages, and reduce them with query-staged-dataset or run-code. Report source, filters, row counts, pagination, truncation, failed pages, and uncovered gaps.\n\nWhen a user asks for something like a digest, reminder, routing rule, or saved behavior:\n- First decide whether it should be a resource, a recurring job, a destination, or a delegated task.\n- Keep responses concise and operational.\n- Avoid inventing integrations or destinations that are not configured yet.`,\n});\n"]}
|
|
@@ -36,7 +36,7 @@ When a user asks for something:
|
|
|
36
36
|
- If the user asks to create, build, make, scaffold, or generate an "agent" from Dispatch chat or by tagging @agent-native in Slack, email, or Telegram, first classify the ask. If it is a simple Dispatch-native behavior like a reminder, digest, monitor, routing rule, saved instruction, or recurring workflow, create or update the recurring job/resource/destination in Dispatch. If it is a robust unique product or teammate that needs its own UI, data model, actions, integrations, or domain workflow, treat it as a new workspace app and call start-workspace-app-creation.
|
|
37
37
|
- If a new-app prompt asks for access to Mail, Calendar, Analytics, Brain, Assets, or similar first-party app data/agents, keep using the existing hosted/connected app and A2A path. Do not ask Builder to scaffold those apps as children of the new app unless the user explicitly asks for a customized app from that template.
|
|
38
38
|
- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind.
|
|
39
|
-
- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. If the request is too vague to classify, ask one concise follow-up. If the action returns mode "builder", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH
|
|
39
|
+
- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. When the prompt contains a source brief or concrete repeatable workflow, choose recommended defaults and do not ask non-blocking product or UX questions; ask only for authorization, credentials, a destructive action, an ambiguous target workspace, or a genuinely missing workflow. If the request is too vague to classify, ask one concise follow-up. If the action returns mode "builder", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode "local-agent", tell the user it is ready for the local code agent and include the returned app path/prompt summary. Dispatch reuses the connected workspace Builder project or provisions it through the Builder Projects API when an organization owner/admin starts the first app; members need an owner/admin to configure the project first. Do not ask the user to use Builder org/beta settings. If it returns mode "builder-unavailable", the action also returns a \`reason\` code plus a user-facing \`message\` and (for some reasons) an operator-facing \`detail\`. Relay the \`message\` to the user as-is; only surface \`detail\` when the user is clearly an operator debugging the deployment (e.g. troubleshooting a broken Builder connection for the workspace), never as routine detail for an end user.
|
|
40
40
|
- For digests, reminders, or saved behavior, prefer recurring jobs, resources, or destinations over chat replies.
|
|
41
41
|
- Keep responses concise and operational — messaging platforms have character limits.
|
|
42
42
|
- Use markdown sparingly (bold and lists are fine, avoid complex formatting).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integrations.js","sourceRoot":"","sources":["../../../src/server/plugins/integrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAErE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EACL,qBAAqB,EACrB,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AAEzC,MAAM,0BAA0B,GAAG;IACjC,GAAG,eAAe;IAClB,2EAA2E;IAC3E,6EAA6E;IAC7E,6EAA6E;IAC7E,OAAO,EAAE;QACP,GAAG,eAAe,CAAC,OAAO;QAC1B,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAEF,MAAM,kCAAkC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;4FA4BiD,CAAC;AAE7F;;;;GAIG;AACH,MAAM,0BAA0B,GAAG,KAAK,EAAE,QAAa,EAAE,EAAE;IACzD,MAAM,EAAE,YAAY,GAAG,EAAE,EAAE,GAAG,iBAAiB,EAAE,CAAC;IAClD,MAAM,cAAc,GAAG,YAAY,CAAC,YAAY,CAAC;IACjD,MAAM,YAAY,GAChB,OAAO,cAAc,KAAK,QAAQ;QAChC,CAAC,CAAC,cAAc;QAChB,CAAC,CAAC,OAAO,cAAc,KAAK,UAAU;YACpC,CAAC,CAAC,cAAc,CAAC,kCAAkC,CAAC;YACpD,CAAC,CAAC,kCAAkC,CAAC;IAE3C,MAAM,MAAM,GAAG,wBAAwB,CAAC;QACtC,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,0BAA0B;QACnC,uBAAuB,EAAE,+BAA+B;QACxD,aAAa,EAAE,qBAAqB;QACpC,YAAY;QACZ,wDAAwD;QACxD,yEAAyE;QACzE,+DAA+D;QAC/D,6EAA6E;KAC9E,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC1B,CAAC,CAAC;AAEF,eAAe,0BAA0B,CAAC","sourcesContent":["import { createIntegrationsPlugin } from \"@agent-native/core/server\";\n\nimport { dispatchActions } from \"../../actions/index.js\";\nimport { getDispatchConfig } from \"../index.js\";\nimport {\n beforeDispatchProcess,\n resolveDispatchExecutionContext,\n} from \"../lib/dispatch-integrations.js\";\n\nconst dispatchIntegrationActions = {\n ...dispatchActions,\n // Messaging integrations should use the core call-agent tool for cross-app\n // delegation because it queues A2A continuations when serverless budgets are\n // tight. The MCP-facing ask_app action is still available outside this path.\n ask_app: {\n ...dispatchActions.ask_app,\n agentTool: false,\n },\n};\n\nconst DISPATCH_INTEGRATION_SYSTEM_PROMPT = `You are the central dispatch for this workspace, responding via a messaging platform integration (Slack, Telegram, email, etc.).\n\nDefault posture:\n- Treat Slack, Telegram, and email as shared entrypoints into the workspace.\n- Heavily delegate domain work to specialized agents through A2A (call-agent) when another app owns the job. Apps you can delegate to include slides (decks/presentations), analytics (data/dashboards), content (docs/articles), forms (form builder), clips (screen recordings), design (visual designs), and assets (brand libraries plus generated images/videos).\n- Use the available-apps prompt context first, then list-connected-agents when you need fresh details, to see what agents are available before assuming a request must be handled locally.\n- Hosted/connected A2A neighbors such as Analytics and Content come from the available-apps context or list-connected-agents. list-workspace-apps only inventories apps mounted inside this workspace deployment; never use a missing row there to conclude that a connected agent is unavailable.\n- When asked whether a mounted workspace app exposes an agent card or A2A endpoint, call list-workspace-apps with includeAgentCards=true. Without that probe, missing agent-card fields mean unchecked, not unavailable.\n- Treat first-party apps such as Mail, Calendar, Analytics, Brain, Assets, and Dispatch as existing hosted/connected neighbors available through links and A2A/default connected agents. Do not create wrapper apps, child apps, nested routes, or cloned template copies just to give a new app access to them; build only the genuinely new workflow and delegate cross-app work to those existing apps.\n- Integration grants are not provider capability limits. For ad hoc provider inspection, querying, reporting, or troubleshooting, call provider-api-catalog/provider-api-docs, then provider-api-request against the provider's real HTTP API. Use connectionId for a specific shared grant and accountId for a specific OAuth account. Never expose secret values or silently widen app access while doing this.\n- Keep durable memory and operating instructions in resources rather than ephemeral chat.\n- Reply in the originating thread unless the user explicitly asks you to send to a saved destination.\n\nWhen a user asks for something:\n- If it belongs to analytics, content, slides, clips, assets, etc., delegate via call-agent — do not re-implement the domain logic in dispatch.\n- Synthetic uptime, health-check, and URL-availability monitors belong to Analytics, even when the monitored target is another app such as Clips. Delegate creation to Analytics and relay its exact monitor URL. Dispatch-native recurring jobs are for reminders, digests, and agent workflows, not HTTP uptime probes.\n- Route by the requested artifact type, not by organization-specific names stored in code. For structured records, databases, tables, queues, boards, and intake forms, resolve the owning app and canonical destination from loaded workspace instructions/resources plus discovered app capabilities; do not assume Content, a database ID, schema, owner, or required fields. Visual designs, mockups, wireframes, screens, and interfaces belong to Design. A trusted Required target agent hint in integration context is authoritative.\n- When delegating structured intake to the resolved owning app, preserve the exact Source thread URL and the workspace instruction context, inspect the destination's current required fields, ask only for missing values, submit once, verify the saved record, and return the exact link.\n- In messaging integrations, use call-agent for cross-app delegation; do not use ask_app.\n- After call-agent returns an answer, RELAY IT DIRECTLY to the user with at most a one-line preface — do not rephrase, summarize, or add commentary. The downstream agent already crafted the answer; your job is delivery, not editing. This minimizes round-trips and keeps the user-visible reply fast.\n- Exception: if the downstream agent reports a missing model/provider credential, do not name exact env vars, Vault keys, tokens, or secrets. Say the target app needs an LLM connection and recommend connecting Builder/managed LLM for that app; keep bring-your-own provider keys as a secondary option only if the user asks.\n- If the user asks to create, build, make, scaffold, or generate an \"agent\" from Dispatch chat or by tagging @agent-native in Slack, email, or Telegram, first classify the ask. If it is a simple Dispatch-native behavior like a reminder, digest, monitor, routing rule, saved instruction, or recurring workflow, create or update the recurring job/resource/destination in Dispatch. If it is a robust unique product or teammate that needs its own UI, data model, actions, integrations, or domain workflow, treat it as a new workspace app and call start-workspace-app-creation.\n- If a new-app prompt asks for access to Mail, Calendar, Analytics, Brain, Assets, or similar first-party app data/agents, keep using the existing hosted/connected app and A2A path. Do not ask Builder to scaffold those apps as children of the new app unless the user explicitly asks for a customized app from that template.\n- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible \"Chat\", \"Starter\", \"Blank app\", or \"New app\" UI behind.\n- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. If the request is too vague to classify, ask one concise follow-up. If the action returns mode \"builder\", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH via appBasePath() in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode \"local-agent\", tell the user it is ready for the local code agent and include the returned app path/prompt summary. Dispatch reuses the connected workspace Builder project or provisions it through the Builder Projects API when an organization owner/admin starts the first app; members need an owner/admin to configure the project first. Do not ask the user to use Builder org/beta settings. If it returns mode \"builder-unavailable\", the action also returns a \\`reason\\` code plus a user-facing \\`message\\` and (for some reasons) an operator-facing \\`detail\\`. Relay the \\`message\\` to the user as-is; only surface \\`detail\\` when the user is clearly an operator debugging the deployment (e.g. troubleshooting a broken Builder connection for the workspace), never as routine detail for an end user.\n- For digests, reminders, or saved behavior, prefer recurring jobs, resources, or destinations over chat replies.\n- Keep responses concise and operational — messaging platforms have character limits.\n- Use markdown sparingly (bold and lists are fine, avoid complex formatting).\n- If a task requires many steps, summarize what you did rather than streaming every detail.`;\n\n/**\n * Defer plugin construction until the Nitro plugin actually fires so the\n * config-aware system prompt resolves AFTER `setupDispatch(config)` has\n * stamped the active config (plugin module load order is not guaranteed).\n */\nconst dispatchIntegrationsPlugin = async (nitroApp: any) => {\n const { integrations = {} } = getDispatchConfig();\n const promptOverride = integrations.systemPrompt;\n const systemPrompt =\n typeof promptOverride === \"string\"\n ? promptOverride\n : typeof promptOverride === \"function\"\n ? promptOverride(DISPATCH_INTEGRATION_SYSTEM_PROMPT)\n : DISPATCH_INTEGRATION_SYSTEM_PROMPT;\n\n const plugin = createIntegrationsPlugin({\n appId: \"dispatch\",\n actions: dispatchIntegrationActions,\n resolveExecutionContext: resolveDispatchExecutionContext,\n beforeProcess: beforeDispatchProcess,\n systemPrompt,\n // Inherit the framework default (claude-sonnet-4-6 from\n // packages/core/src/integrations/plugin.ts). Haiku was tried for latency\n // but hallucinated URLs/IDs after delegated call-agent results\n // (e.g. inventing `https://slides.workspace.com/deck/builder-io-deck-2024`).\n });\n\n return plugin(nitroApp);\n};\n\nexport default dispatchIntegrationsPlugin;\n"]}
|
|
1
|
+
{"version":3,"file":"integrations.js","sourceRoot":"","sources":["../../../src/server/plugins/integrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAErE,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EACL,qBAAqB,EACrB,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AAEzC,MAAM,0BAA0B,GAAG;IACjC,GAAG,eAAe;IAClB,2EAA2E;IAC3E,6EAA6E;IAC7E,6EAA6E;IAC7E,OAAO,EAAE;QACP,GAAG,eAAe,CAAC,OAAO;QAC1B,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAEF,MAAM,kCAAkC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;4FA4BiD,CAAC;AAE7F;;;;GAIG;AACH,MAAM,0BAA0B,GAAG,KAAK,EAAE,QAAa,EAAE,EAAE;IACzD,MAAM,EAAE,YAAY,GAAG,EAAE,EAAE,GAAG,iBAAiB,EAAE,CAAC;IAClD,MAAM,cAAc,GAAG,YAAY,CAAC,YAAY,CAAC;IACjD,MAAM,YAAY,GAChB,OAAO,cAAc,KAAK,QAAQ;QAChC,CAAC,CAAC,cAAc;QAChB,CAAC,CAAC,OAAO,cAAc,KAAK,UAAU;YACpC,CAAC,CAAC,cAAc,CAAC,kCAAkC,CAAC;YACpD,CAAC,CAAC,kCAAkC,CAAC;IAE3C,MAAM,MAAM,GAAG,wBAAwB,CAAC;QACtC,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,0BAA0B;QACnC,uBAAuB,EAAE,+BAA+B;QACxD,aAAa,EAAE,qBAAqB;QACpC,YAAY;QACZ,wDAAwD;QACxD,yEAAyE;QACzE,+DAA+D;QAC/D,6EAA6E;KAC9E,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC1B,CAAC,CAAC;AAEF,eAAe,0BAA0B,CAAC","sourcesContent":["import { createIntegrationsPlugin } from \"@agent-native/core/server\";\n\nimport { dispatchActions } from \"../../actions/index.js\";\nimport { getDispatchConfig } from \"../index.js\";\nimport {\n beforeDispatchProcess,\n resolveDispatchExecutionContext,\n} from \"../lib/dispatch-integrations.js\";\n\nconst dispatchIntegrationActions = {\n ...dispatchActions,\n // Messaging integrations should use the core call-agent tool for cross-app\n // delegation because it queues A2A continuations when serverless budgets are\n // tight. The MCP-facing ask_app action is still available outside this path.\n ask_app: {\n ...dispatchActions.ask_app,\n agentTool: false,\n },\n};\n\nconst DISPATCH_INTEGRATION_SYSTEM_PROMPT = `You are the central dispatch for this workspace, responding via a messaging platform integration (Slack, Telegram, email, etc.).\n\nDefault posture:\n- Treat Slack, Telegram, and email as shared entrypoints into the workspace.\n- Heavily delegate domain work to specialized agents through A2A (call-agent) when another app owns the job. Apps you can delegate to include slides (decks/presentations), analytics (data/dashboards), content (docs/articles), forms (form builder), clips (screen recordings), design (visual designs), and assets (brand libraries plus generated images/videos).\n- Use the available-apps prompt context first, then list-connected-agents when you need fresh details, to see what agents are available before assuming a request must be handled locally.\n- Hosted/connected A2A neighbors such as Analytics and Content come from the available-apps context or list-connected-agents. list-workspace-apps only inventories apps mounted inside this workspace deployment; never use a missing row there to conclude that a connected agent is unavailable.\n- When asked whether a mounted workspace app exposes an agent card or A2A endpoint, call list-workspace-apps with includeAgentCards=true. Without that probe, missing agent-card fields mean unchecked, not unavailable.\n- Treat first-party apps such as Mail, Calendar, Analytics, Brain, Assets, and Dispatch as existing hosted/connected neighbors available through links and A2A/default connected agents. Do not create wrapper apps, child apps, nested routes, or cloned template copies just to give a new app access to them; build only the genuinely new workflow and delegate cross-app work to those existing apps.\n- Integration grants are not provider capability limits. For ad hoc provider inspection, querying, reporting, or troubleshooting, call provider-api-catalog/provider-api-docs, then provider-api-request against the provider's real HTTP API. Use connectionId for a specific shared grant and accountId for a specific OAuth account. Never expose secret values or silently widen app access while doing this.\n- Keep durable memory and operating instructions in resources rather than ephemeral chat.\n- Reply in the originating thread unless the user explicitly asks you to send to a saved destination.\n\nWhen a user asks for something:\n- If it belongs to analytics, content, slides, clips, assets, etc., delegate via call-agent — do not re-implement the domain logic in dispatch.\n- Synthetic uptime, health-check, and URL-availability monitors belong to Analytics, even when the monitored target is another app such as Clips. Delegate creation to Analytics and relay its exact monitor URL. Dispatch-native recurring jobs are for reminders, digests, and agent workflows, not HTTP uptime probes.\n- Route by the requested artifact type, not by organization-specific names stored in code. For structured records, databases, tables, queues, boards, and intake forms, resolve the owning app and canonical destination from loaded workspace instructions/resources plus discovered app capabilities; do not assume Content, a database ID, schema, owner, or required fields. Visual designs, mockups, wireframes, screens, and interfaces belong to Design. A trusted Required target agent hint in integration context is authoritative.\n- When delegating structured intake to the resolved owning app, preserve the exact Source thread URL and the workspace instruction context, inspect the destination's current required fields, ask only for missing values, submit once, verify the saved record, and return the exact link.\n- In messaging integrations, use call-agent for cross-app delegation; do not use ask_app.\n- After call-agent returns an answer, RELAY IT DIRECTLY to the user with at most a one-line preface — do not rephrase, summarize, or add commentary. The downstream agent already crafted the answer; your job is delivery, not editing. This minimizes round-trips and keeps the user-visible reply fast.\n- Exception: if the downstream agent reports a missing model/provider credential, do not name exact env vars, Vault keys, tokens, or secrets. Say the target app needs an LLM connection and recommend connecting Builder/managed LLM for that app; keep bring-your-own provider keys as a secondary option only if the user asks.\n- If the user asks to create, build, make, scaffold, or generate an \"agent\" from Dispatch chat or by tagging @agent-native in Slack, email, or Telegram, first classify the ask. If it is a simple Dispatch-native behavior like a reminder, digest, monitor, routing rule, saved instruction, or recurring workflow, create or update the recurring job/resource/destination in Dispatch. If it is a robust unique product or teammate that needs its own UI, data model, actions, integrations, or domain workflow, treat it as a new workspace app and call start-workspace-app-creation.\n- If a new-app prompt asks for access to Mail, Calendar, Analytics, Brain, Assets, or similar first-party app data/agents, keep using the existing hosted/connected app and A2A path. Do not ask Builder to scaffold those apps as children of the new app unless the user explicitly asks for a customized app from that template.\n- If the chat template is used, treat it as scaffolding only: the finished app must be branded as the requested app with its own home screen/navigation/package metadata/manifest, and must not leave visible \"Chat\", \"Starter\", \"Blank app\", or \"New app\" UI behind.\n- If the user explicitly asks for a new app or workspace app, call start-workspace-app-creation with their prompt and include a concise generated description by default. Do not satisfy a new-app request by adding a route, page, component, or file inside apps/chat or another existing app unless the user explicitly asks to modify that existing app. When the prompt contains a source brief or concrete repeatable workflow, choose recommended defaults and do not ask non-blocking product or UX questions; ask only for authorization, credentials, a destructive action, an ambiguous target workspace, or a genuinely missing workflow. If the request is too vague to classify, ask one concise follow-up. If the action returns mode \"builder\", reply with the Builder branch URL; Builder is responsible for creating the separate workspace app under apps/<app-id>, mounting it at /<app-id>, ensuring apps/<app-id>/package.json exists with name/displayName and description so Dispatch discovers it, using relative /<app-id> links instead of hardcoded localhost/dev ports, and preserving APP_BASE_PATH/VITE_APP_BASE_PATH in the React Router client entry. The new app lives at the workspace root /<app-id>, NOT under /dispatch/<app-id>, /apps/<app-id>, or any other Dispatch tab — when telling the user where to find it, link to /<app-id> only. There is no separate workspace app registry to edit. If it returns mode \"local-agent\", tell the user it is ready for the local code agent and include the returned app path/prompt summary. Dispatch reuses the connected workspace Builder project or provisions it through the Builder Projects API when an organization owner/admin starts the first app; members need an owner/admin to configure the project first. Do not ask the user to use Builder org/beta settings. If it returns mode \"builder-unavailable\", the action also returns a \\`reason\\` code plus a user-facing \\`message\\` and (for some reasons) an operator-facing \\`detail\\`. Relay the \\`message\\` to the user as-is; only surface \\`detail\\` when the user is clearly an operator debugging the deployment (e.g. troubleshooting a broken Builder connection for the workspace), never as routine detail for an end user.\n- For digests, reminders, or saved behavior, prefer recurring jobs, resources, or destinations over chat replies.\n- Keep responses concise and operational — messaging platforms have character limits.\n- Use markdown sparingly (bold and lists are fine, avoid complex formatting).\n- If a task requires many steps, summarize what you did rather than streaming every detail.`;\n\n/**\n * Defer plugin construction until the Nitro plugin actually fires so the\n * config-aware system prompt resolves AFTER `setupDispatch(config)` has\n * stamped the active config (plugin module load order is not guaranteed).\n */\nconst dispatchIntegrationsPlugin = async (nitroApp: any) => {\n const { integrations = {} } = getDispatchConfig();\n const promptOverride = integrations.systemPrompt;\n const systemPrompt =\n typeof promptOverride === \"string\"\n ? promptOverride\n : typeof promptOverride === \"function\"\n ? promptOverride(DISPATCH_INTEGRATION_SYSTEM_PROMPT)\n : DISPATCH_INTEGRATION_SYSTEM_PROMPT;\n\n const plugin = createIntegrationsPlugin({\n appId: \"dispatch\",\n actions: dispatchIntegrationActions,\n resolveExecutionContext: resolveDispatchExecutionContext,\n beforeProcess: beforeDispatchProcess,\n systemPrompt,\n // Inherit the framework default (claude-sonnet-4-6 from\n // packages/core/src/integrations/plugin.ts). Haiku was tried for latency\n // but hallucinated URLs/IDs after delegated call-agent results\n // (e.g. inventing `https://slides.workspace.com/deck/builder-io-deck-2024`).\n });\n\n return plugin(nitroApp);\n};\n\nexport default dispatchIntegrationsPlugin;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-native/dispatch",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.0",
|
|
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": {
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
"tailwind-merge": "^3.5.0",
|
|
85
85
|
"vaul": "^1.1.2",
|
|
86
86
|
"zod": "^4.3.6",
|
|
87
|
-
"@agent-native/toolkit": "0.13.
|
|
87
|
+
"@agent-native/toolkit": "0.13.7"
|
|
88
88
|
},
|
|
89
89
|
"devDependencies": {
|
|
90
90
|
"@react-router/dev": "^8.1.0",
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
"typescript-7": "npm:typescript@^7.0.2",
|
|
99
99
|
"vite": "8.1.0",
|
|
100
100
|
"vitest": "^4.1.5",
|
|
101
|
-
"@agent-native/core": "0.
|
|
101
|
+
"@agent-native/core": "0.148.0"
|
|
102
102
|
},
|
|
103
103
|
"peerDependencies": {
|
|
104
104
|
"@agent-native/core": ">=0.8.0",
|
|
@@ -5,7 +5,7 @@ import { searchAgentThreads } from "../server/lib/thread-debug-store.js";
|
|
|
5
5
|
|
|
6
6
|
export default defineAction({
|
|
7
7
|
description:
|
|
8
|
-
"Search agent chat threads by title, preview, full persisted thread content, or an exact request/run ID. Non-admins are limited to their own current Dispatch DB threads.",
|
|
8
|
+
"Search agent chat threads by title, owner email, preview, full persisted thread content, or an exact request/run ID. Non-admins are limited to their own current Dispatch DB threads.",
|
|
9
9
|
schema: z.object({
|
|
10
10
|
sourceId: z
|
|
11
11
|
.string()
|
|
@@ -15,7 +15,7 @@ export default defineAction({
|
|
|
15
15
|
.string()
|
|
16
16
|
.optional()
|
|
17
17
|
.describe(
|
|
18
|
-
"Full-text search term matched against title, preview, and thread data.",
|
|
18
|
+
"Full-text search term matched against title, owner email, preview, and thread data.",
|
|
19
19
|
),
|
|
20
20
|
ownerEmail: z
|
|
21
21
|
.string()
|
|
@@ -6,7 +6,7 @@ import { startWorkspaceAppCreation } from "../server/lib/app-creation-store.js";
|
|
|
6
6
|
|
|
7
7
|
export default defineAction({
|
|
8
8
|
description:
|
|
9
|
-
'Start creating a new workspace app from Dispatch when the request truly needs its own app. For Claude Web, ChatGPT Web, or either host\'s web Project, this action is the Builder handoff: call it after forming a bounded source brief and do not scaffold or edit files in the host sandbox. Callers should include a concise generated description by default; Dispatch generates one from the prompt when omitted. In local dev this returns a code-agent prompt; in production it reuses the connected Agent-Native workspace project or, for an organization owner/admin, provisions it through the Builder Projects API before starting the Builder Cloud Agent branch. If no project is configured, organization members must ask an owner/admin to configure it first. The result must be a separate workspace app under apps/<app-id>, not a new route or file in apps/chat. If chat is used as the source template, the finished app must be branded as the requested app and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind. If the request needs Mail, Calendar, Analytics, Brain, Assets, or another first-party app, use the existing hosted/connected app via links or A2A; do not wrap or nest those apps inside the new app unless the user explicitly asks for a customized app from that template.',
|
|
9
|
+
'Start creating a new workspace app from Dispatch when the request truly needs its own app. For Claude Web, ChatGPT Web, or either host\'s web Project, this action is the Builder handoff: call it after forming a bounded source brief and do not scaffold or edit files in the host sandbox. This handoff is autonomous once the brief exists: do not ask the user for non-blocking product or UX choices; choose recommended defaults and let Builder record assumptions while it implements. Callers should include a concise generated description by default; Dispatch generates one from the prompt when omitted. In local dev this returns a code-agent prompt; in production it reuses the connected Agent-Native workspace project or, for an organization owner/admin, provisions it through the Builder Projects API before starting the Builder Cloud Agent branch. If no project is configured, organization members must ask an owner/admin to configure it first. The result must be a separate workspace app under apps/<app-id>, not a new route or file in apps/chat. If chat is used as the source template, the finished app must be branded as the requested app and must not leave visible "Chat", "Starter", "Blank app", or "New app" UI behind. If the request needs Mail, Calendar, Analytics, Brain, Assets, or another first-party app, use the existing hosted/connected app via links or A2A; do not wrap or nest those apps inside the new app unless the user explicitly asks for a customized app from that template.',
|
|
10
10
|
schema: z.object({
|
|
11
11
|
prompt: z.string().min(1).describe("The user's app creation request"),
|
|
12
12
|
appId: z
|
|
@@ -189,6 +189,28 @@ describe("CreateAppFlow", () => {
|
|
|
189
189
|
connectButton.click();
|
|
190
190
|
});
|
|
191
191
|
expect(builderConnectFlowState.start).toHaveBeenCalledTimes(1);
|
|
192
|
+
const localLink = container.querySelector<HTMLAnchorElement>(
|
|
193
|
+
"[data-create-app-local-link]",
|
|
194
|
+
);
|
|
195
|
+
expect(localLink?.textContent).toContain("Create locally");
|
|
196
|
+
expect(localLink?.href).toBe(
|
|
197
|
+
"https://agent-native.com/docs/multi-app-workspace#adding-a-new-app",
|
|
198
|
+
);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("sends the shared scaffold prompt to Builder when already in Builder", async () => {
|
|
202
|
+
frameState.inBuilderFrame = true;
|
|
203
|
+
await renderAndSubmit("Build a quality dashboard");
|
|
204
|
+
|
|
205
|
+
expect(sendToAgentChatMock).toHaveBeenCalledTimes(1);
|
|
206
|
+
expect(sendToAgentChatMock).toHaveBeenCalledWith(
|
|
207
|
+
expect.objectContaining({ submit: true, type: "code" }),
|
|
208
|
+
);
|
|
209
|
+
expect(
|
|
210
|
+
fetchSpy.mock.calls.some(([input]) =>
|
|
211
|
+
String(input).includes("start-workspace-app-creation"),
|
|
212
|
+
),
|
|
213
|
+
).toBe(false);
|
|
192
214
|
});
|
|
193
215
|
|
|
194
216
|
it("renders the error affordance and a Try again control for builder-error, without a Connect Builder control", async () => {
|