@agent-native/core 0.7.62 → 0.7.64

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.
@@ -0,0 +1,6 @@
1
+ export interface RuntimeContextOptions {
2
+ now?: Date;
3
+ timezone?: string | null;
4
+ }
5
+ export declare function buildRuntimeContextPrompt(options?: RuntimeContextOptions): string;
6
+ //# sourceMappingURL=runtime-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-context.d.ts","sourceRoot":"","sources":["../../src/agent/runtime-context.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,qBAAqB;IACpC,GAAG,CAAC,EAAE,IAAI,CAAC;IACX,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAsCD,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,qBAA0B,GAClC,MAAM,CAiBR"}
@@ -0,0 +1,51 @@
1
+ function isValidTimezone(timezone) {
2
+ try {
3
+ new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
4
+ return true;
5
+ }
6
+ catch {
7
+ return false;
8
+ }
9
+ }
10
+ function formatDateTime(date, timezone) {
11
+ return new Intl.DateTimeFormat("en-US", {
12
+ timeZone: timezone,
13
+ weekday: "long",
14
+ year: "numeric",
15
+ month: "long",
16
+ day: "numeric",
17
+ hour: "2-digit",
18
+ minute: "2-digit",
19
+ second: "2-digit",
20
+ timeZoneName: "short",
21
+ }).format(date);
22
+ }
23
+ function formatDate(date, timezone) {
24
+ const parts = new Intl.DateTimeFormat("en-CA", {
25
+ timeZone: timezone,
26
+ year: "numeric",
27
+ month: "2-digit",
28
+ day: "2-digit",
29
+ }).formatToParts(date);
30
+ const year = parts.find((part) => part.type === "year")?.value ?? "1970";
31
+ const month = parts.find((part) => part.type === "month")?.value ?? "01";
32
+ const day = parts.find((part) => part.type === "day")?.value ?? "01";
33
+ return `${year}-${month}-${day}`;
34
+ }
35
+ export function buildRuntimeContextPrompt(options = {}) {
36
+ const now = options.now ?? new Date();
37
+ const timezone = typeof options.timezone === "string" && isValidTimezone(options.timezone)
38
+ ? options.timezone
39
+ : "UTC";
40
+ return `
41
+
42
+ <runtime-context>
43
+ currentUtc: ${now.toISOString()}
44
+ currentDateUtc: ${formatDate(now, "UTC")}
45
+ currentTimezone: ${timezone}
46
+ currentDateInTimezone: ${formatDate(now, timezone)}
47
+ currentTimeInTimezone: ${formatDateTime(now, timezone)}
48
+ Use this runtime context as authoritative for relative dates such as today, yesterday, tomorrow, this week, and last month. Resolve relative dates to explicit calendar dates before querying data or creating artifacts, and include the exact date or date range in factual answers.
49
+ </runtime-context>`;
50
+ }
51
+ //# sourceMappingURL=runtime-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-context.js","sourceRoot":"","sources":["../../src/agent/runtime-context.ts"],"names":[],"mappings":"AAKA,SAAS,eAAe,CAAC,QAAgB;IACvC,IAAI,CAAC;QACH,IAAI,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC;QAClE,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,SAAS,cAAc,CAAC,IAAU,EAAE,QAAgB;IAClD,OAAO,IAAI,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;QACtC,QAAQ,EAAE,QAAQ;QAClB,OAAO,EAAE,MAAM;QACf,IAAI,EAAE,SAAS;QACf,KAAK,EAAE,MAAM;QACb,GAAG,EAAE,SAAS;QACd,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,SAAS;QACjB,MAAM,EAAE,SAAS;QACjB,YAAY,EAAE,OAAO;KACtB,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAClB,CAAC;AAED,SAAS,UAAU,CAAC,IAAU,EAAE,QAAgB;IAC9C,MAAM,KAAK,GAAG,IAAI,IAAI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ezone?: string | null;\n}\n\nfunction isValidTimezone(timezone: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone }).format();\n return true;\n } catch {\n return false;\n }\n}\n\nfunction formatDateTime(date: Date, timezone: string): string {\n return new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n weekday: \"long\",\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZoneName: \"short\",\n }).format(date);\n}\n\nfunction formatDate(date: Date, timezone: string): string {\n const parts = new Intl.DateTimeFormat(\"en-CA\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n }).formatToParts(date);\n const year = parts.find((part) => part.type === \"year\")?.value ?? \"1970\";\n const month = parts.find((part) => part.type === \"month\")?.value ?? \"01\";\n const day = parts.find((part) => part.type === \"day\")?.value ?? \"01\";\n return `${year}-${month}-${day}`;\n}\n\nexport function buildRuntimeContextPrompt(\n options: RuntimeContextOptions = {},\n): string {\n const now = options.now ?? new Date();\n const timezone =\n typeof options.timezone === \"string\" && isValidTimezone(options.timezone)\n ? options.timezone\n : \"UTC\";\n\n return `\n\n<runtime-context>\ncurrentUtc: ${now.toISOString()}\ncurrentDateUtc: ${formatDate(now, \"UTC\")}\ncurrentTimezone: ${timezone}\ncurrentDateInTimezone: ${formatDate(now, timezone)}\ncurrentTimeInTimezone: ${formatDateTime(now, timezone)}\nUse this runtime context as authoritative for relative dates such as today, yesterday, tomorrow, this week, and last month. Resolve relative dates to explicit calendar dates before querying data or creating artifacts, and include the exact date or date range in factual answers.\n</runtime-context>`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-handler.d.ts","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE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;;;;GAIG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CASf"}
1
+ {"version":3,"file":"webhook-handler.d.ts","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGnE,OAAO,EAML,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;AAYtC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAU5D,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,0BAA0B,CAAC;AA+BlC,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,eAAe,CAAC;IACzB,oCAAoC;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,mCAAmC;IACnC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACrC,mBAAmB;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,wBAAwB;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,sEAAsE;IACtE,MAAM,CAAC,EACH,WAAW,GACX,MAAM,GACN;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IACtD,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,yEAAyE;IACzE,aAAa,CAAC,EAAE,CACd,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,eAAe,KACrB,OAAO,CACR;QACE,OAAO,EAAE,IAAI,CAAC;QACd,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB,GACD;QAAE,OAAO,EAAE,KAAK,CAAA;KAAE,CACrB,CAAC;CACH;AAmDD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,aAAa,CACjC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC,CAsE5C;AAgHD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CA2BrD;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CASf"}
@@ -18,6 +18,7 @@ import { withConfiguredAppBasePath } from "../server/app-base-path.js";
18
18
  import { A2A_CONTINUATION_QUEUED_MARKER } from "./a2a-continuation-marker.js";
19
19
  import { collectFinalResponseTextFromAgentEvents } from "../a2a/response-text.js";
20
20
  import { appendA2AArtifactLinks, } from "../a2a/artifact-response.js";
21
+ import { buildRuntimeContextPrompt } from "../agent/runtime-context.js";
21
22
  const PROCESSOR_DISPATCH_SETTLE_WAIT_MS = 1_500;
22
23
  /**
23
24
  * Build a stable per-event dedup key from the incoming message. The same
@@ -295,6 +296,7 @@ export async function processIntegrationTask(task, options) {
295
296
  */
296
297
  async function processIncomingMessage(incoming, options, opts = {}) {
297
298
  const { adapter, systemPrompt, actions, model, apiKey, ownerEmail, engine: engineOption, } = options;
299
+ const effectiveSystemPrompt = systemPrompt + buildRuntimeContextPrompt();
298
300
  // Resolve or create internal thread
299
301
  let mapping = await getThreadMapping(incoming.platform, incoming.externalThreadId);
300
302
  if (!mapping) {
@@ -399,7 +401,7 @@ async function processIncomingMessage(incoming, options, opts = {}) {
399
401
  return runAgentLoop({
400
402
  engine,
401
403
  model: resolvedModel,
402
- systemPrompt,
404
+ systemPrompt: effectiveSystemPrompt,
403
405
  tools,
404
406
  messages,
405
407
  actions,
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-handler.js","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,oBAAoB,EACpB,cAAc,EACd,gBAAgB,GAEjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,sCAAsC,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAC3E,OAAO,EACL,uBAAuB,EACvB,aAAa,GACd,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAG9C,OAAO,EAAE,QAAQ,EAAkB,MAAM,yBAAyB,CAAC;AACnE,OAAO,EACL,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EACL,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAC9E,OAAO,EAAE,uCAAuC,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EACL,sBAAsB,G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MAAM,EAAE,OAAO,IAAI,EAAE,EACrC,IAAI,CAAC,QAAQ,CAAC,MAAM,CACrB,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,0BAA0B;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport type { PlatformAdapter, IncomingMessage } from \"./types.js\";\nimport { getThreadMapping, saveThreadMapping } from \"./thread-mapping-store.js\";\nimport { createThread, getThread } from \"../chat-threads/store.js\";\nimport {\n runAgentLoop,\n actionsToEngineTools,\n getOwnerActiveApiKey,\n getOwnerApiKey,\n engineToProvider,\n type ActionEntry,\n} from \"../agent/production-agent.js\";\nimport { PROVIDER_TO_ENV } from \"../agent/engine/provider-env-vars.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { readDeployCredentialEnv } from \"../server/credential-provider.js\";\nimport {\n getStoredModelForEngine,\n resolveEngine,\n} from \"../agent/engine/index.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { AgentEngine } from \"../agent/engine/types.js\";\nimport type { EngineMessage } from \"../agent/engine/types.js\";\nimport { startRun, type ActiveRun } from \"../agent/run-manager.js\";\nimport {\n buildAssistantMessage,\n extractThreadMeta,\n} from \"../agent/thread-data-builder.js\";\nimport { updateThreadData } from \"../chat-threads/store.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { resolveOrgIdForEmail } from \"../org/context.js\";\nimport {\n insertPendingTask,\n isDuplicateEventError,\n type PendingTask,\n} from \"./pending-tasks-store.js\";\nimport { signInternalToken } from \"./internal-token.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"./a2a-continuation-marker.js\";\nimport { collectFinalResponseTextFromAgentEvents } from \"../a2a/response-text.js\";\nimport {\n appendA2AArtifactLinks,\n type A2AToolResultSummary,\n} from \"../a2a/artifact-response.js\";\n\nconst PROCESSOR_DISPATCH_SETTLE_WAIT_MS = 1_500;\n\ntype ToolDoneEvent = { type: \"tool_done\"; tool: string; result: string };\n\n/**\n * Build a stable per-event dedup key from the incoming message. The same\n * key is computed for every retry of the same event from the platform —\n * Slack/Telegram retry on timeout (3s for Slack), so we MUST treat the\n * second delivery as a duplicate and return 200 silently.\n *\n * The `(platform, external_event_key)` UNIQUE index in\n * `integration_pending_tasks` enforces this at the SQL layer, replacing\n * the previous in-memory Map (H3 in the webhook security audit) which\n * couldn't survive serverless cold starts.\n */\nfunction buildEventDedupKey(incoming: IncomingMessage): string {\n return `${incoming.platform}:${incoming.externalThreadId}:${incoming.timestamp}`;\n}\n\nexport interface WebhookHandlerOptions {\n adapter: PlatformAdapter;\n /** Resolved system prompt string */\n systemPrompt: string;\n /** Action entries for the agent */\n actions: Record<string, ActionEntry>;\n /** Model to use */\n model: string;\n /** Anthropic API key */\n apiKey: string;\n /** Agent engine to use. Defaults to the same resolver as web chat. */\n engine?:\n | AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Thread owner for personal/shared resource loading */\n ownerEmail: string;\n /**\n * Pre-parsed incoming message. When provided, handleWebhook skips its own\n * verification + parsing steps. Required when the caller has already read\n * the request body (h3 doesn't reliably cache parsed bodies, so re-parsing\n * the same event hangs on streaming providers).\n */\n incoming?: IncomingMessage;\n /** Optional hook to intercept inbound commands before agent execution */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n\nfunction explicitEngineName(\n engineOption: WebhookHandlerOptions[\"engine\"],\n): string | undefined {\n if (!engineOption) return undefined;\n if (typeof engineOption === \"string\") return engineOption;\n if (\n typeof engineOption === \"object\" &&\n !(\"stream\" in engineOption) &&\n typeof engineOption.name === \"string\"\n ) {\n return engineOption.name;\n }\n return undefined;\n}\n\nfunction isMultiTenantDeploy(): boolean {\n if (process.env.NODE_ENV !== \"production\") return false;\n return !isLocalDatabase();\n}\n\nfunction collectToolResultSummaries(\n completedRun: ActiveRun,\n): A2AToolResultSummary[] {\n return completedRun.events\n .map((runEvent) => runEvent.event)\n .filter((event): event is ToolDoneEvent => event.type === \"tool_done\")\n .map((event) => ({ tool: event.tool, result: event.result }));\n}\n\nasync function resolveIntegrationApiKey(\n engineOption: WebhookHandlerOptions[\"engine\"],\n ownerEmail: string,\n fallbackApiKey: string,\n): Promise<string | undefined> {\n const engineName = explicitEngineName(engineOption);\n if (engineName) {\n const provider = engineToProvider(engineName);\n const userApiKey = await getOwnerApiKey(provider, ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n const envVar = PROVIDER_TO_ENV[provider];\n const providerEnvKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\n return providerEnvKey || fallbackApiKey.trim() || undefined;\n }\n\n const userApiKey = await getOwnerActiveApiKey(ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n return fallbackApiKey.trim() || undefined;\n}\n\n/**\n * Process an incoming webhook from a messaging platform.\n *\n * Flow:\n * 1. Handle verification challenges (Slack url_verification, etc.)\n * 2. Verify webhook signature\n * 3. Parse incoming message (null = ignored event)\n * 4. Persist task to SQL\n * 5. Fire-and-forget POST to /_agent-native/integrations/process-task\n * (a fresh function execution with its own timeout budget)\n * 6. Return HTTP 200 immediately (within Slack's 3s SLA)\n *\n * The processor endpoint runs the actual agent loop. This split is essential\n * for serverless platforms (Netlify Lambda, Vercel, Cloudflare Workers) which\n * freeze the function as soon as the response is returned, killing any\n * lingering background promises.\n */\nexport async function handleWebhook(\n event: H3Event,\n options: WebhookHandlerOptions,\n): Promise<{ status: number; body: unknown }> {\n const { adapter, beforeProcess } = options;\n\n let incoming: IncomingMessage | null = options.incoming ?? null;\n\n // When the caller didn't pre-parse, run the full verify + parse pipeline.\n // Otherwise skip it — h3's body stream has already been consumed and a\n // second readBody call hangs on streaming providers.\n if (!incoming) {\n // Step 1: Handle platform-specific verification challenges\n const verification = await adapter.handleVerification(event);\n if (verification.handled) {\n return { status: 200, body: verification.response ?? \"ok\" };\n }\n\n // Step 2: Verify webhook signature\n const isValid = await adapter.verifyWebhook(event);\n if (!isValid) {\n return { status: 401, body: { error: \"Invalid webhook signature\" } };\n }\n\n // Step 3: Parse the incoming message\n incoming = await adapter.parseIncomingMessage(event);\n if (!incoming) {\n // Not a user message (bot message, edit, reaction, etc.) — acknowledge silently\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Dedup is enforced inside enqueueAndDispatch — the unique index on\n // `(platform, external_event_key)` raises a constraint violation we treat\n // as \"already enqueued\" and respond 200. We can't dedup BEFORE the\n // beforeProcess hook because some templates use beforeProcess for\n // command-style intercepts that are stateless and idempotent (e.g. a\n // Slack `/help` command that doesn't enqueue a task).\n\n if (beforeProcess) {\n const result = await beforeProcess(incoming, adapter);\n if (result.handled) {\n if (result.responseText?.trim()) {\n const outgoing = adapter.formatAgentResponse(result.responseText);\n await adapter.sendResponse(outgoing, incoming);\n }\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Step 4 + 5: Enqueue to SQL and dispatch to processor in a fresh request.\n try {\n await enqueueAndDispatch(event, incoming, options);\n } catch (err) {\n // Duplicate event delivery: the SQL UNIQUE constraint on\n // (platform, external_event_key) rejected the second insert. This is\n // the expected path when a platform retries an event that already\n // landed (e.g. Slack 3-second timeout) — return 200 so the platform\n // stops retrying. See H3 in the webhook security audit.\n if (isDuplicateEventError(err)) {\n return { status: 200, body: \"ok\" };\n }\n console.error(\n `[integrations] Failed to enqueue/dispatch ${incoming.platform} message:`,\n err,\n );\n // Return 500 so the platform retries. If the SQL insert failed for a\n // non-dup reason, the message is genuinely lost — better to let Slack\n // retry (it will re-fire the same event_callback) than silently drop it.\n return { status: 500, body: { error: \"enqueue failed\" } };\n }\n\n return { status: 200, body: \"ok\" };\n}\n\n/**\n * Persist the task to SQL and dispatch a fresh HTTP request to the processor\n * endpoint. The dispatch is fire-and-forget — we deliberately do NOT await\n * the resulting fetch, so the current handler can return immediately.\n *\n * This pattern works on every supported host:\n * - Netlify Lambda: function returns; the dispatched request hits a fresh\n * Lambda with its own function budget.\n * - Vercel Functions: same.\n * - Cloudflare Workers: same (no waitUntil dependency).\n * - Self-hosted Node: a separate request comes back through the same\n * server, but each handler still runs to completion.\n */\nasync function enqueueAndDispatch(\n event: H3Event,\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Resolve the org id once at enqueue-time so the processor doesn't have to\n // re-derive it (and so we can drop it on the row for observability).\n let orgId: string | null = null;\n try {\n orgId = (await resolveOrgIdForEmail(options.ownerEmail)) ?? null;\n } catch {\n orgId = null;\n }\n\n // Post a \"thinking…\" placeholder immediately if the adapter supports\n // in-place edits. The processor flow will update this same message with\n // the final answer, so users see one tidy thread reply instead of\n // \"[silence] → answer\". Adapters without edit support skip this and the\n // processor posts a fresh response.\n let placeholderRef: string | undefined;\n try {\n if (options.adapter.postProcessingPlaceholder) {\n const placeholder =\n await options.adapter.postProcessingPlaceholder(incoming);\n if (placeholder?.placeholderRef) {\n placeholderRef = placeholder.placeholderRef;\n }\n }\n } catch (err) {\n console.error(\"[integrations] postProcessingPlaceholder failed:\", err);\n }\n\n const payload = JSON.stringify({ incoming, placeholderRef });\n\n await insertPendingTask({\n id: taskId,\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n payload,\n ownerEmail: options.ownerEmail,\n orgId,\n // SQL-level dedup key — duplicate webhook deliveries from the same\n // platform produce the same key, so the unique index rejects the\n // second insert (H3 in the webhook security audit).\n externalEventKey: buildEventDedupKey(incoming),\n });\n\n const baseUrl = resolveBaseUrl(event);\n const processUrl = `${baseUrl}${FRAMEWORK_ROUTE_PREFIX}/integrations/process-task`;\n\n // Sign the dispatch with an HMAC token so the processor endpoint can\n // verify the request came from us and not the public internet. The\n // processor refuses unsigned requests in production (C3 in the webhook\n // security audit). In dev, dispatching unsigned is allowed and falls\n // through to the SQL atomic claim for double-processing protection.\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(taskId)}`;\n } catch (err) {\n // Distinguish \"secret not configured\" (the documented dev path) from\n // a real signing failure — silently swallowing both made malformed\n // secrets fail invisibly (L5 in the audit).\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${taskId}:`,\n err,\n );\n }\n }\n\n // Fire-and-forget: do NOT await the full response (the processor's run\n // takes minutes — we don't want to block the caller). BUT on Netlify\n // Lambda, when we return immediately, the runtime can freeze the function\n // before the outbound TCP handshake even starts, which leaves the dispatch\n // request stuck waiting for the 60s retry-sweep job. Race the fetch\n // against a short timer so the request gets a reasonable chance to leave\n // the box; the trade-off is at most a couple seconds of added webhook\n // latency, still inside Slack's timeout window.\n const dispatchPromise = fetch(processUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId }),\n }).catch((err) => {\n console.error(\"[integrations] Failed to dispatch processor request:\", err);\n });\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) =>\n setTimeout(resolve, PROCESSOR_DISPATCH_SETTLE_WAIT_MS),\n ),\n ]);\n}\n\n/**\n * Resolve the base URL we should dispatch the processor request to.\n * Prefers explicit env vars (most reliable on serverless), falls back to the\n * inbound request's headers.\n */\nexport function resolveBaseUrl(event: H3Event): string {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(fromEnv);\n\n try {\n const headers = (event as any).node?.req?.headers ?? (event as any).headers;\n const get = (name: string): string | undefined => {\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return headers.get(name) ?? undefined;\n }\n const lower = String(name).toLowerCase();\n const map = headers as Record<string, string | undefined>;\n return map[name] ?? map[lower];\n };\n const proto = get(\"x-forwarded-proto\") || \"http\";\n const host = get(\"host\") || `localhost:${process.env.PORT || 3000}`;\n return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {\n return withConfiguredAppBasePath(\n `http://localhost:${process.env.PORT || 3000}`,\n );\n }\n}\n\n/**\n * Run the actual agent loop for a previously-enqueued task. Called by the\n * processor endpoint in `plugin.ts`. This is a fresh function execution, so\n * it gets its own timeout budget independent of the inbound webhook handler.\n */\nexport async function processIntegrationTask(\n task: PendingTask,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const parsed = JSON.parse(task.payload) as {\n incoming: IncomingMessage;\n placeholderRef?: string;\n };\n await processIncomingMessage(parsed.incoming, options, {\n taskId: task.id,\n placeholderRef: parsed.placeholderRef,\n });\n}\n\n/**\n * Resolve thread, run agent loop, post response, persist thread data.\n * Shared between the new processor endpoint and any direct callers.\n */\nasync function processIncomingMessage(\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n opts: { taskId?: string; placeholderRef?: string } = {},\n): Promise<void> {\n const {\n adapter,\n systemPrompt,\n actions,\n model,\n apiKey,\n ownerEmail,\n engine: engineOption,\n } = options;\n\n // Resolve or create internal thread\n let mapping = await getThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n );\n\n if (!mapping) {\n const thread = await createThread(ownerEmail, {\n title: `${adapter.label}: ${incoming.senderName || incoming.senderId || \"User\"}`,\n });\n await saveThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n thread.id,\n incoming.platformContext,\n );\n mapping = {\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n internalThreadId: thread.id,\n platformContext: incoming.platformContext,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n }\n\n const threadId = mapping.internalThreadId;\n\n // Load existing thread history for context\n const thread = await getThread(threadId);\n const existingMessages: EngineMessage[] = [];\n if (thread?.threadData) {\n try {\n const data = JSON.parse(thread.threadData);\n if (Array.isArray(data.messages)) {\n for (const msg of data.messages) {\n const m = msg.message ?? msg;\n const textContent =\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content\n .filter((c: any) => c.type === \"text\")\n .map((c: any) => c.text)\n .join(\"\\n\")\n : \"\";\n if (m.role === \"user\") {\n existingMessages.push({\n role: \"user\",\n content: [{ type: \"text\", text: textContent }],\n });\n } else if (m.role === \"assistant\") {\n existingMessages.push({\n role: \"assistant\",\n content: [{ type: \"text\", text: textContent }],\n });\n }\n }\n }\n } catch {}\n }\n\n // Add the new user message. Include verified platform identity as lightweight\n // context so app-specific agents can attribute requests without guessing.\n const identityLines = [\n `Platform: ${incoming.platform}`,\n incoming.senderName ? `Sender name: ${incoming.senderName}` : null,\n incoming.senderEmail ? `Sender email: ${incoming.senderEmail}` : null,\n incoming.senderId ? `Sender ID: ${incoming.senderId}` : null,\n ].filter(Boolean);\n const userText =\n identityLines.length > 1\n ? `<integration-context>\\n${identityLines.join(\"\\n\")}\\n</integration-context>\\n\\n${incoming.text}`\n : incoming.text;\n\n const messages: EngineMessage[] = [\n ...existingMessages,\n { role: \"user\", content: [{ type: \"text\", text: userText }] },\n ];\n\n // Run agent loop via startRun, wrapped in a request context so that\n // tools (especially call-agent) can resolve the caller's org for org-scoped\n // A2A delegation. Without this, getRequestOrgId() returns undefined and\n // call-agent can't look up the org's a2a_secret or org_domain.\n const orgId = await resolveOrgIdForEmail(ownerEmail);\n const tools = actionsToEngineTools(actions);\n\n const runId = `integration-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Wait for the run to complete inside this fresh function execution.\n // We use a Promise so the processor endpoint can await the full lifecycle.\n await new Promise<void>((resolve) => {\n startRun(\n runId,\n threadId,\n async (send, signal) => {\n await runWithRequestContext(\n {\n userEmail: ownerEmail,\n orgId: orgId ?? undefined,\n // Lets downstream callers (call-agent script) apply tighter\n // budgets on integration paths without affecting normal\n // agent-chat. See `isIntegrationCallerRequest()`.\n isIntegrationCaller: true,\n integration: opts.taskId\n ? {\n taskId: opts.taskId,\n incoming,\n placeholderRef: opts.placeholderRef,\n }\n : undefined,\n },\n async () => {\n const effectiveApiKey = await resolveIntegrationApiKey(\n engineOption,\n ownerEmail,\n apiKey,\n );\n const engine = await resolveEngine({\n engineOption,\n apiKey: effectiveApiKey,\n model,\n });\n const resolvedModel =\n (await getStoredModelForEngine(engine)) ??\n model ??\n engine.defaultModel;\n\n return runAgentLoop({\n engine,\n model: resolvedModel,\n systemPrompt,\n tools,\n messages,\n actions,\n send,\n signal,\n });\n },\n );\n },\n async (completedRun: ActiveRun) => {\n try {\n const queuedA2AContinuation = hasQueuedA2AContinuation(completedRun);\n let responseText = collectFinalResponseTextFromAgentEvents(\n completedRun.events.map((runEvent) => runEvent.event),\n { fallbackToPreToolText: !queuedA2AContinuation },\n );\n if (!queuedA2AContinuation && !responseText.trim()) {\n const recoverableA2AArtifactText =\n extractRecoverableA2AArtifactToolResult(completedRun);\n if (recoverableA2AArtifactText) {\n responseText = recoverableA2AArtifactText;\n }\n }\n\n const suppressPlatformReply =\n queuedA2AContinuation &&\n isQueuedA2AContinuationDeferral(responseText);\n\n // If the run errored OR produced no text, post a graceful fallback so\n // the user isn't left wondering whether the bot saw their message.\n // Common case: an A2A delegation timed out and the agent loop bailed\n // before generating any user-facing text.\n const runErrored = completedRun.status === \"errored\";\n const runErrorText = completedRun.events\n .map((runEvent) =>\n runEvent.event.type === \"error\" ? runEvent.event.error : \"\",\n )\n .filter(Boolean)\n .join(\"\\n\");\n if (\n isLlmCredentialError(responseText) ||\n isLlmCredentialError(runErrorText)\n ) {\n responseText = formatLlmCredentialErrorMessage();\n } else if (\n !suppressPlatformReply &&\n (!responseText.trim() || runErrored)\n ) {\n if (runErrored) {\n responseText =\n (responseText.trim() ? responseText + \"\\n\\n\" : \"\") +\n \"I ran into a problem before I could finish that one. \" +\n \"If it was a complex analytics question, opening the analytics app \" +\n \"directly is the most reliable way to get an answer right now.\";\n } else {\n responseText = \"(No response)\";\n }\n }\n\n // Compute the deep-link to the dispatch UI for this thread, then\n // hand it to the adapter as a structured `threadDeepLinkUrl` so\n // platforms with rich blocks (Slack) can render a button instead\n // of inlining a `<url|text>` link that auto-unfurls into a giant\n // preview card.\n const baseUrl = process.env.APP_URL || process.env.URL || \"\";\n const appBaseUrl = baseUrl ? withConfiguredAppBasePath(baseUrl) : \"\";\n if (!suppressPlatformReply) {\n responseText = appendA2AArtifactLinks(\n responseText,\n collectToolResultSummaries(completedRun),\n { baseUrl: appBaseUrl || undefined },\n );\n }\n const threadDeepLinkUrl =\n appBaseUrl && threadId\n ? `${appBaseUrl}/?thread=${threadId}`\n : undefined;\n\n // Format and send back to platform — update the \"thinking…\"\n // placeholder in place if the adapter supplied one.\n if (!suppressPlatformReply) {\n const outgoing = adapter.formatAgentResponse(responseText, {\n threadDeepLinkUrl,\n });\n await adapter.sendResponse(outgoing, incoming, {\n placeholderRef: opts.placeholderRef,\n });\n }\n\n // Persist thread data\n await persistThreadData(\n threadId,\n incoming.text,\n completedRun,\n thread,\n );\n } catch (err) {\n console.error(\n `[integrations] Error sending response to ${incoming.platform}:`,\n err,\n );\n // Last-ditch: try to post a brief apology so the thread isn't silent.\n try {\n const fallback = adapter.formatAgentResponse(\n \"Something went wrong on my end while replying. Please try again.\",\n );\n await adapter.sendResponse(fallback, incoming);\n } catch {}\n } finally {\n resolve();\n }\n },\n );\n });\n}\n\nfunction hasQueuedA2AContinuation(completedRun: ActiveRun): boolean {\n return completedRun.events.some((runEvent) => {\n const event = runEvent.event;\n return (\n event.type === \"tool_done\" &&\n event.tool === \"call-agent\" &&\n String(event.result ?? \"\").includes(A2A_CONTINUATION_QUEUED_MARKER)\n );\n });\n}\n\nfunction extractRecoverableA2AArtifactToolResult(\n completedRun: ActiveRun,\n): string | null {\n for (let i = completedRun.events.length - 1; i >= 0; i--) {\n const event = completedRun.events[i].event;\n if (event.type !== \"tool_done\" || event.tool !== \"call-agent\") continue;\n\n const result = String(event.result ?? \"\").trim();\n if (\n result.includes(\"verified artifacts already exist\") &&\n result.includes(\"\\nArtifacts:\\n\")\n ) {\n return result;\n }\n }\n return null;\n}\n\nfunction isQueuedA2AContinuationDeferral(text: string): boolean {\n const normalized = text.replace(/\\s+/g, \" \").trim();\n if (!normalized) return true;\n if (normalized.includes(A2A_CONTINUATION_QUEUED_MARKER)) return true;\n return /\\b(?:still (?:working|processing)|is working on|taking longer than expected|will (?:post|update|surface|show up)|(?:it'?ll|it will|the result will|the final result will) (?:post|be posted|update|be updated|surface|show up)|will be (?:posted|updated|sent|shared)|final result when it finishes|while you wait|as soon as (?:it|it'?s|it is|the result|the artifact) (?:comes back|is ready|ready)|hang tight|relay from the .* agent)\\b/i.test(\n normalized,\n );\n}\n\n/**\n * Persist the user message and agent response to the thread data,\n * so the conversation history is available in the web UI too.\n */\nasync function persistThreadData(\n threadId: string,\n userText: string,\n completedRun: ActiveRun,\n thread: any,\n): Promise<void> {\n try {\n let repo: any;\n try {\n repo = JSON.parse(thread?.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n // Add user message\n const userMsg = {\n id: `msg-${Date.now()}-user`,\n role: \"user\",\n content: [{ type: \"text\", text: userText }],\n createdAt: new Date().toISOString(),\n };\n\n // Build assistant message from run events\n const assistantMsg = buildAssistantMessage(\n completedRun.events ?? [],\n completedRun.runId,\n );\n\n repo.messages.push(userMsg);\n if (assistantMsg) {\n repo.messages.push(assistantMsg);\n }\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread?.title || \"Integration Chat\",\n meta.preview || thread?.preview || \"\",\n repo.messages.length,\n );\n } catch {\n // Best-effort persistence\n }\n}\n"]}
1
+ {"version":3,"file":"webhook-handler.js","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,SAAS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QAAQ,CAAC,MAAM,CACrB,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,0BAA0B;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport type { PlatformAdapter, IncomingMessage } from \"./types.js\";\nimport { getThreadMapping, saveThreadMapping } from \"./thread-mapping-store.js\";\nimport { createThread, getThread } from \"../chat-threads/store.js\";\nimport {\n runAgentLoop,\n actionsToEngineTools,\n getOwnerActiveApiKey,\n getOwnerApiKey,\n engineToProvider,\n type ActionEntry,\n} from \"../agent/production-agent.js\";\nimport { PROVIDER_TO_ENV } from \"../agent/engine/provider-env-vars.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { readDeployCredentialEnv } from \"../server/credential-provider.js\";\nimport {\n getStoredModelForEngine,\n resolveEngine,\n} from \"../agent/engine/index.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { AgentEngine } from \"../agent/engine/types.js\";\nimport type { EngineMessage } from \"../agent/engine/types.js\";\nimport { startRun, type ActiveRun } from \"../agent/run-manager.js\";\nimport {\n buildAssistantMessage,\n extractThreadMeta,\n} from \"../agent/thread-data-builder.js\";\nimport { updateThreadData } from \"../chat-threads/store.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { resolveOrgIdForEmail } from \"../org/context.js\";\nimport {\n insertPendingTask,\n isDuplicateEventError,\n type PendingTask,\n} from \"./pending-tasks-store.js\";\nimport { signInternalToken } from \"./internal-token.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"./a2a-continuation-marker.js\";\nimport { collectFinalResponseTextFromAgentEvents } from \"../a2a/response-text.js\";\nimport {\n appendA2AArtifactLinks,\n type A2AToolResultSummary,\n} from \"../a2a/artifact-response.js\";\nimport { buildRuntimeContextPrompt } from \"../agent/runtime-context.js\";\n\nconst PROCESSOR_DISPATCH_SETTLE_WAIT_MS = 1_500;\n\ntype ToolDoneEvent = { type: \"tool_done\"; tool: string; result: string };\n\n/**\n * Build a stable per-event dedup key from the incoming message. The same\n * key is computed for every retry of the same event from the platform —\n * Slack/Telegram retry on timeout (3s for Slack), so we MUST treat the\n * second delivery as a duplicate and return 200 silently.\n *\n * The `(platform, external_event_key)` UNIQUE index in\n * `integration_pending_tasks` enforces this at the SQL layer, replacing\n * the previous in-memory Map (H3 in the webhook security audit) which\n * couldn't survive serverless cold starts.\n */\nfunction buildEventDedupKey(incoming: IncomingMessage): string {\n return `${incoming.platform}:${incoming.externalThreadId}:${incoming.timestamp}`;\n}\n\nexport interface WebhookHandlerOptions {\n adapter: PlatformAdapter;\n /** Resolved system prompt string */\n systemPrompt: string;\n /** Action entries for the agent */\n actions: Record<string, ActionEntry>;\n /** Model to use */\n model: string;\n /** Anthropic API key */\n apiKey: string;\n /** Agent engine to use. Defaults to the same resolver as web chat. */\n engine?:\n | AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Thread owner for personal/shared resource loading */\n ownerEmail: string;\n /**\n * Pre-parsed incoming message. When provided, handleWebhook skips its own\n * verification + parsing steps. Required when the caller has already read\n * the request body (h3 doesn't reliably cache parsed bodies, so re-parsing\n * the same event hangs on streaming providers).\n */\n incoming?: IncomingMessage;\n /** Optional hook to intercept inbound commands before agent execution */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n\nfunction explicitEngineName(\n engineOption: WebhookHandlerOptions[\"engine\"],\n): string | undefined {\n if (!engineOption) return undefined;\n if (typeof engineOption === \"string\") return engineOption;\n if (\n typeof engineOption === \"object\" &&\n !(\"stream\" in engineOption) &&\n typeof engineOption.name === \"string\"\n ) {\n return engineOption.name;\n }\n return undefined;\n}\n\nfunction isMultiTenantDeploy(): boolean {\n if (process.env.NODE_ENV !== \"production\") return false;\n return !isLocalDatabase();\n}\n\nfunction collectToolResultSummaries(\n completedRun: ActiveRun,\n): A2AToolResultSummary[] {\n return completedRun.events\n .map((runEvent) => runEvent.event)\n .filter((event): event is ToolDoneEvent => event.type === \"tool_done\")\n .map((event) => ({ tool: event.tool, result: event.result }));\n}\n\nasync function resolveIntegrationApiKey(\n engineOption: WebhookHandlerOptions[\"engine\"],\n ownerEmail: string,\n fallbackApiKey: string,\n): Promise<string | undefined> {\n const engineName = explicitEngineName(engineOption);\n if (engineName) {\n const provider = engineToProvider(engineName);\n const userApiKey = await getOwnerApiKey(provider, ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n const envVar = PROVIDER_TO_ENV[provider];\n const providerEnvKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\n return providerEnvKey || fallbackApiKey.trim() || undefined;\n }\n\n const userApiKey = await getOwnerActiveApiKey(ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n return fallbackApiKey.trim() || undefined;\n}\n\n/**\n * Process an incoming webhook from a messaging platform.\n *\n * Flow:\n * 1. Handle verification challenges (Slack url_verification, etc.)\n * 2. Verify webhook signature\n * 3. Parse incoming message (null = ignored event)\n * 4. Persist task to SQL\n * 5. Fire-and-forget POST to /_agent-native/integrations/process-task\n * (a fresh function execution with its own timeout budget)\n * 6. Return HTTP 200 immediately (within Slack's 3s SLA)\n *\n * The processor endpoint runs the actual agent loop. This split is essential\n * for serverless platforms (Netlify Lambda, Vercel, Cloudflare Workers) which\n * freeze the function as soon as the response is returned, killing any\n * lingering background promises.\n */\nexport async function handleWebhook(\n event: H3Event,\n options: WebhookHandlerOptions,\n): Promise<{ status: number; body: unknown }> {\n const { adapter, beforeProcess } = options;\n\n let incoming: IncomingMessage | null = options.incoming ?? null;\n\n // When the caller didn't pre-parse, run the full verify + parse pipeline.\n // Otherwise skip it — h3's body stream has already been consumed and a\n // second readBody call hangs on streaming providers.\n if (!incoming) {\n // Step 1: Handle platform-specific verification challenges\n const verification = await adapter.handleVerification(event);\n if (verification.handled) {\n return { status: 200, body: verification.response ?? \"ok\" };\n }\n\n // Step 2: Verify webhook signature\n const isValid = await adapter.verifyWebhook(event);\n if (!isValid) {\n return { status: 401, body: { error: \"Invalid webhook signature\" } };\n }\n\n // Step 3: Parse the incoming message\n incoming = await adapter.parseIncomingMessage(event);\n if (!incoming) {\n // Not a user message (bot message, edit, reaction, etc.) — acknowledge silently\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Dedup is enforced inside enqueueAndDispatch — the unique index on\n // `(platform, external_event_key)` raises a constraint violation we treat\n // as \"already enqueued\" and respond 200. We can't dedup BEFORE the\n // beforeProcess hook because some templates use beforeProcess for\n // command-style intercepts that are stateless and idempotent (e.g. a\n // Slack `/help` command that doesn't enqueue a task).\n\n if (beforeProcess) {\n const result = await beforeProcess(incoming, adapter);\n if (result.handled) {\n if (result.responseText?.trim()) {\n const outgoing = adapter.formatAgentResponse(result.responseText);\n await adapter.sendResponse(outgoing, incoming);\n }\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Step 4 + 5: Enqueue to SQL and dispatch to processor in a fresh request.\n try {\n await enqueueAndDispatch(event, incoming, options);\n } catch (err) {\n // Duplicate event delivery: the SQL UNIQUE constraint on\n // (platform, external_event_key) rejected the second insert. This is\n // the expected path when a platform retries an event that already\n // landed (e.g. Slack 3-second timeout) — return 200 so the platform\n // stops retrying. See H3 in the webhook security audit.\n if (isDuplicateEventError(err)) {\n return { status: 200, body: \"ok\" };\n }\n console.error(\n `[integrations] Failed to enqueue/dispatch ${incoming.platform} message:`,\n err,\n );\n // Return 500 so the platform retries. If the SQL insert failed for a\n // non-dup reason, the message is genuinely lost — better to let Slack\n // retry (it will re-fire the same event_callback) than silently drop it.\n return { status: 500, body: { error: \"enqueue failed\" } };\n }\n\n return { status: 200, body: \"ok\" };\n}\n\n/**\n * Persist the task to SQL and dispatch a fresh HTTP request to the processor\n * endpoint. The dispatch is fire-and-forget — we deliberately do NOT await\n * the resulting fetch, so the current handler can return immediately.\n *\n * This pattern works on every supported host:\n * - Netlify Lambda: function returns; the dispatched request hits a fresh\n * Lambda with its own function budget.\n * - Vercel Functions: same.\n * - Cloudflare Workers: same (no waitUntil dependency).\n * - Self-hosted Node: a separate request comes back through the same\n * server, but each handler still runs to completion.\n */\nasync function enqueueAndDispatch(\n event: H3Event,\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Resolve the org id once at enqueue-time so the processor doesn't have to\n // re-derive it (and so we can drop it on the row for observability).\n let orgId: string | null = null;\n try {\n orgId = (await resolveOrgIdForEmail(options.ownerEmail)) ?? null;\n } catch {\n orgId = null;\n }\n\n // Post a \"thinking…\" placeholder immediately if the adapter supports\n // in-place edits. The processor flow will update this same message with\n // the final answer, so users see one tidy thread reply instead of\n // \"[silence] → answer\". Adapters without edit support skip this and the\n // processor posts a fresh response.\n let placeholderRef: string | undefined;\n try {\n if (options.adapter.postProcessingPlaceholder) {\n const placeholder =\n await options.adapter.postProcessingPlaceholder(incoming);\n if (placeholder?.placeholderRef) {\n placeholderRef = placeholder.placeholderRef;\n }\n }\n } catch (err) {\n console.error(\"[integrations] postProcessingPlaceholder failed:\", err);\n }\n\n const payload = JSON.stringify({ incoming, placeholderRef });\n\n await insertPendingTask({\n id: taskId,\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n payload,\n ownerEmail: options.ownerEmail,\n orgId,\n // SQL-level dedup key — duplicate webhook deliveries from the same\n // platform produce the same key, so the unique index rejects the\n // second insert (H3 in the webhook security audit).\n externalEventKey: buildEventDedupKey(incoming),\n });\n\n const baseUrl = resolveBaseUrl(event);\n const processUrl = `${baseUrl}${FRAMEWORK_ROUTE_PREFIX}/integrations/process-task`;\n\n // Sign the dispatch with an HMAC token so the processor endpoint can\n // verify the request came from us and not the public internet. The\n // processor refuses unsigned requests in production (C3 in the webhook\n // security audit). In dev, dispatching unsigned is allowed and falls\n // through to the SQL atomic claim for double-processing protection.\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(taskId)}`;\n } catch (err) {\n // Distinguish \"secret not configured\" (the documented dev path) from\n // a real signing failure — silently swallowing both made malformed\n // secrets fail invisibly (L5 in the audit).\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${taskId}:`,\n err,\n );\n }\n }\n\n // Fire-and-forget: do NOT await the full response (the processor's run\n // takes minutes — we don't want to block the caller). BUT on Netlify\n // Lambda, when we return immediately, the runtime can freeze the function\n // before the outbound TCP handshake even starts, which leaves the dispatch\n // request stuck waiting for the 60s retry-sweep job. Race the fetch\n // against a short timer so the request gets a reasonable chance to leave\n // the box; the trade-off is at most a couple seconds of added webhook\n // latency, still inside Slack's timeout window.\n const dispatchPromise = fetch(processUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId }),\n }).catch((err) => {\n console.error(\"[integrations] Failed to dispatch processor request:\", err);\n });\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) =>\n setTimeout(resolve, PROCESSOR_DISPATCH_SETTLE_WAIT_MS),\n ),\n ]);\n}\n\n/**\n * Resolve the base URL we should dispatch the processor request to.\n * Prefers explicit env vars (most reliable on serverless), falls back to the\n * inbound request's headers.\n */\nexport function resolveBaseUrl(event: H3Event): string {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(fromEnv);\n\n try {\n const headers = (event as any).node?.req?.headers ?? (event as any).headers;\n const get = (name: string): string | undefined => {\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return headers.get(name) ?? undefined;\n }\n const lower = String(name).toLowerCase();\n const map = headers as Record<string, string | undefined>;\n return map[name] ?? map[lower];\n };\n const proto = get(\"x-forwarded-proto\") || \"http\";\n const host = get(\"host\") || `localhost:${process.env.PORT || 3000}`;\n return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {\n return withConfiguredAppBasePath(\n `http://localhost:${process.env.PORT || 3000}`,\n );\n }\n}\n\n/**\n * Run the actual agent loop for a previously-enqueued task. Called by the\n * processor endpoint in `plugin.ts`. This is a fresh function execution, so\n * it gets its own timeout budget independent of the inbound webhook handler.\n */\nexport async function processIntegrationTask(\n task: PendingTask,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const parsed = JSON.parse(task.payload) as {\n incoming: IncomingMessage;\n placeholderRef?: string;\n };\n await processIncomingMessage(parsed.incoming, options, {\n taskId: task.id,\n placeholderRef: parsed.placeholderRef,\n });\n}\n\n/**\n * Resolve thread, run agent loop, post response, persist thread data.\n * Shared between the new processor endpoint and any direct callers.\n */\nasync function processIncomingMessage(\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n opts: { taskId?: string; placeholderRef?: string } = {},\n): Promise<void> {\n const {\n adapter,\n systemPrompt,\n actions,\n model,\n apiKey,\n ownerEmail,\n engine: engineOption,\n } = options;\n const effectiveSystemPrompt = systemPrompt + buildRuntimeContextPrompt();\n\n // Resolve or create internal thread\n let mapping = await getThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n );\n\n if (!mapping) {\n const thread = await createThread(ownerEmail, {\n title: `${adapter.label}: ${incoming.senderName || incoming.senderId || \"User\"}`,\n });\n await saveThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n thread.id,\n incoming.platformContext,\n );\n mapping = {\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n internalThreadId: thread.id,\n platformContext: incoming.platformContext,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n }\n\n const threadId = mapping.internalThreadId;\n\n // Load existing thread history for context\n const thread = await getThread(threadId);\n const existingMessages: EngineMessage[] = [];\n if (thread?.threadData) {\n try {\n const data = JSON.parse(thread.threadData);\n if (Array.isArray(data.messages)) {\n for (const msg of data.messages) {\n const m = msg.message ?? msg;\n const textContent =\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content\n .filter((c: any) => c.type === \"text\")\n .map((c: any) => c.text)\n .join(\"\\n\")\n : \"\";\n if (m.role === \"user\") {\n existingMessages.push({\n role: \"user\",\n content: [{ type: \"text\", text: textContent }],\n });\n } else if (m.role === \"assistant\") {\n existingMessages.push({\n role: \"assistant\",\n content: [{ type: \"text\", text: textContent }],\n });\n }\n }\n }\n } catch {}\n }\n\n // Add the new user message. Include verified platform identity as lightweight\n // context so app-specific agents can attribute requests without guessing.\n const identityLines = [\n `Platform: ${incoming.platform}`,\n incoming.senderName ? `Sender name: ${incoming.senderName}` : null,\n incoming.senderEmail ? `Sender email: ${incoming.senderEmail}` : null,\n incoming.senderId ? `Sender ID: ${incoming.senderId}` : null,\n ].filter(Boolean);\n const userText =\n identityLines.length > 1\n ? `<integration-context>\\n${identityLines.join(\"\\n\")}\\n</integration-context>\\n\\n${incoming.text}`\n : incoming.text;\n\n const messages: EngineMessage[] = [\n ...existingMessages,\n { role: \"user\", content: [{ type: \"text\", text: userText }] },\n ];\n\n // Run agent loop via startRun, wrapped in a request context so that\n // tools (especially call-agent) can resolve the caller's org for org-scoped\n // A2A delegation. Without this, getRequestOrgId() returns undefined and\n // call-agent can't look up the org's a2a_secret or org_domain.\n const orgId = await resolveOrgIdForEmail(ownerEmail);\n const tools = actionsToEngineTools(actions);\n\n const runId = `integration-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Wait for the run to complete inside this fresh function execution.\n // We use a Promise so the processor endpoint can await the full lifecycle.\n await new Promise<void>((resolve) => {\n startRun(\n runId,\n threadId,\n async (send, signal) => {\n await runWithRequestContext(\n {\n userEmail: ownerEmail,\n orgId: orgId ?? undefined,\n // Lets downstream callers (call-agent script) apply tighter\n // budgets on integration paths without affecting normal\n // agent-chat. See `isIntegrationCallerRequest()`.\n isIntegrationCaller: true,\n integration: opts.taskId\n ? {\n taskId: opts.taskId,\n incoming,\n placeholderRef: opts.placeholderRef,\n }\n : undefined,\n },\n async () => {\n const effectiveApiKey = await resolveIntegrationApiKey(\n engineOption,\n ownerEmail,\n apiKey,\n );\n const engine = await resolveEngine({\n engineOption,\n apiKey: effectiveApiKey,\n model,\n });\n const resolvedModel =\n (await getStoredModelForEngine(engine)) ??\n model ??\n engine.defaultModel;\n\n return runAgentLoop({\n engine,\n model: resolvedModel,\n systemPrompt: effectiveSystemPrompt,\n tools,\n messages,\n actions,\n send,\n signal,\n });\n },\n );\n },\n async (completedRun: ActiveRun) => {\n try {\n const queuedA2AContinuation = hasQueuedA2AContinuation(completedRun);\n let responseText = collectFinalResponseTextFromAgentEvents(\n completedRun.events.map((runEvent) => runEvent.event),\n { fallbackToPreToolText: !queuedA2AContinuation },\n );\n if (!queuedA2AContinuation && !responseText.trim()) {\n const recoverableA2AArtifactText =\n extractRecoverableA2AArtifactToolResult(completedRun);\n if (recoverableA2AArtifactText) {\n responseText = recoverableA2AArtifactText;\n }\n }\n\n const suppressPlatformReply =\n queuedA2AContinuation &&\n isQueuedA2AContinuationDeferral(responseText);\n\n // If the run errored OR produced no text, post a graceful fallback so\n // the user isn't left wondering whether the bot saw their message.\n // Common case: an A2A delegation timed out and the agent loop bailed\n // before generating any user-facing text.\n const runErrored = completedRun.status === \"errored\";\n const runErrorText = completedRun.events\n .map((runEvent) =>\n runEvent.event.type === \"error\" ? runEvent.event.error : \"\",\n )\n .filter(Boolean)\n .join(\"\\n\");\n if (\n isLlmCredentialError(responseText) ||\n isLlmCredentialError(runErrorText)\n ) {\n responseText = formatLlmCredentialErrorMessage();\n } else if (\n !suppressPlatformReply &&\n (!responseText.trim() || runErrored)\n ) {\n if (runErrored) {\n responseText =\n (responseText.trim() ? responseText + \"\\n\\n\" : \"\") +\n \"I ran into a problem before I could finish that one. \" +\n \"If it was a complex analytics question, opening the analytics app \" +\n \"directly is the most reliable way to get an answer right now.\";\n } else {\n responseText = \"(No response)\";\n }\n }\n\n // Compute the deep-link to the dispatch UI for this thread, then\n // hand it to the adapter as a structured `threadDeepLinkUrl` so\n // platforms with rich blocks (Slack) can render a button instead\n // of inlining a `<url|text>` link that auto-unfurls into a giant\n // preview card.\n const baseUrl = process.env.APP_URL || process.env.URL || \"\";\n const appBaseUrl = baseUrl ? withConfiguredAppBasePath(baseUrl) : \"\";\n if (!suppressPlatformReply) {\n responseText = appendA2AArtifactLinks(\n responseText,\n collectToolResultSummaries(completedRun),\n { baseUrl: appBaseUrl || undefined },\n );\n }\n const threadDeepLinkUrl =\n appBaseUrl && threadId\n ? `${appBaseUrl}/?thread=${threadId}`\n : undefined;\n\n // Format and send back to platform — update the \"thinking…\"\n // placeholder in place if the adapter supplied one.\n if (!suppressPlatformReply) {\n const outgoing = adapter.formatAgentResponse(responseText, {\n threadDeepLinkUrl,\n });\n await adapter.sendResponse(outgoing, incoming, {\n placeholderRef: opts.placeholderRef,\n });\n }\n\n // Persist thread data\n await persistThreadData(\n threadId,\n incoming.text,\n completedRun,\n thread,\n );\n } catch (err) {\n console.error(\n `[integrations] Error sending response to ${incoming.platform}:`,\n err,\n );\n // Last-ditch: try to post a brief apology so the thread isn't silent.\n try {\n const fallback = adapter.formatAgentResponse(\n \"Something went wrong on my end while replying. Please try again.\",\n );\n await adapter.sendResponse(fallback, incoming);\n } catch {}\n } finally {\n resolve();\n }\n },\n );\n });\n}\n\nfunction hasQueuedA2AContinuation(completedRun: ActiveRun): boolean {\n return completedRun.events.some((runEvent) => {\n const event = runEvent.event;\n return (\n event.type === \"tool_done\" &&\n event.tool === \"call-agent\" &&\n String(event.result ?? \"\").includes(A2A_CONTINUATION_QUEUED_MARKER)\n );\n });\n}\n\nfunction extractRecoverableA2AArtifactToolResult(\n completedRun: ActiveRun,\n): string | null {\n for (let i = completedRun.events.length - 1; i >= 0; i--) {\n const event = completedRun.events[i].event;\n if (event.type !== \"tool_done\" || event.tool !== \"call-agent\") continue;\n\n const result = String(event.result ?? \"\").trim();\n if (\n result.includes(\"verified artifacts already exist\") &&\n result.includes(\"\\nArtifacts:\\n\")\n ) {\n return result;\n }\n }\n return null;\n}\n\nfunction isQueuedA2AContinuationDeferral(text: string): boolean {\n const normalized = text.replace(/\\s+/g, \" \").trim();\n if (!normalized) return true;\n if (normalized.includes(A2A_CONTINUATION_QUEUED_MARKER)) return true;\n return /\\b(?:still (?:working|processing)|is working on|taking longer than expected|will (?:post|update|surface|show up)|(?:it'?ll|it will|the result will|the final result will) (?:post|be posted|update|be updated|surface|show up)|will be (?:posted|updated|sent|shared)|final result when it finishes|while you wait|as soon as (?:it|it'?s|it is|the result|the artifact) (?:comes back|is ready|ready)|hang tight|relay from the .* agent)\\b/i.test(\n normalized,\n );\n}\n\n/**\n * Persist the user message and agent response to the thread data,\n * so the conversation history is available in the web UI too.\n */\nasync function persistThreadData(\n threadId: string,\n userText: string,\n completedRun: ActiveRun,\n thread: any,\n): Promise<void> {\n try {\n let repo: any;\n try {\n repo = JSON.parse(thread?.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n // Add user message\n const userMsg = {\n id: `msg-${Date.now()}-user`,\n role: \"user\",\n content: [{ type: \"text\", text: userText }],\n createdAt: new Date().toISOString(),\n };\n\n // Build assistant message from run events\n const assistantMsg = buildAssistantMessage(\n completedRun.events ?? [],\n completedRun.runId,\n );\n\n repo.messages.push(userMsg);\n if (assistantMsg) {\n repo.messages.push(assistantMsg);\n }\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread?.title || \"Integration Chat\",\n meta.preview || thread?.preview || \"\",\n repo.messages.length,\n );\n } catch {\n // Best-effort persistence\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-chat-plugin.d.ts","sourceRoot":"","sources":["../../src/server/agent-chat-plugin.ts"],"names":[],"mappings":"AAaA,OAAO,EASL,KAAK,WAAW,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E;AACzE,wBAAgB,mBAAmB,IAAI,gBAAgB,GAAG,IAAI,CAE7D"}
@@ -22,6 +22,7 @@ import { withConfiguredAppBasePath } from "./app-base-path.js";
22
22
  import { appendA2AArtifactLinks, buildA2ARecoverableArtifactMessage, } from "../a2a/artifact-response.js";
23
23
  import { updateTaskStatusMessage } from "../a2a/task-store.js";
24
24
  import { collectFinalResponseTextFromAgentEvents } from "../a2a/response-text.js";
25
+ import { buildRuntimeContextPrompt } from "../agent/runtime-context.js";
25
26
  // Lazy fs — loaded via dynamic import() on first use.
26
27
  // This avoids require() which bundlers convert to createRequire(import.meta.url)
27
28
  // that crashes on CF Workers where import.meta.url is undefined.
@@ -998,6 +999,7 @@ const FRAMEWORK_CORE_COMPACT = `
998
999
  9. **Never fabricate factual claims** — Do NOT invent numbers, metrics, records, query results, URLs, citations, source attributions, customer names, dates, or success rates. This applies inside generated artifacts too: decks, documents, reports, dashboards, Slack/email replies, and charts must not contain unsupported factual specifics. Only state factual numbers/claims when the user provided them or you retrieved them with an action/tool. If a data source is unavailable (missing credentials, connection error, tool failure), say so clearly and work with what you have. If a specific metric would be useful but is not known, use qualitative wording, placeholders like \`[metric TBD]\`, or clearly labeled draft assumptions instead of plausible-looking facts. Presenting made-up data as real is a critical failure — it is worse than admitting the limitation.
999
1000
  10. **Never fabricate success from tool errors** — When any tool call returns an error (marked \`isError: true\`, contains "Command failed", "Error:", or non-zero exit output), the operation FAILED. Do NOT synthesize a success narrative or describe what the action "would have" produced. Report the failure verbatim from the tool output. This applies especially to \`shell(command="pnpm action ...")\` calls: if the action threw, it did NOT succeed.
1000
1001
  11. **Find tools when unsure** — Use \`tool-search\` to find the exact action/tool for a capability. It searches the live registry, including connected MCP server tools.
1002
+ 12. **Relative dates use runtime context** — The \`<runtime-context>\` block gives the authoritative current date/time. Resolve "today", "yesterday", "last week", and similar phrases to explicit calendar dates before querying data or creating artifacts.
1001
1003
 
1002
1004
  ### Resources
1003
1005
 
@@ -1166,6 +1168,7 @@ const FRAMEWORK_CORE = `
1166
1168
  9. **Never fabricate factual claims** — Do NOT invent numbers, metrics, records, query results, URLs, citations, source attributions, customer names, dates, or success rates. This applies inside generated artifacts too: decks, documents, reports, dashboards, Slack/email replies, and charts must not contain unsupported factual specifics. Only state factual numbers/claims when the user provided them or you retrieved them with an action/tool. If a data source is unavailable (missing credentials, connection error, tool failure), say so clearly and work with what you have. If a specific metric would be useful but is not known, use qualitative wording, placeholders like \`[metric TBD]\`, or clearly labeled draft assumptions instead of plausible-looking facts. Presenting made-up data as real is a critical failure — it is worse than admitting the limitation.
1167
1169
  10. **Never fabricate success from tool errors** — When any tool call returns an error (marked \`isError: true\`, contains "Command failed", "Error:", or non-zero exit output), the operation FAILED. Do NOT synthesize a success narrative, format a result table, or describe what the action "would have" produced. Report the failure verbatim from the tool output. This applies especially to \`shell(command="pnpm action ...")\` calls: if the underlying action threw (visible in the error text), the action did NOT succeed — report the error, do not describe a successful outcome.
1168
1170
  11. **Find tools when unsure** — Use \`tool-search\` to find the exact action/tool for a capability. It searches the live registry, including connected MCP server tools added through config, settings, or the MCP hub.
1171
+ 12. **Relative dates use runtime context** — The \`<runtime-context>\` block gives the authoritative current date/time. Resolve "today", "yesterday", "last week", and similar phrases to explicit calendar dates before querying data or creating artifacts. When answering factual questions, include the exact date or date range you used.
1169
1172
 
1170
1173
  ### Resources
1171
1174
 
@@ -2232,9 +2235,10 @@ export function createAgentChatPlugin(options) {
2232
2235
  ? ""
2233
2236
  : await buildSchemaBlock(owner, devActive);
2234
2237
  const extra = await resolveExtraContext(context.event, owner);
2238
+ const runtimeContext = runtimeContextForEvent(context.event);
2235
2239
  const systemPrompt = devActive
2236
- ? devPrompt + resources + schemaBlock + extra
2237
- : basePrompt + resources + schemaBlock + extra;
2240
+ ? devPrompt + runtimeContext + resources + schemaBlock + extra
2241
+ : basePrompt + runtimeContext + resources + schemaBlock + extra;
2238
2242
  const model = options?.model ?? DEFAULT_MODEL;
2239
2243
  // Build tools — same as interactive handler but WITHOUT call-agent
2240
2244
  // to prevent infinite recursive A2A loops (agent calling itself).
@@ -2425,8 +2429,14 @@ export function createAgentChatPlugin(options) {
2425
2429
  ? DEV_FRAMEWORK_PROMPT_COMPACT
2426
2430
  : DEV_FRAMEWORK_PROMPT) + devActionsPrompt;
2427
2431
  const systemPrompt = devActiveMcp
2428
- ? mcpDevPrompt + resources + schemaBlock
2429
- : basePrompt + resources + schemaBlock;
2432
+ ? mcpDevPrompt +
2433
+ buildRuntimeContextPrompt() +
2434
+ resources +
2435
+ schemaBlock
2436
+ : basePrompt +
2437
+ buildRuntimeContextPrompt() +
2438
+ resources +
2439
+ schemaBlock;
2430
2440
  let accumulatedText = "";
2431
2441
  const controller = new AbortController();
2432
2442
  await runAgentLoop({
@@ -2778,12 +2788,22 @@ export function createAgentChatPlugin(options) {
2778
2788
  runCtx.systemPrompt = prompt;
2779
2789
  return prompt;
2780
2790
  };
2791
+ const runtimeContextForEvent = (event) => {
2792
+ const tzRaw = getHeader(event, "x-user-timezone");
2793
+ const timezone = typeof tzRaw === "string" &&
2794
+ tzRaw.trim().length > 0 &&
2795
+ tzRaw.trim().length < 64
2796
+ ? tzRaw.trim()
2797
+ : undefined;
2798
+ return buildRuntimeContextPrompt({ timezone });
2799
+ };
2781
2800
  const prodHandler = createProductionAgentHandler({
2782
2801
  actions: leanPrompt ? leanActions : prodActions,
2783
2802
  systemPrompt: async (event) => {
2784
2803
  const { owner, extra } = await prepareRun(event);
2804
+ const runtimeContext = runtimeContextForEvent(event);
2785
2805
  if (leanPrompt) {
2786
- return setSystemPromptOnContext(leanBasePrompt + extra);
2806
+ return setSystemPromptOnContext(leanBasePrompt + runtimeContext + extra);
2787
2807
  }
2788
2808
  const resources = await loadResourcesForPrompt(owner, lazyContext);
2789
2809
  // In lazy context mode, skip embedding the full schema — the agent
@@ -2791,7 +2811,7 @@ export function createAgentChatPlugin(options) {
2791
2811
  const schemaBlock = lazyContext
2792
2812
  ? ""
2793
2813
  : await buildSchemaBlock(owner, false);
2794
- return setSystemPromptOnContext(basePrompt + resources + schemaBlock + extra);
2814
+ return setSystemPromptOnContext(basePrompt + runtimeContext + resources + schemaBlock + extra);
2795
2815
  },
2796
2816
  model: options?.model ?? DEFAULT_MODEL,
2797
2817
  apiKey: options?.apiKey,
@@ -2864,14 +2884,15 @@ export function createAgentChatPlugin(options) {
2864
2884
  actions: devActions,
2865
2885
  systemPrompt: async (event) => {
2866
2886
  const { owner, extra } = await prepareRun(event);
2887
+ const runtimeContext = runtimeContextForEvent(event);
2867
2888
  if (leanPrompt) {
2868
- return setSystemPromptOnContext(leanBasePrompt + extra);
2889
+ return setSystemPromptOnContext(leanBasePrompt + runtimeContext + extra);
2869
2890
  }
2870
2891
  const resources = await loadResourcesForPrompt(owner, lazyContext);
2871
2892
  const schemaBlock = lazyContext
2872
2893
  ? ""
2873
2894
  : await buildSchemaBlock(owner, true);
2874
- return setSystemPromptOnContext(devPrompt + resources + schemaBlock + extra);
2895
+ return setSystemPromptOnContext(devPrompt + runtimeContext + resources + schemaBlock + extra);
2875
2896
  },
2876
2897
  model: options?.model,
2877
2898
  apiKey: options?.apiKey,