@agent-native/dispatch 0.15.23 → 0.15.25
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 +7 -1
- package/dist/actions/get-agent-thread-debug.js +16 -3
- package/dist/actions/get-agent-thread-debug.js.map +1 -1
- package/dist/actions/list-curated-workspace-templates.js +1 -1
- package/dist/actions/list-curated-workspace-templates.js.map +1 -1
- package/dist/actions/provider-api-register.d.ts +11 -11
- package/dist/actions/remix-workspace-template.js +5 -5
- package/dist/actions/remix-workspace-template.js.map +1 -1
- package/dist/actions/search-agent-threads.js +1 -1
- 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.js +2 -2
- package/dist/components/create-app-popover.js.map +1 -1
- package/dist/components/workspace-template-card.js +4 -4
- package/dist/components/workspace-template-card.js.map +1 -1
- package/dist/routes/pages/thread-debug.d.ts.map +1 -1
- package/dist/routes/pages/thread-debug.js +25 -11
- package/dist/routes/pages/thread-debug.js.map +1 -1
- package/dist/server/lib/app-creation-store.js +2 -2
- package/dist/server/lib/app-creation-store.js.map +1 -1
- package/dist/server/lib/curated-workspace-templates.d.ts +1 -1
- package/dist/server/lib/curated-workspace-templates.js +2 -2
- package/dist/server/lib/curated-workspace-templates.js.map +1 -1
- package/dist/server/lib/thread-debug-store.d.ts +7 -1
- package/dist/server/lib/thread-debug-store.d.ts.map +1 -1
- package/dist/server/lib/thread-debug-store.js +43 -5
- package/dist/server/lib/thread-debug-store.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/get-agent-thread-debug.ts +30 -15
- package/src/actions/list-curated-workspace-templates.ts +1 -1
- package/src/actions/remix-workspace-template.spec.ts +2 -2
- package/src/actions/remix-workspace-template.ts +5 -5
- package/src/actions/search-agent-threads.ts +1 -1
- package/src/actions/start-workspace-app-creation.ts +1 -1
- package/src/components/create-app-popover.tsx +2 -2
- package/src/components/workspace-template-card.spec.tsx +4 -4
- package/src/components/workspace-template-card.tsx +4 -4
- package/src/routes/pages/thread-debug.tsx +34 -14
- package/src/server/lib/app-creation-store.ts +2 -2
- package/src/server/lib/curated-workspace-templates.ts +2 -2
- package/src/server/lib/thread-debug-store.spec.ts +82 -0
- package/src/server/lib/thread-debug-store.ts +62 -6
- package/src/server/plugins/integrations.ts +1 -1
|
@@ -13,7 +13,7 @@ export interface CuratedWorkspaceTemplateStatus extends CuratedWorkspaceTemplate
|
|
|
13
13
|
installed: boolean;
|
|
14
14
|
}
|
|
15
15
|
/**
|
|
16
|
-
* Stable first-party template metadata for the initial
|
|
16
|
+
* Stable first-party template metadata for the initial app-creation catalog.
|
|
17
17
|
* `liveUrl` identifies the product URL; it is not a public-demo claim.
|
|
18
18
|
*/
|
|
19
19
|
export declare const CURATED_WORKSPACE_TEMPLATES: readonly CuratedWorkspaceTemplate[];
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { listWorkspaceApps } from "./app-creation-store.js";
|
|
2
2
|
/**
|
|
3
|
-
* Stable first-party template metadata for the initial
|
|
3
|
+
* Stable first-party template metadata for the initial app-creation catalog.
|
|
4
4
|
* `liveUrl` identifies the product URL; it is not a public-demo claim.
|
|
5
5
|
*/
|
|
6
6
|
export const CURATED_WORKSPACE_TEMPLATES = [
|
|
@@ -57,7 +57,7 @@ export const CURATED_WORKSPACE_TEMPLATES = [
|
|
|
57
57
|
template: "content",
|
|
58
58
|
liveUrl: "https://content.agent-native.com",
|
|
59
59
|
category: "content",
|
|
60
|
-
setupNote: "Choose a content folder or create a first document for the private
|
|
60
|
+
setupNote: "Choose a content folder or create a first document for the private app.",
|
|
61
61
|
},
|
|
62
62
|
{
|
|
63
63
|
id: "clips",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"curated-workspace-templates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AS;QAChB,QAAQ,EAAE,SAAS;QACnB,OAAO,EAAE,kCAAkC;QAC3C,QAAQ,EAAE,SAAS;QACnB,SAAS,EACP,
|
|
1
|
+
{"version":3,"file":"curated-workspace-templates.js","sourceRoot":"","sources":["../../../src/server/lib/curated-workspace-templates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAkB5D;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GACtC;IACE;QACE,EAAE,EAAE,MAAM;QACV,IAAI,EAAE,MAAM;QACZ,WAAW,EACT,kEAAkE;QACpE,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,SAAS;QAChB,QAAQ,EAAE,MAAM;QAChB,OAAO,EAAE,+BAA+B;QACxC,QAAQ,EAAE,eAAe;QACzB,SAAS,EACP,wEAAwE;KAC3E;IACD;QACE,EAAE,EAAE,UAAU;QACd,IAAI,EAAE,UAAU;QAChB,WAAW,EACT,mFAAmF;QACrF,IAAI,EAAE,cAAc;QACpB,KAAK,EAAE,SAAS;QAChB,QAAQ,EAAE,UAAU;QACpB,OAAO,EAAE,mCAAmC;QAC5C,QAAQ,EAAE,cAAc;QACxB,SAAS,EACP,6EAA6E;KAChF;IACD;QACE,EAAE,EAAE,WAAW;QACf,IAAI,EAAE,WAAW;QACjB,WAAW,EACT,4EAA4E;QAC9E,IAAI,EAAE,WAAW;QACjB,KAAK,EAAE,SAAS;QAChB,QAAQ,EAAE,WAAW;QACrB,OAAO,EAAE,oCAAoC;QAC7C,QAAQ,EAAE,UAAU;QACpB,SAAS,EACP,2EAA2E;KAC9E;IACD;QACE,EAAE,EAAE,QAAQ;QACZ,IAAI,EAAE,QAAQ;QACd,WAAW,EACT,8DAA8D;QAChE,IAAI,EAAE,mBAAmB;QACzB,KAAK,EAAE,SAAS;QAChB,QAAQ,EAAE,QAAQ;QAClB,OAAO,EAAE,iCAAiC;QAC1C,QAAQ,EAAE,UAAU;QACpB,SAAS,EACP,4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interface CuratedWorkspaceTemplate {\n id: string;\n name: string;\n description: string;\n icon: string;\n color: string;\n template: string;\n liveUrl: string;\n category: string;\n setupNote: string;\n}\n\nexport interface CuratedWorkspaceTemplateStatus extends CuratedWorkspaceTemplate {\n installed: boolean;\n}\n\n/**\n * Stable first-party template metadata for the initial app-creation catalog.\n * `liveUrl` identifies the product URL; it is not a public-demo claim.\n */\nexport const CURATED_WORKSPACE_TEMPLATES: readonly CuratedWorkspaceTemplate[] =\n [\n {\n id: \"mail\",\n name: \"Mail\",\n description:\n \"Agent-native email client with keyboard shortcuts and AI triage.\",\n icon: \"Mail\",\n color: \"#3B82F6\",\n template: \"mail\",\n liveUrl: \"https://mail.agent-native.com\",\n category: \"communication\",\n setupNote:\n \"Connect the workspace email integration before working with live mail.\",\n },\n {\n id: \"calendar\",\n name: \"Calendar\",\n description:\n \"Manage events, synchronization, and public booking with an agent-native calendar.\",\n icon: \"CalendarDays\",\n color: \"#00B5FF\",\n template: \"calendar\",\n liveUrl: \"https://calendar.agent-native.com\",\n category: \"productivity\",\n setupNote:\n \"Connect the workspace calendar integration before working with live events.\",\n },\n {\n id: \"analytics\",\n name: \"Analytics\",\n description:\n \"Connect data sources and prompt for charts, reports, and product insights.\",\n icon: \"BarChart2\",\n color: \"#F59E0B\",\n template: \"analytics\",\n liveUrl: \"https://analytics.agent-native.com\",\n category: \"insights\",\n setupNote:\n \"Connect a data source or import a representative dataset before analysis.\",\n },\n {\n id: \"slides\",\n name: \"Slides\",\n description:\n \"Generate and edit React presentations with agent assistance.\",\n icon: \"GalleryHorizontal\",\n color: \"#EC4899\",\n template: \"slides\",\n liveUrl: \"https://slides.agent-native.com\",\n category: \"creative\",\n setupNote:\n \"Start with a blank deck or connect the workspace presentation integration.\",\n },\n {\n id: \"content\",\n name: \"Content\",\n description:\n \"Write and organize local MDX content with agent assistance.\",\n icon: \"FileText\",\n color: \"#10B981\",\n template: \"content\",\n liveUrl: \"https://content.agent-native.com\",\n category: \"content\",\n setupNote:\n \"Choose a content folder or create a first document for the private app.\",\n },\n {\n id: \"clips\",\n name: \"Clips\",\n description:\n \"Record screens, capture meeting notes, and use voice dictation with AI.\",\n icon: \"ScreenShare\",\n color: \"#0EA5E9\",\n template: \"clips\",\n liveUrl: \"https://clips.agent-native.com\",\n category: \"media\",\n setupNote:\n \"Grant screen and audio permissions only when the workspace needs recording.\",\n },\n {\n id: \"brain\",\n name: \"Brain\",\n description:\n \"Search cited company knowledge from conversations, meetings, and decisions.\",\n icon: \"Brain\",\n color: \"#8B5CF6\",\n template: \"brain\",\n liveUrl: \"https://brain.agent-native.com\",\n category: \"knowledge\",\n setupNote:\n \"Connect approved knowledge sources before indexing workspace information.\",\n },\n {\n id: \"assets\",\n name: \"Assets\",\n description:\n \"Upload, organize, search, and generate on-brand images and videos.\",\n icon: \"Photo\",\n color: \"#0F766E\",\n template: \"assets\",\n liveUrl: \"https://assets.agent-native.com\",\n category: \"content\",\n setupNote:\n \"Upload a representative asset or connect approved asset storage to begin.\",\n },\n {\n id: \"forms\",\n name: \"Forms\",\n description: \"Create, edit, and manage forms with agent assistance.\",\n icon: \"ClipboardList\",\n color: \"#06B6D4\",\n template: \"forms\",\n liveUrl: \"https://forms.agent-native.com\",\n category: \"operations\",\n setupNote:\n \"Create a form and choose its submission destination before inviting respondents.\",\n },\n {\n id: \"design\",\n name: \"Design\",\n description:\n \"Create and edit visual designs with agent-assisted exploration.\",\n icon: \"Brush\",\n color: \"#F472B6\",\n template: \"design\",\n liveUrl: \"https://design.agent-native.com\",\n category: \"creative\",\n setupNote:\n \"Create a private project and optionally connect approved asset sources.\",\n },\n ] as const;\n\nconst curatedTemplateById = new Map(\n CURATED_WORKSPACE_TEMPLATES.map((template) => [template.id, template]),\n);\n\nexport function getCuratedWorkspaceTemplate(\n templateId: string,\n): CuratedWorkspaceTemplate {\n const normalized = templateId.trim().toLowerCase();\n const template = curatedTemplateById.get(normalized);\n if (!template) {\n throw new Error(`Unknown curated workspace template \"${templateId}\".`);\n }\n return template;\n}\n\nexport async function listCuratedWorkspaceTemplates(): Promise<\n CuratedWorkspaceTemplateStatus[]\n> {\n const installedIds = new Set(\n (\n await listWorkspaceApps({\n includeAgentCards: false,\n includeArchived: true,\n })\n ).map((app) => app.id.trim().toLowerCase()),\n );\n\n return CURATED_WORKSPACE_TEMPLATES.map((template) => ({\n ...template,\n installed: installedIds.has(template.id),\n }));\n}\n"]}
|
|
@@ -55,7 +55,8 @@ export declare function searchAgentThreads(input: {
|
|
|
55
55
|
}>;
|
|
56
56
|
export declare function getAgentThreadDebug(input: {
|
|
57
57
|
sourceId?: string;
|
|
58
|
-
threadId
|
|
58
|
+
threadId?: string;
|
|
59
|
+
runId?: string;
|
|
59
60
|
ownerEmail?: string;
|
|
60
61
|
maxRuns?: number;
|
|
61
62
|
maxEvents?: number;
|
|
@@ -81,6 +82,11 @@ export declare function getAgentThreadDebug(input: {
|
|
|
81
82
|
createdAt: number;
|
|
82
83
|
updatedAt: number;
|
|
83
84
|
};
|
|
85
|
+
lookup: {
|
|
86
|
+
requestedId: string;
|
|
87
|
+
threadId: string;
|
|
88
|
+
runId: string | null;
|
|
89
|
+
};
|
|
84
90
|
messages: any;
|
|
85
91
|
debug: any;
|
|
86
92
|
debugRuns: any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-debug-store.d.ts","sourceRoot":"","sources":["../../../src/server/lib/thread-debug-store.ts"],"names":[],"mappings":"AAsBA,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,W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erScope(access, input.ownerEmail);
|
|
436
436
|
const where = [scope.sql];
|
|
437
437
|
const args = [...scope.args];
|
|
438
|
+
const runThreadIds = q
|
|
439
|
+
? (await optionalRows(exec, "SELECT thread_id FROM agent_runs WHERE id = ? LIMIT 1", [q]))
|
|
440
|
+
.map((row) => String(row.thread_id ?? "").trim())
|
|
441
|
+
.filter(Boolean)
|
|
442
|
+
: [];
|
|
438
443
|
if (q) {
|
|
439
|
-
const pattern =
|
|
440
|
-
|
|
444
|
+
const pattern = "%" + escapeLike(q.toLowerCase()) + "%";
|
|
445
|
+
const runIdClause = runThreadIds.length > 0
|
|
446
|
+
? " OR id IN (" + runThreadIds.map(() => "?").join(", ") + ")"
|
|
447
|
+
: "";
|
|
448
|
+
where.push("(LOWER(title) LIKE ? ESCAPE '\\' OR LOWER(preview) LIKE ? ESCAPE '\\' OR LOWER(thread_data) LIKE ? ESCAPE '\\'" +
|
|
449
|
+
runIdClause +
|
|
450
|
+
")");
|
|
441
451
|
args.push(pattern, pattern, pattern);
|
|
452
|
+
args.push(...runThreadIds);
|
|
442
453
|
}
|
|
443
454
|
args.push(limit);
|
|
444
455
|
const rows = await optionalRows(exec, `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at
|
|
@@ -469,13 +480,35 @@ export async function getAgentThreadDebug(input) {
|
|
|
469
480
|
assertSourceAccess(source, access);
|
|
470
481
|
const exec = await execForSource(source);
|
|
471
482
|
const scope = ownerScope(access, input.ownerEmail);
|
|
472
|
-
const
|
|
483
|
+
const requestedId = input.runId?.trim() || input.threadId?.trim() || "";
|
|
484
|
+
if (!requestedId) {
|
|
485
|
+
throw new Error("A thread ID or request/run ID is required.");
|
|
486
|
+
}
|
|
487
|
+
let rows = await queryRows(exec, `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at
|
|
473
488
|
FROM chat_threads
|
|
474
489
|
WHERE id = ? AND ${scope.sql}
|
|
475
|
-
LIMIT 1`, [input.threadId, ...scope.args]);
|
|
490
|
+
LIMIT 1`, [input.threadId?.trim() || requestedId, ...scope.args]);
|
|
491
|
+
let resolvedRunId = input.runId?.trim() || null;
|
|
492
|
+
if (!rows[0]) {
|
|
493
|
+
const runRows = await optionalRows(exec, `SELECT id, thread_id
|
|
494
|
+
FROM agent_runs
|
|
495
|
+
WHERE id = ?
|
|
496
|
+
LIMIT 1`, [requestedId]);
|
|
497
|
+
const threadId = runRows[0]?.thread_id
|
|
498
|
+
? String(runRows[0].thread_id).trim()
|
|
499
|
+
: "";
|
|
500
|
+
if (threadId) {
|
|
501
|
+
rows = await queryRows(exec, `SELECT id, owner_email, title, preview, thread_data, message_count, created_at, updated_at
|
|
502
|
+
FROM chat_threads
|
|
503
|
+
WHERE id = ? AND ${scope.sql}
|
|
504
|
+
LIMIT 1`, [threadId, ...scope.args]);
|
|
505
|
+
if (rows[0])
|
|
506
|
+
resolvedRunId = requestedId;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
476
509
|
const row = rows[0];
|
|
477
510
|
if (!row) {
|
|
478
|
-
throw new Error(`Thread "${
|
|
511
|
+
throw new Error(`Thread or request/run ID "${requestedId}" was not found.`);
|
|
479
512
|
}
|
|
480
513
|
const threadData = safeJsonParse(row.thread_data, {});
|
|
481
514
|
const maxRuns = Math.max(1, Math.min(50, input.maxRuns ?? DEFAULT_RUN_LIMIT));
|
|
@@ -568,6 +601,11 @@ export async function getAgentThreadDebug(input) {
|
|
|
568
601
|
createdAt: numberField(row.created_at),
|
|
569
602
|
updatedAt: numberField(row.updated_at),
|
|
570
603
|
},
|
|
604
|
+
lookup: {
|
|
605
|
+
requestedId,
|
|
606
|
+
threadId: String(row.id),
|
|
607
|
+
runId: resolvedRunId,
|
|
608
|
+
},
|
|
571
609
|
messages: normalizeMessages(threadData),
|
|
572
610
|
debug: threadData?._debug ?? null,
|
|
573
611
|
debugRuns: Array.isArray(threadData?._debugRuns)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-debug-store.js","sourceRoot":"","s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M,CAAC,cAAc,IAAI,IAAI;SAC9C;QACD,MAAM,EAAE;YACN,WAAW,EAAE,MAAM,CAAC,WAAW;YAC/B,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,aAAa,EAAE,MAAM,CAAC,aAAa;SACpC;QACD,MAAM,EAAE;YACN,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;YAClB,UAAU,EAAE,MAAM,CAAC,GAAG,CAAC,WAAW,IAAI,EAAE,CAAC;YACzC,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC;YAC9B,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,OAAO,IAAI,EAAE,CAAC;YAClC,YAAY,EAAE,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC;YAC5C,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC;YACtC,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC;SACvC;QACD,QAAQ,EAAE,iBAAiB,CAAC,UAAU,CAAC;QACvC,KAAK,EAAG,UAAkB,EAAE,MAAM,IAAI,IAAI;QAC1C,SAAS,EAAE,KAAK,CAAC,OAAO,CAAE,UAAkB,EAAE,UAAU,CAAC;YACvD,CAAC,CAAE,UAAkB,CAAC,UAAU;YAChC,CAAC,CAAC,EAAE;QACN,cAAc,EAAG,UAAkB,EAAE,cAAc,IAAI,EAAE;QACzD,UAAU;QACV,aAAa,EAAE,GAAG,CAAC,WAAW,IAAI,EAAE;QACpC,IAAI;QACJ,MAAM,EAAE;YACN,SAAS,EAAE,gBAAgB;YAC3B,KAAK,EAAE,aAAa;SACrB;QACD,QAAQ,EAAE,YAAY;QACtB,YAAY,EAAE,gBAAgB;QAC9B,KAAK,EAAE,QAAQ;QACf,WAAW,EAAE,cAAc;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["import { createDbExec, getDbExec, type DbExec } from \"@agent-native/core/db\";\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}\n\nconst execCache = new Map<string, Promise<DbExec>>();\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 isMissingTableError(error: unknown): boolean {\n const message = String((error as Error)?.message ?? error).toLowerCase();\n return (\n message.includes(\"no such table\") ||\n message.includes(\"does not exist\") ||\n message.includes(\"unknown table\") ||\n message.includes(\"undefined table\")\n );\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 if (isMissingTableError(error)) {\n throw new Error(\n \"This database does not have agent chat thread tables yet.\",\n );\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 if (!databaseUrl) return null;\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) return direct;\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 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 Error(\n \"Only Dispatch admins can inspect thread databases from other apps.\",\n );\n }\n}\n\nfunction ownerScope(access: DebugAccess, ownerEmail?: string): OwnerScope {\n const requested = ownerEmail?.trim();\n if (!access.canInspectAll) {\n return {\n sql: \"owner_email = ?\",\n args: [access.viewerEmail],\n label: access.viewerEmail,\n };\n }\n\n if (requested && requested !== \"*\") {\n return {\n sql: \"owner_email = ?\",\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: \"owner_email = ?\",\n args: [access.viewerEmail],\n label: access.viewerEmail,\n };\n }\n const placeholders = emails.map(() => \"?\").join(\", \");\n return {\n sql: `owner_email 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 status: String(row.status),\n abortReason: row.abort_reason ? String(row.abort_reason) : null,\n startedAt: numberField(row.started_at),\n completedAt: nullableNumberField(row.completed_at),\n heartbeatAt: nullableNumberField(row.heartbeat_at),\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\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 if (q) {\n const pattern = `%${escapeLike(q.toLowerCase())}%`;\n where.push(\n `(LOWER(title) LIKE ? ESCAPE '\\\\' OR LOWER(preview) LIKE ? ESCAPE '\\\\' OR LOWER(thread_data) LIKE ? ESCAPE '\\\\')`,\n );\n args.push(pattern, pattern, pattern);\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 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 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, ...scope.args],\n );\n const row = rows[0];\n if (!row) {\n throw new Error(`Thread \"${input.threadId}\" 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 id, thread_id, status, abort_reason, started_at, heartbeat_at, completed_at\n FROM agent_runs\n WHERE thread_id = ?\n ORDER BY 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 messages: normalizeMessages(threadData),\n debug: (threadData as any)?._debug ?? null,\n debugRuns: Array.isArray((threadData as any)?._debugRuns)\n ? (threadData as any)._debugRuns\n : [],\n queuedMessages: (threadData as any)?.queuedMessages ?? [],\n threadData,\n rawThreadData: row.thread_data ?? \"\",\n runs,\n traces: {\n summaries: traceSummaryRows,\n spans: traceSpanRows,\n },\n feedback: feedbackRows,\n satisfaction: satisfactionRows,\n evals: evalRows,\n checkpoints: checkpointRows,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"thread-debug-store.js","sourceRoot":"","sources":["../../../src/server/lib/thread-debug-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,SAAS,EAAe,MAAM,uBAAuB,CAAC;AAE7E,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAEtE,MAAM,cAAc,GAAG,qCAAqC,CAAC;AAC7D,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AA2DrC,MAAM,SAAS,GAAG,IAAI,GAAG,EAA2B,CAAC;AAErD,SAAS,SAAS,CAAC,IAAY;IAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAC7B,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,C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AE,CAAC;YAC9B,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,OAAO,IAAI,EAAE,CAAC;YAClC,YAAY,EAAE,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC;YAC5C,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC;YACtC,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC;SACvC;QACD,MAAM,EAAE;YACN,WAAW;YACX,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;YACxB,KAAK,EAAE,aAAa;SACrB;QACD,QAAQ,EAAE,iBAAiB,CAAC,UAAU,CAAC;QACvC,KAAK,EAAG,UAAkB,EAAE,MAAM,IAAI,IAAI;QAC1C,SAAS,EAAE,KAAK,CAAC,OAAO,CAAE,UAAkB,EAAE,UAAU,CAAC;YACvD,CAAC,CAAE,UAAkB,CAAC,UAAU;YAChC,CAAC,CAAC,EAAE;QACN,cAAc,EAAG,UAAkB,EAAE,cAAc,IAAI,EAAE;QACzD,UAAU;QACV,aAAa,EAAE,GAAG,CAAC,WAAW,IAAI,EAAE;QACpC,IAAI;QACJ,MAAM,EAAE;YACN,SAAS,EAAE,gBAAgB;YAC3B,KAAK,EAAE,aAAa;SACrB;QACD,QAAQ,EAAE,YAAY;QACtB,YAAY,EAAE,gBAAgB;QAC9B,KAAK,EAAE,QAAQ;QACf,WAAW,EAAE,cAAc;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["import { createDbExec, getDbExec, type DbExec } from \"@agent-native/core/db\";\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}\n\nconst execCache = new Map<string, Promise<DbExec>>();\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 isMissingTableError(error: unknown): boolean {\n const message = String((error as Error)?.message ?? error).toLowerCase();\n return (\n message.includes(\"no such table\") ||\n message.includes(\"does not exist\") ||\n message.includes(\"unknown table\") ||\n message.includes(\"undefined table\")\n );\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 if (isMissingTableError(error)) {\n throw new Error(\n \"This database does not have agent chat thread tables yet.\",\n );\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 if (!databaseUrl) return null;\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) return direct;\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 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 Error(\n \"Only Dispatch admins can inspect thread databases from other apps.\",\n );\n }\n}\n\nfunction ownerScope(access: DebugAccess, ownerEmail?: string): OwnerScope {\n const requested = ownerEmail?.trim();\n if (!access.canInspectAll) {\n return {\n sql: \"owner_email = ?\",\n args: [access.viewerEmail],\n label: access.viewerEmail,\n };\n }\n\n if (requested && requested !== \"*\") {\n return {\n sql: \"owner_email = ?\",\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: \"owner_email = ?\",\n args: [access.viewerEmail],\n label: access.viewerEmail,\n };\n }\n const placeholders = emails.map(() => \"?\").join(\", \");\n return {\n sql: `owner_email 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 status: String(row.status),\n abortReason: row.abort_reason ? String(row.abort_reason) : null,\n startedAt: numberField(row.started_at),\n completedAt: nullableNumberField(row.completed_at),\n heartbeatAt: nullableNumberField(row.heartbeat_at),\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\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 id, thread_id, status, abort_reason, started_at, heartbeat_at, completed_at\n FROM agent_runs\n WHERE thread_id = ?\n ORDER BY 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"]}
|
|
@@ -34,7 +34,7 @@ When a user asks for something:
|
|
|
34
34
|
- 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.
|
|
35
35
|
- 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.
|
|
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
|
-
- 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
|
|
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
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 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. If it returns mode "coming-soon", say this requires a code change and they can edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like; do not send them to 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.
|
|
@@ -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 fork/copy.\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. If it returns mode \"coming-soon\", say this requires a code change and they can edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like; do not send them to 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. 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. If it returns mode \"coming-soon\", say this requires a code change and they can edit locally or use Builder.io to edit this code in the cloud and continue customizing the app any way they like; do not send them to 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.15.
|
|
3
|
+
"version": "0.15.25",
|
|
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.10.
|
|
87
|
+
"@agent-native/toolkit": "0.10.8"
|
|
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.124.4"
|
|
102
102
|
},
|
|
103
103
|
"peerDependencies": {
|
|
104
104
|
"@agent-native/core": ">=0.8.0",
|
|
@@ -5,21 +5,36 @@ import { getAgentThreadDebug } from "../server/lib/thread-debug-store.js";
|
|
|
5
5
|
|
|
6
6
|
export default defineAction({
|
|
7
7
|
description:
|
|
8
|
-
"Get a full read-only debug snapshot
|
|
9
|
-
schema: z
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
8
|
+
"Get a full read-only debug snapshot by chat thread ID or copied request/run ID, including persisted messages, raw thread_data, run events, traces, feedback, evals, and checkpoints when present.",
|
|
9
|
+
schema: z
|
|
10
|
+
.object({
|
|
11
|
+
sourceId: z
|
|
12
|
+
.string()
|
|
13
|
+
.default("current")
|
|
14
|
+
.describe("Thread debug source id from list-agent-thread-sources."),
|
|
15
|
+
threadId: z
|
|
16
|
+
.string()
|
|
17
|
+
.min(1)
|
|
18
|
+
.optional()
|
|
19
|
+
.describe("Agent chat thread ID to inspect."),
|
|
20
|
+
runId: z
|
|
21
|
+
.string()
|
|
22
|
+
.min(1)
|
|
23
|
+
.optional()
|
|
24
|
+
.describe(
|
|
25
|
+
"Copied Agent Native request/run ID, usually shown as run-..., to resolve to its owning chat thread.",
|
|
26
|
+
),
|
|
27
|
+
ownerEmail: z
|
|
28
|
+
.string()
|
|
29
|
+
.optional()
|
|
30
|
+
.describe("Optional owner email scope for admin cross-user lookups."),
|
|
31
|
+
maxRuns: z.coerce.number().int().min(1).max(50).default(20),
|
|
32
|
+
maxEvents: z.coerce.number().int().min(1).max(2000).default(600),
|
|
33
|
+
maxTraceSpans: z.coerce.number().int().min(1).max(2000).default(500),
|
|
34
|
+
})
|
|
35
|
+
.refine((input) => Boolean(input.threadId || input.runId), {
|
|
36
|
+
message: "Provide either threadId or runId.",
|
|
37
|
+
}),
|
|
23
38
|
http: { method: "GET" },
|
|
24
39
|
readOnly: true,
|
|
25
40
|
run: async (input) => getAgentThreadDebug(input),
|
|
@@ -5,7 +5,7 @@ import { listCuratedWorkspaceTemplates } from "../server/lib/curated-workspace-t
|
|
|
5
5
|
|
|
6
6
|
export default defineAction({
|
|
7
7
|
description:
|
|
8
|
-
"List the curated first-party workspace templates available for private
|
|
8
|
+
"List the curated first-party workspace templates available for creating private apps. Returns stable template metadata, the product/live URL (not a public-demo claim), setup guidance, and whether each source template is already installed in the current workspace.",
|
|
9
9
|
schema: z.object({}),
|
|
10
10
|
http: { method: "GET" },
|
|
11
11
|
run: async () => listCuratedWorkspaceTemplates(),
|
|
@@ -68,7 +68,7 @@ describe("remix-workspace-template action", () => {
|
|
|
68
68
|
);
|
|
69
69
|
});
|
|
70
70
|
|
|
71
|
-
it("starts a hosted private
|
|
71
|
+
it("starts a hosted private app without copying data or secrets", async () => {
|
|
72
72
|
vi.stubEnv("NODE_ENV", "production");
|
|
73
73
|
mocks.startWorkspaceAppCreation.mockResolvedValue({
|
|
74
74
|
mode: "builder",
|
|
@@ -88,7 +88,7 @@ describe("remix-workspace-template action", () => {
|
|
|
88
88
|
template: "calendar",
|
|
89
89
|
description: "A private scheduling workflow.",
|
|
90
90
|
prompt: expect.stringContaining(
|
|
91
|
-
"private workspace
|
|
91
|
+
"private workspace app from a curated first-party template",
|
|
92
92
|
),
|
|
93
93
|
}),
|
|
94
94
|
);
|