@sentry/junior 0.317.0 → 0.318.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{admin-CAugg87B.js → admin-UOHix_5P.js} +1 -1
  2. package/dist/{agent-runner-AjrEV6Qe.js → agent-runner-DeYymwh2.js} +183 -113
  3. package/dist/{agent-update-delivery-B_YIZcgf.js → agent-update-delivery-DH8bx7jU.js} +5 -5
  4. package/dist/api/schema.d.ts +42 -28
  5. package/dist/api/schema.js +3 -3
  6. package/dist/api.js +38 -41
  7. package/dist/{app-MoNAsVV5.d.ts → app-DKAOuaoC.d.ts} +4 -9
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +62 -91
  10. package/dist/{thread-context-CqZDKErp.js → auth-pause-state-f9hJM_zO.js} +6 -59
  11. package/dist/{catalog-runtime-DfSpJZdY.js → catalog-runtime-BfdAnztW.js} +1 -1
  12. package/dist/{channel-access-j-YAVYK4.js → channel-access-A0de5lRv.js} +1 -1
  13. package/dist/{chat-core-engine-aH85nEHv.js → chat-core-engine-D3Wd7f5n.js} +6 -6
  14. package/dist/{child-message-DHjQLEd1.js → child-message-peFWLcCZ.js} +1 -5
  15. package/dist/cli/chat.js +32 -24
  16. package/dist/cli/check.js +4 -4
  17. package/dist/cli/main.js +2 -2
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -5
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/context-BKF_5zzI.js +1833 -0
  22. package/dist/{continue-in-slack-D-FZ8Fin.js → continue-in-slack-YxwMQVeR.js} +3 -2
  23. package/dist/{conversation-feed--9S0_PXL.js → conversation-feed-Cj7IuBtM.js} +1 -1
  24. package/dist/{conversation-privacy-B1uXn5sf.js → conversation-privacy-Cr_dNW1p.js} +1 -1
  25. package/dist/{conversation-turn-BUE_7xaN.js → conversation-turn-Bru4w_FD.js} +111 -18
  26. package/dist/{create-DoDIYgtZ.js → create-Btl1y1rq.js} +13 -15
  27. package/dist/{credential-sync-BJOqGnjV.js → credential-sync-DTarZ63K.js} +17 -17
  28. package/dist/{db-BFmyYZtJ.js → db-of6e3sGt.js} +1943 -1189
  29. package/dist/{deployment-DXq9ZLU4.js → deployment-C0qXa0FD.js} +1 -1
  30. package/dist/{engine-context-CgQ7mlHt.js → engine-context-C_QL_bMQ.js} +52 -21
  31. package/dist/{html-B3VKTGbJ.js → html-9_pS9SjY.js} +6 -6
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{job-runner-A1lCkybD.js → job-runner-B2XEvpif.js} +11 -12
  34. package/dist/{lineage-Bktb0UcV.js → lineage-nh4z9iQN.js} +1 -1
  35. package/dist/{list-Bxvg5wXf.js → list-HRP3TIRl.js} +45 -37
  36. package/dist/{logging--smS7XRK.js → logging-BnOG0qz2.js} +3 -49
  37. package/dist/{mailbox-turn-uSXhUFc9.js → mailbox-turn-Byrry9o1.js} +220 -223
  38. package/dist/{parent-result-Ck1rFYRQ.js → markers-CTTtJqYn.js} +84 -52
  39. package/dist/{message-BNenhsmB.js → message-BRUuLgrY.js} +9 -10
  40. package/dist/{model-input-BReSnwHp.js → model-input-CFC62mf-.js} +2 -2
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +4 -4
  43. package/dist/{oauth-callback-server-CE4soEIY.js → oauth-callback-server-CjnnUr4o.js} +2 -2
  44. package/dist/{oauth-relay-C36gX1gH.js → oauth-relay-BvHFH0fV.js} +1 -1
  45. package/dist/{profile-BQ-iBDsZ.js → profile-iHw1uu32.js} +7 -7
  46. package/dist/{prompt-Dv7gkpD6.js → prompt-DEkStuxG.js} +10 -10
  47. package/dist/{registry-iXMT5Jmh.js → registry-Cl7Labpe.js} +7 -7
  48. package/dist/{reports-WKHfGTsU.js → reports-C1d9azyV.js} +2 -2
  49. package/dist/{resolve-tony4ibz.js → resolve-DC6zBuDV.js} +5 -5
  50. package/dist/{result-Bta_dlWa.js → result-DxewDuXb.js} +12 -12
  51. package/dist/{run-conversation-DL6ru7iW.js → run-conversation-Cz2ubZK-.js} +6 -5
  52. package/dist/{runner-BstDRbD9.js → runner-99YxVN_r.js} +10 -18
  53. package/dist/{sandbox-egress-signals-oSJMJOnn.js → sandbox-egress-signals-CgoX5CTI.js} +1 -1
  54. package/dist/{schema-DfqrHACA.js → schema-BTojNBr5.js} +2 -2
  55. package/dist/{sender-actors-CPglLd5R.js → sender-actors-77zTQbSG.js} +7 -6
  56. package/dist/{service-account-CTV_jaNu.js → service-account-YDCPSByj.js} +3 -3
  57. package/dist/{skills-BCEU41zM.js → skills-CleC0Hze.js} +5 -4
  58. package/dist/{slack-conversation-unfurl-DxVmhbGP.js → slack-conversation-unfurl-BNQLC12R.js} +7 -7
  59. package/dist/{spawn-frczVPIr.js → spawn-DuZfodPa.js} +7 -10
  60. package/dist/{system-prompt-table-CiXy0eNR.js → system-prompt-table-Ci6Ck4gk.js} +2 -2
  61. package/dist/{task-runner-C9Yc2_ae.js → task-runner-BJ9Up3bG.js} +18 -15
  62. package/dist/{topics-SRN7IVX-.js → topics-BoCkoPJJ.js} +2 -5
  63. package/dist/{turn-membership-CENFf3kI.js → turn-membership-VT7XZh-L.js} +4 -4
  64. package/dist/{turn-wake-BhloiI2h.js → turn-wake-C7HeLHAM.js} +4 -4
  65. package/dist/{types-C4iC-IMC.js → types-DCzTAA63.js} +55 -49
  66. package/dist/{users-ByG5RCEJ.js → users-Cb9c1k9q.js} +1 -1
  67. package/dist/{validation-8gjfR91V.js → validation-BiUmWPhy.js} +1 -1
  68. package/dist/{version-BeZhWWBE.js → version-VEXiEcZu.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{worker-BqMQQNRk.js → worker-ChWYQdhm.js} +5 -5
  71. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  72. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  73. package/package.json +5 -5
  74. package/dist/config-CHQ8X251.js +0 -2422
@@ -1,22 +1,22 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $ as isProviderRetryError, A as ACTIVE_LOCK_TTL_MS, J as createProviderError, K as ProviderError, O as cacheKeyPrefix, P as withLock, S as rerankTexts, _ as completeObject$1, b as gatewayCostUsd, d as normalizeSlackEmojiName, f as TURN_REASONING_LEVELS, g as completeDecision$1, h as GEN_AI_SERVER_ADDRESS, i as getSlackBotToken, k as createCache, m as GEN_AI_PROVIDER_NAME, n as getChatConfig, t as botConfig, tt as resolveGatewayCredential, v as completeText$1, w as searchWeb$1, x as generateImages$1, y as embedTexts$1 } from "./config-CHQ8X251.js";
3
- import { A as automationVersionSchema, En as AGENT_UPDATE_EVENT_TYPE, Gn as usageSchema, Hn as isValidTimeZone, In as DEFAULT_NOTIFICATION_SCHEDULE, Ln as isWithinNotificationSchedule, Mn as automationTaskColumns, Nn as automationTaskDescription, Pn as automationTaskSchema, Rn as notificationScheduleSchema, Tt as sameActorIdentity, Un as CONTENT_VERSION_HEADER, _n as buttonUserInputField, _t as historyReplacementSchema, a as UPDATE_TODOS_TOOL_NAME, bn as normalizeUserInputAnswer, fn as inboxItemQuestion, ft as encodeAgentHistoryPayload, hn as USER_INPUT_NOTE, i as TODO_STATUSES, jn as automationSkillNameSchema, ln as eventAutomationSchema, lt as decodeStoredConversationEvent, mn as USER_INPUT_LIMITS, n as SELF_TODO_ASSIGNEE, nn as scheduledAutomationSchema, o as isOpenTodoStatus, ot as conversationEventDataSchema, pn as inboxItemRequestSchema, pt as isAgentHistoryData, r as TODOS_REGISTRATION_NAME, rt as agentTypeSchema, t as OPEN_TODO_STATUSES, un as eventAutomationTriggerSchema, ut as newConversationEventSchema, zt as inboxItemChangeRecordSchema } from "./types-C4iC-IMC.js";
4
- import { D as buildSentryConversationUrl, E as withSpan, N as normalizeIdentityEmail, P as toOptionalString, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, h as logWarn, i as extractGenAiUsageAttributes, j as GOOGLE_IDENTITY_PROVIDER, m as logInfo, p as logException, x as setSpanStatus } from "./logging--smS7XRK.js";
5
- import { L as mapBounded, d as SANDBOX_WORKSPACE_ROOT, g as RUNTIME_CONTEXT_TEXT_STARTS, h as createPluginLogger, n as toPromptContributionContext, r as runPluginHooksAtOnce, s as SANDBOX_JUNIOR_ROOT } from "./prompt-Dv7gkpD6.js";
6
- import { _ as withScope, n as captureMessage } from "./sentry-CPbZjomA.js";
7
- import { a as resolveConversationWorkQueueTopic, r as PLUGIN_TASK_QUEUE_TOPIC } from "./topics-SRN7IVX-.js";
8
- import { t as canExposeConversationPayload } from "./conversation-privacy-B1uXn5sf.js";
2
+ import { $ as resolveGatewayModel, B as getSlackBotToken, D as parseSlackChannelReferenceId, J as normalizeSlackEmojiName, L as botConfig, O as parseSlackTeamId, P as parseSlackMessageTs, Q as findGatewayModel, R as getChatConfig, T as withLock, Y as TURN_REASONING_LEVELS, Z as GATEWAY_PROVIDER, a as credentialSubjectSchema, at as streamSimpleAnthropic, b as getStateValues, c as createSlackActor, d as isSlackUserId, et as calculateCost, f as isUserActor, it as streamAnthropic, k as parseSlackUserId, m as parseStoredSlackActor, nt as getEnvApiKey, p as parseActorUserId, r as credentialContextSchema, rt as registerApiProvider, tt as completeSimple, u as isActorUserId, v as getDefaultRedisStateAdapterFor, x as setStateValues, y as getStateAdapter } from "./context-BKF_5zzI.js";
3
+ import { A as automationVersionSchema, An as isWithinNotificationSchedule, Dn as automationTaskSchema, En as automationTaskDescription, Fn as isValidTimeZone, Gn as usageSchema, In as CONTENT_VERSION_HEADER, Tn as automationTaskColumns, Tt as sameActorIdentity, Wn as gatewayOnlyProviders, _n as buttonUserInputField, _t as historyReplacementSchema, a as UPDATE_TODOS_TOOL_NAME, bn as normalizeUserInputAnswer, fn as inboxItemQuestion, ft as encodeAgentHistoryPayload, hn as USER_INPUT_NOTE, i as TODO_STATUSES, jn as notificationScheduleSchema, kn as DEFAULT_NOTIFICATION_SCHEDULE, ln as eventAutomationSchema, lt as decodeStoredConversationEvent, mn as USER_INPUT_LIMITS, n as SELF_TODO_ASSIGNEE, nn as scheduledAutomationSchema, o as isOpenTodoStatus, ot as conversationEventDataSchema, pn as inboxItemRequestSchema, pt as isAgentHistoryData, r as TODOS_REGISTRATION_NAME, rt as agentTypeSchema, t as OPEN_TODO_STATUSES, un as eventAutomationTriggerSchema, ut as newConversationEventSchema, wn as automationSkillNameSchema, zn as AGENT_UPDATE_EVENT_TYPE, zt as inboxItemChangeRecordSchema } from "./types-DCzTAA63.js";
4
+ import { A as toOptionalString, D as GOOGLE_IDENTITY_PROVIDER, T as withSpan, _ as serializeGenAiAttribute, b as setSpanStatus, f as logException, g as runBestEffort, i as extractGenAiUsageSummary, k as normalizeIdentityEmail, m as logWarn, p as logInfo, r as extractGenAiUsageAttributes, s as getLogContextAttributes, y as setSpanAttributes } from "./logging-BnOG0qz2.js";
5
+ import { G as mapBounded, R as unwrapCurrentInstruction, d as SANDBOX_WORKSPACE_ROOT, g as RUNTIME_CONTEXT_TEXT_STARTS, h as createPluginLogger, n as toPromptContributionContext, r as runPluginHooksAtOnce, s as SANDBOX_JUNIOR_ROOT } from "./prompt-DEkStuxG.js";
6
+ import { i as PLUGIN_TASK_QUEUE_TOPIC, o as toOptionalTrimmed } from "./topics-BoCkoPJJ.js";
7
+ import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-Cr_dNW1p.js";
8
+ import { _ as withScope, a as getClient$1, n as captureMessage } from "./sentry-CPbZjomA.js";
9
9
  import * as z from "zod";
10
- import { createGatewayProvider } from "@ai-sdk/gateway";
11
- import { transcribe } from "ai";
10
+ import { SQL, and, arrayOverlaps, asc, count, desc, eq, exists, getTableName, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, max, ne, not, notExists, or, sql } from "drizzle-orm";
11
+ import { PgAsyncDatabase, QueryBuilder, alias, bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgSequence, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
12
+ import { MAX_CONVERSATION_CHANGES, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeFilterSchema, codeChangeInputSchema, codeRepositoryInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, defineConversationEvent, defineJuniorPlugin, definePluginTool, definePromptContext, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagText, eventDataSchema, eventInputSchema, eventMatchFieldsSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, getSourceKey, identitySchema, isPluginModelCostEventName, isSlackDestination, locationSchema, markdownPlainText, normalizeEventIdentifier, normalizeEventMatch, objectFactFields, objectIconPath, objectLinkFilterSchema, objectPresentation, objectTypeSchema, pluginApiRouteRequestContextSchema, pluginEventsSchema, pluginModelCostEventNames, pluginTaskStartInputSchema, pluginToolOutputSchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, taskOutcomeSchema, userSchema, withToolContext } from "@sentry/junior-plugin-api";
12
13
  import { isDeepStrictEqual } from "node:util";
13
14
  import { AsyncLocalStorage } from "node:async_hooks";
14
15
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
15
- import { MAX_CONVERSATION_CHANGES, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeFilterSchema, codeChangeInputSchema, codeRepositoryInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, defineConversationEvent, defineJuniorPlugin, definePluginTool, definePromptContext, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagText, eventDataSchema, eventInputSchema, eventMatchFieldsSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, getSourceKey, identitySchema, isPluginModelCostEventName, isSlackDestination, localDestinationSchema, locationSchema, markdownPlainText, normalizeEventIdentifier, normalizeEventMatch, objectFactFields, objectIconPath, objectLinkFilterSchema, objectPresentation, objectTypeSchema, pluginApiRouteRequestContextSchema, pluginEventsSchema, pluginModelCostEventNames, pluginTaskStartInputSchema, pluginToolOutputSchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, taskOutcomeSchema, userSchema, withToolContext } from "@sentry/junior-plugin-api";
16
- import { SQL, and, arrayOverlaps, asc, count, desc, eq, exists, getTableName, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, max, ne, not, notExists, or, sql } from "drizzle-orm";
17
- import { PgAsyncDatabase, QueryBuilder, alias, bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgSequence, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
18
- import { createMemoryState } from "@chat-adapter/state-memory";
19
- import { createRedisState } from "@chat-adapter/state-redis";
16
+ import { createGatewayProvider } from "@ai-sdk/gateway";
17
+ import { getVercelOidcToken } from "@vercel/oidc";
18
+ import { Experimental_DecisionRefusalError, NoImageGeneratedError, NoObjectGeneratedError, embedMany, experimental_decide, generateImage, generateObject, generateText, rerank, transcribe } from "ai";
19
+ import { renderSystemMessageUpdate } from "@earendil-works/pi-ai";
20
20
  import { InvalidArgumentError, Option } from "commander";
21
21
  import { Type } from "@sinclair/typebox";
22
22
  import { Value } from "@sinclair/typebox/value";
@@ -29,51 +29,6 @@ import { Agent } from "undici";
29
29
  import { readMigrationFiles } from "drizzle-orm/migrator";
30
30
  import pg from "pg";
31
31
  import { drizzle as drizzle$1 } from "drizzle-orm/node-postgres";
32
- // src/chat/configuration/defaults.ts
33
- let installDefaults = {};
34
- function cloneDefaults(defaults) {
35
- return structuredClone(defaults);
36
- }
37
- /** Store install-wide configuration defaults. */
38
- function setConfigDefaults(defaults) {
39
- if (defaults === void 0) {
40
- installDefaults = {};
41
- return;
42
- }
43
- if (typeof defaults !== "object" || defaults === null || Array.isArray(defaults)) throw new Error("configDefaults must be an object keyed by plugin config key");
44
- installDefaults = cloneDefaults(Object.fromEntries(Object.entries(defaults)));
45
- }
46
- /** Return the install-wide configuration defaults (empty object when none set). */
47
- function getConfigDefaults() {
48
- return cloneDefaults(installDefaults);
49
- }
50
- // src/chat/conversations/destination.ts
51
- function requireLocalDestination(conversationId) {
52
- const parsed = localDestinationSchema.safeParse({
53
- platform: "local",
54
- conversationId
55
- });
56
- if (!parsed.success) throw new Error(`Invalid local conversation id: ${conversationId}`);
57
- return parsed.data;
58
- }
59
- /**
60
- * Keep a stored Destination, or create the temporary local Destination.
61
- *
62
- * TODO(dcramer): Delete this module after Conversation and AgentRun use
63
- * Location, and web and event Turns no longer need a local
64
- * Destination.
65
- */
66
- function resolveConversationDestination(args) {
67
- return args.existing ?? requireLocalDestination(args.conversationId);
68
- }
69
- /**
70
- * Create the local Destination of a Conversation that needs its own, such as
71
- * a Lead's child. A child agent's id is not a local id, so it gets one under
72
- * `local:`.
73
- */
74
- function ownLocalDestination(conversationId) {
75
- return requireLocalDestination(conversationId.startsWith("local:") ? conversationId : `local:${conversationId}`);
76
- }
77
32
  // src/db/schema/timestamps.ts
78
33
  const timestamptz = (name) => timestamp(name, { withTimezone: true });
79
34
  // src/db/schema/artifacts.ts
@@ -759,6 +714,8 @@ const juniorTurns = pgTable("junior_turns", {
759
714
  failureCode: text("failure_code").$type(),
760
715
  failureReason: text("failure_reason").$type(),
761
716
  failureEventId: text("failure_event_id"),
717
+ discardedCostMicroUsd: bigint("discarded_cost_micro_usd", { mode: "number" }).default(0).notNull(),
718
+ discardedTokens: jsonb("discarded_tokens").$type(),
762
719
  createdAt: timestamptz("created_at").defaultNow().notNull(),
763
720
  updatedAt: timestamptz("updated_at").defaultNow().notNull(),
764
721
  startedAt: timestamptz("started_at"),
@@ -1544,17 +1501,9 @@ const juniorTurnOutbox = pgTable("junior_turn_outbox", {
1544
1501
  index("junior_turn_outbox_pending_idx").on(table.createdAt).where(sql`${table.state} = 'pending'`)
1545
1502
  ]);
1546
1503
  // src/chat/conversations/sql/listed.ts
1547
- /**
1548
- * Match top-level Conversations: one with no parent, or a Lead's child,
1549
- * which is top-level Space work. Top-level lists show these.
1550
- */
1504
+ /** Match top-level Conversations: tree roots, with no parent. */
1551
1505
  function topLevelConversation() {
1552
- return or(isNull(juniorConversations.parentConversationId), sql`${juniorConversations.parentConversationId} = any(array(
1553
- select listed_lead.conversation_id
1554
- from junior_conversations listed_lead
1555
- where listed_lead.kind = 'lead'
1556
- and listed_lead.space_id is not null
1557
- ))`);
1506
+ return isNull(juniorConversations.parentConversationId);
1558
1507
  }
1559
1508
  /**
1560
1509
  * Match Conversations that are not a Lead. Its Space's page opens the Lead,
@@ -1564,9 +1513,9 @@ function notLeadConversation() {
1564
1513
  return or(isNull(juniorConversations.kind), ne(juniorConversations.kind, "lead"));
1565
1514
  }
1566
1515
  /**
1567
- * Match Conversations that lists and searches may show: top-level
1568
- * Conversations that are not an unkept Quick question or a Lead. Each list adds its own access and
1569
- * scope filters. Structural root checks, such as retention, do not use this.
1516
+ * Match Conversations that lists and searches may show: roots that are not
1517
+ * an unkept Quick question or a Lead. Each list adds its own access and scope
1518
+ * filters. Structural root checks, such as retention, do not use this.
1570
1519
  */
1571
1520
  function listedConversation() {
1572
1521
  return and(topLevelConversation(), isNull(juniorConversations.quickQuestionAt), notLeadConversation());
@@ -1599,67 +1548,6 @@ function isLeadSql$1(conversationId) {
1599
1548
  and lead_parent.kind = 'lead'
1600
1549
  )`;
1601
1550
  }
1602
- // src/chat/slack/timestamp.ts
1603
- /** Native Slack message timestamp, safe to pass as Slack Web API `message_ts`. */
1604
- const slackMessageTsSchema = z.string().trim().regex(/^\d+(?:\.\d+)?$/).brand();
1605
- /** Parse a native Slack message timestamp from untrusted message metadata. */
1606
- function parseSlackMessageTs(value) {
1607
- const parsed = slackMessageTsSchema.safeParse(value);
1608
- return parsed.success ? parsed.data : void 0;
1609
- }
1610
- /**
1611
- * Write a time in milliseconds as a Slack timestamp, for input that has no
1612
- * Slack message of its own, such as a submitted form.
1613
- */
1614
- function slackMessageTsFromMs(ms) {
1615
- return slackMessageTsSchema.parse((ms / 1e3).toFixed(6));
1616
- }
1617
- // src/chat/slack/ids.ts
1618
- const slackChannelIdSchema = z.string().regex(/^[CDG][A-Z0-9]+$/).brand();
1619
- const slackTeamIdSchema = z.string().regex(/^T[A-Z0-9]+$/).brand();
1620
- const slackUserIdSchema = z.string().regex(/^[UW][A-Z0-9]+$/).brand();
1621
- const slackBotIdSchema = z.string().regex(/^B[A-Z0-9]+$/).brand();
1622
- const SLACK_CHANNEL_MENTION_RE = /^<#([CDG][A-Z0-9]+)(?:\|[^>]*)?>$/;
1623
- function slackChannelReferenceCandidate(value) {
1624
- const trimmed = value.trim();
1625
- if (!trimmed.startsWith("slack:")) return trimmed;
1626
- const parts = trimmed.split(":");
1627
- if (parts.length === 2) return parts[1]?.trim() ?? "";
1628
- if (parts.length === 3 && parseSlackMessageTs(parts[2])) return parts[1]?.trim() ?? "";
1629
- return "";
1630
- }
1631
- /** Parse an exact Slack channel/conversation ID from untrusted input. */
1632
- function parseSlackChannelId(value) {
1633
- if (typeof value !== "string") return void 0;
1634
- const parsed = slackChannelIdSchema.safeParse(value.trim());
1635
- return parsed.success ? parsed.data : void 0;
1636
- }
1637
- /**
1638
- * Parse a channel id from common tool/model reference forms.
1639
- *
1640
- * Accepts exact ids (`C123`), Slack mentions (`<#C123>` / `<#C123|name>`),
1641
- * and Junior slack references (`slack:C123`, `slack:C123:ts`). Plain channel
1642
- * names are not ids and are rejected here.
1643
- */
1644
- function parseSlackChannelReferenceId(value) {
1645
- if (typeof value !== "string") return void 0;
1646
- const trimmed = value.trim();
1647
- const mentionMatch = SLACK_CHANNEL_MENTION_RE.exec(trimmed);
1648
- if (mentionMatch?.[1]) return parseSlackChannelId(mentionMatch[1]);
1649
- return parseSlackChannelId(slackChannelReferenceCandidate(trimmed));
1650
- }
1651
- /** Parse a Slack workspace/team ID from untrusted metadata. */
1652
- function parseSlackTeamId(value) {
1653
- if (typeof value !== "string") return void 0;
1654
- const parsed = slackTeamIdSchema.safeParse(value.trim());
1655
- return parsed.success ? parsed.data : void 0;
1656
- }
1657
- /** Parse a Slack user ID from untrusted metadata. */
1658
- function parseSlackUserId(value) {
1659
- if (typeof value !== "string") return void 0;
1660
- const parsed = slackUserIdSchema.safeParse(value.trim());
1661
- return parsed.success ? parsed.data : void 0;
1662
- }
1663
1551
  // src/chat/destination.ts
1664
1552
  /** Build Junior's canonical destination from Slack workspace and channel ids. */
1665
1553
  function createSlackDestination(input) {
@@ -1728,12 +1616,12 @@ async function rootConversationIsArchived(executor, conversationId) {
1728
1616
  return Boolean(row?.archivedAt);
1729
1617
  }
1730
1618
  /**
1731
- * Upsert one linked user as a participant on a root conversation.
1732
- * No-ops and returns false when the identity is missing, unlinked, or not a
1733
- * user. `resubscribe` ends an unsubscribe: the user addressed Junior again.
1734
- * With `message`, only a Slack author is added: on the web and other
1735
- * surfaces a person joins explicitly, so their Message only updates a row
1736
- * that they already have.
1619
+ * Upsert one linked user as a participant on a root conversation, and
1620
+ * return whether they are one now. No-ops and returns false when the
1621
+ * identity is missing, unlinked, or not a user. `resubscribe` ends an
1622
+ * unsubscribe: the user addressed Junior again. With `message`, only a Slack
1623
+ * author is added: on the web and other surfaces a person joins explicitly,
1624
+ * so their Message only updates a row that they already have.
1737
1625
  */
1738
1626
  async function recordConversationParticipant(executor, args) {
1739
1627
  const [identity] = await executor.db().select({
@@ -1748,10 +1636,7 @@ async function recordConversationParticipant(executor, args) {
1748
1636
  lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, ${at})`,
1749
1637
  ...args.resubscribe ? { unsubscribedAt: null } : void 0
1750
1638
  };
1751
- if (args.message && identity.provider !== "slack") {
1752
- await executor.db().update(juniorConversationParticipants).set(set).where(and(eq(juniorConversationParticipants.userId, identity.userId), eq(juniorConversationParticipants.rootConversationId, rootConversationId)));
1753
- return true;
1754
- }
1639
+ if (args.message && identity.provider !== "slack") return (await executor.db().update(juniorConversationParticipants).set(set).where(and(eq(juniorConversationParticipants.userId, identity.userId), eq(juniorConversationParticipants.rootConversationId, rootConversationId))).returning({ userId: juniorConversationParticipants.userId })).length > 0;
1755
1640
  await executor.db().insert(juniorConversationParticipants).values({
1756
1641
  userId: identity.userId,
1757
1642
  rootConversationId,
@@ -1884,259 +1769,6 @@ function addAgentTurnUsage(...usages) {
1884
1769
  };
1885
1770
  return hasAgentTurnUsage(result) ? result : void 0;
1886
1771
  }
1887
- // src/chat/state/adapter.ts
1888
- var adapter_exports = /* @__PURE__ */ __exportAll({ getStateAdapter: () => getStateAdapter });
1889
- const ACTIVE_LOCK_HEARTBEAT_MS = 3e4;
1890
- const REDIS_STATE_KEY_PREFIX = "chat-sdk";
1891
- let stateAdapter;
1892
- let redisStateAdapter;
1893
- /** Lazily connect state operations, including queued-adapter lock heartbeats. */
1894
- function createConnectingStateAdapter(base) {
1895
- const connected = async (operation) => {
1896
- await base.connect();
1897
- return await operation();
1898
- };
1899
- return {
1900
- appendToList: (key, value, options) => connected(() => base.appendToList(key, value, options)),
1901
- connect: () => base.connect(),
1902
- disconnect: () => base.disconnect(),
1903
- subscribe: (threadId) => connected(() => base.subscribe(threadId)),
1904
- unsubscribe: (threadId) => connected(() => base.unsubscribe(threadId)),
1905
- isSubscribed: (threadId) => connected(() => base.isSubscribed(threadId)),
1906
- acquireLock: (threadId, ttlMs) => connected(() => base.acquireLock(threadId, ttlMs)),
1907
- releaseLock: (lock) => connected(() => base.releaseLock(lock)),
1908
- extendLock: (lock, ttlMs) => connected(() => base.extendLock(lock, ttlMs)),
1909
- forceReleaseLock: (threadId) => connected(() => base.forceReleaseLock(threadId)),
1910
- enqueue: (threadId, entry, maxSize) => connected(() => base.enqueue(threadId, entry, maxSize)),
1911
- dequeue: (threadId) => connected(() => base.dequeue(threadId)),
1912
- queueDepth: (threadId) => connected(() => base.queueDepth(threadId)),
1913
- get: (key) => connected(() => base.get(key)),
1914
- getList: (key) => connected(() => base.getList(key)),
1915
- set: (key, value, ttlMs) => connected(() => base.set(key, value, ttlMs)),
1916
- setIfNotExists: (key, value, ttlMs) => connected(() => base.setIfNotExists(key, value, ttlMs)),
1917
- delete: (key) => connected(() => base.delete(key))
1918
- };
1919
- }
1920
- function createPrefixedStateAdapter(base, prefix) {
1921
- const prefixed = (value) => `${prefix}:${value}`;
1922
- const unprefixed = (value) => value.startsWith(`${prefix}:`) ? value.slice(prefix.length + 1) : value;
1923
- const prefixLock = (lock) => ({
1924
- ...lock,
1925
- threadId: prefixed(lock.threadId)
1926
- });
1927
- const unprefixLock = (lock) => ({
1928
- ...lock,
1929
- threadId: unprefixed(lock.threadId)
1930
- });
1931
- return {
1932
- appendToList: (key, value, options) => base.appendToList(prefixed(key), value, options),
1933
- connect: () => base.connect(),
1934
- disconnect: () => base.disconnect(),
1935
- subscribe: (threadId) => base.subscribe(prefixed(threadId)),
1936
- unsubscribe: (threadId) => base.unsubscribe(prefixed(threadId)),
1937
- isSubscribed: (threadId) => base.isSubscribed(prefixed(threadId)),
1938
- acquireLock: async (threadId, ttlMs) => {
1939
- const lock = await base.acquireLock(prefixed(threadId), ttlMs);
1940
- return lock ? unprefixLock(lock) : null;
1941
- },
1942
- releaseLock: (lock) => base.releaseLock(prefixLock(lock)),
1943
- extendLock: async (lock, ttlMs) => {
1944
- const prefixedLock = prefixLock(lock);
1945
- const extended = await base.extendLock(prefixedLock, ttlMs);
1946
- if (extended) lock.expiresAt = prefixedLock.expiresAt;
1947
- return extended;
1948
- },
1949
- forceReleaseLock: (threadId) => base.forceReleaseLock(prefixed(threadId)),
1950
- enqueue: (threadId, entry, maxSize) => base.enqueue(prefixed(threadId), entry, maxSize),
1951
- dequeue: (threadId) => base.dequeue(prefixed(threadId)),
1952
- queueDepth: (threadId) => base.queueDepth(prefixed(threadId)),
1953
- get: (key) => base.get(prefixed(key)),
1954
- getList: (key) => base.getList(prefixed(key)),
1955
- set: (key, value, ttlMs) => base.set(prefixed(key), value, ttlMs),
1956
- setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(prefixed(key), value, ttlMs),
1957
- delete: (key) => base.delete(prefixed(key))
1958
- };
1959
- }
1960
- function createQueuedStateAdapter(base, options) {
1961
- const heartbeats = /* @__PURE__ */ new Map();
1962
- const shouldHeartbeatLock = (ttlMs) => ttlMs === ACTIVE_LOCK_TTL_MS;
1963
- const heartbeatKey = (lock) => `${lock.threadId}:${lock.token}`;
1964
- const stopHeartbeatByKey = (key) => {
1965
- const heartbeat = heartbeats.get(key);
1966
- if (!heartbeat) return;
1967
- clearInterval(heartbeat.timer);
1968
- heartbeats.delete(key);
1969
- };
1970
- const stopHeartbeat = (lock) => {
1971
- stopHeartbeatByKey(heartbeatKey(lock));
1972
- };
1973
- const stopHeartbeatsForThread = (threadId) => {
1974
- for (const [key, heartbeat] of heartbeats) if (heartbeat.lock.threadId === threadId) stopHeartbeatByKey(key);
1975
- };
1976
- const stopAllHeartbeats = () => {
1977
- for (const key of heartbeats.keys()) stopHeartbeatByKey(key);
1978
- };
1979
- const runHeartbeat = async (key) => {
1980
- const heartbeat = heartbeats.get(key);
1981
- if (!heartbeat || heartbeat.inFlight) return;
1982
- heartbeat.inFlight = true;
1983
- try {
1984
- if (Date.now() - heartbeat.startedAtMs >= options.activeLockMaxAgeMs) {
1985
- stopHeartbeatByKey(key);
1986
- return;
1987
- }
1988
- if (!await base.extendLock(heartbeat.lock, heartbeat.ttlMs)) {
1989
- stopHeartbeatByKey(key);
1990
- return;
1991
- }
1992
- heartbeat.lock.expiresAt = Date.now() + heartbeat.ttlMs;
1993
- } catch {} finally {
1994
- const current = heartbeats.get(key);
1995
- if (current === heartbeat) current.inFlight = false;
1996
- }
1997
- };
1998
- const startOrUpdateHeartbeat = (lock, ttlMs) => {
1999
- const key = heartbeatKey(lock);
2000
- const existing = heartbeats.get(key);
2001
- if (existing) {
2002
- existing.ttlMs = ttlMs;
2003
- return;
2004
- }
2005
- const timer = setInterval(() => {
2006
- runHeartbeat(key);
2007
- }, ACTIVE_LOCK_HEARTBEAT_MS);
2008
- timer.unref?.();
2009
- heartbeats.set(key, {
2010
- inFlight: false,
2011
- lock,
2012
- startedAtMs: Date.now(),
2013
- timer,
2014
- ttlMs
2015
- });
2016
- };
2017
- const acquireLock = async (threadId, ttlMs) => {
2018
- const lock = await base.acquireLock(threadId, ttlMs);
2019
- if (lock && shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
2020
- return lock;
2021
- };
2022
- return {
2023
- appendToList: (key, value, options) => base.appendToList(key, value, options),
2024
- connect: () => base.connect(),
2025
- disconnect: async () => {
2026
- stopAllHeartbeats();
2027
- await base.disconnect();
2028
- },
2029
- subscribe: (threadId) => base.subscribe(threadId),
2030
- unsubscribe: (threadId) => base.unsubscribe(threadId),
2031
- isSubscribed: (threadId) => base.isSubscribed(threadId),
2032
- acquireLock,
2033
- releaseLock: async (lock) => {
2034
- stopHeartbeat(lock);
2035
- await base.releaseLock(lock);
2036
- },
2037
- extendLock: async (lock, ttlMs) => {
2038
- const extended = await base.extendLock(lock, ttlMs);
2039
- if (extended) {
2040
- lock.expiresAt = Date.now() + ttlMs;
2041
- if (shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
2042
- else stopHeartbeat(lock);
2043
- } else stopHeartbeat(lock);
2044
- return extended;
2045
- },
2046
- forceReleaseLock: async (threadId) => {
2047
- stopHeartbeatsForThread(threadId);
2048
- await base.forceReleaseLock(threadId);
2049
- },
2050
- enqueue: (threadId, entry, maxSize) => base.enqueue(threadId, entry, maxSize),
2051
- dequeue: (threadId) => base.dequeue(threadId),
2052
- queueDepth: (threadId) => base.queueDepth(threadId),
2053
- get: (key) => base.get(key),
2054
- getList: (key) => base.getList(key),
2055
- set: (key, value, ttlMs) => base.set(key, value, ttlMs),
2056
- setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(key, value, ttlMs),
2057
- delete: (key) => base.delete(key)
2058
- };
2059
- }
2060
- function withOptionalPrefix(base, prefix) {
2061
- return prefix ? createPrefixedStateAdapter(base, prefix) : base;
2062
- }
2063
- function createStateAdapter() {
2064
- const config = getChatConfig();
2065
- const activeLockMaxAgeMs = config.bot.turnTimeoutMs + ACTIVE_LOCK_TTL_MS;
2066
- if (config.state.adapter === "memory") {
2067
- redisStateAdapter = void 0;
2068
- return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(createMemoryState(), config.state.keyPrefix)), { activeLockMaxAgeMs });
2069
- }
2070
- if (!config.state.redisUrl) throw new Error("REDIS_URL is required for durable Slack thread state");
2071
- const redisState = createRedisState({
2072
- keyPrefix: REDIS_STATE_KEY_PREFIX,
2073
- url: config.state.redisUrl
2074
- });
2075
- redisStateAdapter = redisState;
2076
- return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(redisState, config.state.keyPrefix)), { activeLockMaxAgeMs });
2077
- }
2078
- function getOptionalRedisStateAdapter() {
2079
- getStateAdapter();
2080
- return redisStateAdapter;
2081
- }
2082
- async function getConnectedStateContext() {
2083
- const adapter = getStateAdapter();
2084
- await adapter.connect();
2085
- return {
2086
- redisStateAdapter: getOptionalRedisStateAdapter(),
2087
- stateAdapter: adapter
2088
- };
2089
- }
2090
- /** Return the Redis adapter only when the caller is using the default state adapter. */
2091
- async function getDefaultRedisStateAdapterFor(adapter) {
2092
- if (adapter !== stateAdapter) return;
2093
- const context = await getConnectedStateContext();
2094
- return context.stateAdapter === adapter ? context.redisStateAdapter : void 0;
2095
- }
2096
- /** The Redis key that the default Redis adapter uses for one state value key. */
2097
- function redisStateKey(key) {
2098
- const prefix = getChatConfig().state.keyPrefix;
2099
- return `${REDIS_STATE_KEY_PREFIX}:cache:${prefix ? `${prefix}:` : ""}${key}`;
2100
- }
2101
- /** Read state values in one Redis round trip. Other adapters read each key. */
2102
- async function getStateValues(state, keys) {
2103
- if (keys.length === 0) return [];
2104
- const redis = await getDefaultRedisStateAdapterFor(state);
2105
- if (!redis) return await mapBounded(keys, (key) => state.get(key));
2106
- return (await redis.getClient().mGet(keys.map(redisStateKey))).map((value) => {
2107
- if (value === null) return null;
2108
- try {
2109
- return JSON.parse(value);
2110
- } catch {
2111
- return value;
2112
- }
2113
- });
2114
- }
2115
- /** Write state values with one TTL in one Redis round trip. */
2116
- async function setStateValues(state, entries, ttlMs) {
2117
- if (entries.length === 0) return;
2118
- const redis = await getDefaultRedisStateAdapterFor(state);
2119
- if (!redis) {
2120
- await mapBounded(entries, ({ key, value }) => state.set(key, value, ttlMs));
2121
- return;
2122
- }
2123
- const pipeline = redis.getClient().multi();
2124
- for (const { key, value } of entries) pipeline.set(redisStateKey(key), JSON.stringify(value), { PX: ttlMs });
2125
- await pipeline.execAsPipeline();
2126
- }
2127
- function getStateAdapter() {
2128
- if (!stateAdapter) stateAdapter = createStateAdapter();
2129
- return stateAdapter;
2130
- }
2131
- async function disconnectStateAdapter() {
2132
- if (!stateAdapter) return;
2133
- try {
2134
- await stateAdapter.disconnect();
2135
- } finally {
2136
- stateAdapter = void 0;
2137
- redisStateAdapter = void 0;
2138
- }
2139
- }
2140
1772
  // src/chat/conversations/structured-events.ts
2141
1773
  /** Reserved namespace for Junior-owned conversation metadata events. */
2142
1774
  const JUNIOR_NATIVE_EVENT_NAMESPACE = "junior";
@@ -2270,107 +1902,1469 @@ function renderJuniorNativeConversationEvent(args) {
2270
1902
  const presentation = definition.renderEvent(definition.parse(args.content));
2271
1903
  return presentation === void 0 ? void 0 : conversationEventPresentationSchema.parse(presentation);
2272
1904
  }
2273
- // src/chat/pi/transcription.ts
2274
- const GEN_AI_OPERATION_TRANSCRIPTION = "transcription";
2275
- const NO_AUDIO_PATTERN = /\(invalid_audio\)\s*$/;
2276
- const SENTENCE_END_PATTERN = /[.?!]["')\]]*$/;
2277
- /** The file has no audio that the model can transcribe. */
2278
- var NoAudioError = class extends Error {
2279
- name = "NoAudioError";
1905
+ // src/chat/pi/gateway-auth.ts
1906
+ /**
1907
+ * AI Gateway credential resolution for every Junior model path.
1908
+ *
1909
+ * Prefer Vercel project OIDC so gateway usage attributes to the deploying
1910
+ * project. Fall back to AI_GATEWAY_API_KEY for local/CI and non-Vercel hosts.
1911
+ * Never cache resolved tokens: runtime OIDC rotates on each invocation.
1912
+ */
1913
+ const UNAUTHENTICATED_GATEWAY_TOKEN = "unauthenticated";
1914
+ /**
1915
+ * Resolve the AI Gateway bearer credential.
1916
+ *
1917
+ * Order:
1918
+ * 1. Vercel OIDC via `@vercel/oidc` (request header `x-vercel-oidc-token`,
1919
+ * then `VERCEL_OIDC_TOKEN`, with local refresh when needed)
1920
+ * 2. Explicit `AI_GATEWAY_API_KEY` / pi-ai env mapping for vercel-ai-gateway
1921
+ * 3. A placeholder token (`mode: "none"`), so auth fails on the server side
1922
+ */
1923
+ async function resolveGatewayCredential() {
1924
+ try {
1925
+ const oidcToken = toOptionalTrimmed(await getVercelOidcToken());
1926
+ if (oidcToken) return {
1927
+ mode: "oidc",
1928
+ token: oidcToken
1929
+ };
1930
+ } catch {}
1931
+ const apiKey = toOptionalTrimmed(getEnvApiKey("vercel-ai-gateway"));
1932
+ if (apiKey) return {
1933
+ mode: "api_key",
1934
+ token: apiKey
1935
+ };
1936
+ return {
1937
+ mode: "none",
1938
+ token: UNAUTHENTICATED_GATEWAY_TOKEN
1939
+ };
1940
+ }
1941
+ /** Resolve the bearer token string for Authorization headers and Pi getApiKey. */
1942
+ async function getGatewayApiKey() {
1943
+ return (await resolveGatewayCredential()).token;
1944
+ }
1945
+ // src/chat/pi/object-completion.ts
1946
+ /**
1947
+ * Output tokens added on top of the object size that a caller asks for.
1948
+ * Reasoning models spend output tokens before they write the object, and the
1949
+ * provider counts both against one `maxOutputTokens` limit. With Guardian's
1950
+ * 2,000-token assessment, this keeps the 8,000 limit its evals pass at.
1951
+ */
1952
+ const STRUCTURED_OUTPUT_REASONING_TOKENS = 6e3;
1953
+ /**
1954
+ * Output token limit for an object of `objectTokens`, with room for reasoning.
1955
+ * It never exceeds the model's own output limit, which providers enforce.
1956
+ */
1957
+ function structuredOutputTokenLimit(objectTokens, modelMaxTokens) {
1958
+ if (objectTokens === void 0) return void 0;
1959
+ const limit = objectTokens + STRUCTURED_OUTPUT_REASONING_TOKENS;
1960
+ return modelMaxTokens !== void 0 ? Math.min(limit, modelMaxTokens) : limit;
1961
+ }
1962
+ /** Span attributes for the finish reason and usage of one object completion. */
1963
+ function objectCompletionAttributes(finishReason, usage) {
1964
+ const reasoningTokens = usage?.outputTokenDetails?.reasoningTokens;
1965
+ return {
1966
+ ...finishReason ? { "gen_ai.response.finish_reasons": [finishReason] } : void 0,
1967
+ ...extractGenAiUsageAttributes(usage),
1968
+ ...reasoningTokens !== void 0 ? { "gen_ai.usage.reasoning.output_tokens": reasoningTokens } : void 0
1969
+ };
1970
+ }
1971
+ /**
1972
+ * Keep only the fixed message and stack of a failed structured output. The SDK
1973
+ * error's `text` and its parse or validation cause hold the raw model output.
1974
+ * A `length` finish gets its own error, so a spent budget is not reported as a
1975
+ * malformed object.
1976
+ */
1977
+ function structuredOutputErrorCause(error) {
1978
+ const spentBudget = error.finishReason === "length";
1979
+ const cause = new Error(spentBudget ? "Structured output hit the output token limit" : error.message);
1980
+ cause.name = spentBudget ? "StructuredOutputLengthError" : error.name;
1981
+ cause.stack = error.stack;
1982
+ return cause;
1983
+ }
1984
+ // src/chat/services/provider-error.ts
1985
+ /** Structured failure produced at an AI provider boundary. */
1986
+ var ProviderError = class extends Error {
1987
+ code = "provider_error";
1988
+ kind;
1989
+ modelId;
1990
+ retryable;
1991
+ retryAfterMs;
1992
+ status;
1993
+ constructor(details) {
1994
+ super(`AI provider error: ${details.kind}`, details.cause !== void 0 ? { cause: details.cause } : {});
1995
+ this.name = "ProviderError";
1996
+ this.kind = details.kind;
1997
+ this.modelId = details.modelId;
1998
+ this.retryable = details.retryable;
1999
+ this.retryAfterMs = details.retryAfterMs;
2000
+ this.status = details.status;
2001
+ }
2002
+ };
2003
+ const NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
2004
+ "ECONNREFUSED",
2005
+ "ECONNRESET",
2006
+ "ENOTFOUND",
2007
+ "EAI_AGAIN"
2008
+ ]);
2009
+ const TIMEOUT_ERROR_CODES$1 = /* @__PURE__ */ new Set([
2010
+ "ETIMEDOUT",
2011
+ "ECONNABORTED",
2012
+ "ESOCKETTIMEDOUT"
2013
+ ]);
2014
+ const CONTENT_POLICY_PATTERN = /\b(?:content|safety|usage)[ _-]?policy\b|\b(?:content|safety) (?:filter|violation)\b|\bmoderation (?:blocked|rejected|refused)\b/i;
2015
+ const QUOTA_PATTERN = /insufficient.?quota|quota exceeded|usage limit|available balance|out of budget|billing (?:limit|quota|error)|payment required/i;
2016
+ const AUTH_PATTERN = /unauthenticated|invalid.?api.?key|no api key|authentication (?:failed|error|required)|(?:invalid|missing|expired|revoked).{0,24}\bcredentials?\b|\bcredentials?\b.{0,24}(?:invalid|missing|expired|revoked)|\bno\b.{0,16}\bcredentials?\b/i;
2017
+ const PERMISSION_PATTERN = /permission denied|forbidden|not authorized|authorization (?:failed|required|denied)/i;
2018
+ const INVALID_REQUEST_PATTERN = /context.?length|context.?window|validation (?:error|failed)|bad request|unsupported model|invalid model|unknown (?:ai gateway )?model|mismatched api/i;
2019
+ const CAPACITY_PATTERN = /overloaded|at capacity|capacity exceeded/i;
2020
+ const TIMEOUT_PATTERN = /timed? out|timeout|gateway timeout/i;
2021
+ const NETWORK_PATTERN = /network.?error|connection (?:error|refused|lost|closed)|fetch failed|cannot connect to api|socket (?:hang up|closed)|stream ended before/i;
2022
+ const SERVER_PATTERN = /service(?: temporarily)?[ _-]?unavailable|server.?error|internal.?error|bad gateway|upstream (?:request )?failed/i;
2023
+ const TERMINAL_KINDS = /* @__PURE__ */ new Set([
2024
+ "auth",
2025
+ "permission",
2026
+ "invalid_request",
2027
+ "invalid_response",
2028
+ "quota",
2029
+ "content_policy"
2030
+ ]);
2031
+ const RETRYABLE_KINDS = /* @__PURE__ */ new Set([
2032
+ "rate_limit",
2033
+ "capacity",
2034
+ "timeout",
2035
+ "network",
2036
+ "server"
2037
+ ]);
2038
+ function providerMessage(error) {
2039
+ return (error instanceof Error ? error.message : String(error)).trim();
2040
+ }
2041
+ const PROVIDER_ERROR_SUMMARY_MAX_CHARS = 240;
2042
+ /** Short provider-boundary text for telemetry. Drop trailing JSON bodies. */
2043
+ function summarizeProviderErrorMessage(message) {
2044
+ const normalized = message.trim().replace(/\s+/g, " ");
2045
+ if (!normalized) return void 0;
2046
+ const jsonStart = normalized.indexOf("{");
2047
+ const summary = (jsonStart >= 0 ? normalized.slice(0, jsonStart) : normalized).trim();
2048
+ if (!summary) return void 0;
2049
+ return summary.length > PROVIDER_ERROR_SUMMARY_MAX_CHARS ? `${summary.slice(0, PROVIDER_ERROR_SUMMARY_MAX_CHARS)}...` : summary;
2050
+ }
2051
+ function extractTransportKind(error, depth = 0) {
2052
+ if (!(error instanceof Error) || depth > 4) return void 0;
2053
+ const providerError = error;
2054
+ const code = typeof providerError.code === "string" ? providerError.code.toUpperCase() : void 0;
2055
+ if (code && TIMEOUT_ERROR_CODES$1.has(code)) return "timeout";
2056
+ if (code && NETWORK_ERROR_CODES.has(code)) return "network";
2057
+ if (depth > 0 && NETWORK_PATTERN.test(providerError.message)) return "network";
2058
+ return extractTransportKind(providerError.cause, depth + 1);
2059
+ }
2060
+ function extractStatus(error, message) {
2061
+ if (error instanceof Error) {
2062
+ const providerError = error;
2063
+ if (typeof providerError.status === "number") return providerError.status;
2064
+ if (typeof providerError.statusCode === "number") return providerError.statusCode;
2065
+ }
2066
+ const match = message.match(/^(?:Error:\s*)?([45]\d\d)\b|\bstatus(?:Code)?["'=:\s]+([45]\d\d)\b/i);
2067
+ const status = match?.[1] ?? match?.[2];
2068
+ return status ? Number(status) : void 0;
2069
+ }
2070
+ function extractRetryAfterMs(error, message) {
2071
+ const headers = error instanceof Error ? error.responseHeaders ?? error.response?.headers : void 0;
2072
+ const retryAfter = headers instanceof Headers ? headers.get("retry-after") : headers && typeof headers === "object" ? Object.entries(headers).find(([name]) => name.toLowerCase() === "retry-after")?.[1] : void 0;
2073
+ const raw = typeof retryAfter === "string" || typeof retryAfter === "number" ? String(retryAfter) : message.match(/"retry-after"\s*:\s*"?([^",}]+)"?/i)?.[1];
2074
+ if (!raw) return void 0;
2075
+ const seconds = Number(raw);
2076
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
2077
+ const date = Date.parse(raw);
2078
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
2079
+ }
2080
+ /** Classify stable provider signals without copying Pi's retry vocabulary. */
2081
+ function classifyProviderError(status, message, transportKind) {
2082
+ if (CONTENT_POLICY_PATTERN.test(message)) return "content_policy";
2083
+ if (QUOTA_PATTERN.test(message)) return "quota";
2084
+ if (status === 401 || AUTH_PATTERN.test(message)) return "auth";
2085
+ if (status === 403 || PERMISSION_PATTERN.test(message)) return "permission";
2086
+ if (INVALID_REQUEST_PATTERN.test(message)) return "invalid_request";
2087
+ if (status === 429 || /rate.?limit|too many requests/i.test(message)) return "rate_limit";
2088
+ if (status === 408) return "timeout";
2089
+ if (CAPACITY_PATTERN.test(message)) return "capacity";
2090
+ if (transportKind === "timeout" || TIMEOUT_PATTERN.test(message)) return "timeout";
2091
+ if (transportKind === "network" || NETWORK_PATTERN.test(message)) return "network";
2092
+ if (status !== void 0 && status >= 500 || SERVER_PATTERN.test(message)) return "server";
2093
+ if (status !== void 0 && status >= 400) return "invalid_request";
2094
+ return "unknown";
2095
+ }
2096
+ /**
2097
+ * The AI SDK retries a call and then throws `AI_RetryError`. The error of
2098
+ * its last attempt has the status and the transport cause.
2099
+ */
2100
+ function lastAttemptError(error) {
2101
+ return error instanceof Error && error.name === "AI_RetryError" && "lastError" in error ? error.lastError : error;
2102
+ }
2103
+ /** Normalize SDK, Gateway, and Pi failures into one provider error contract. */
2104
+ function createProviderError(error, options = {}) {
2105
+ if (error instanceof ProviderError) return error;
2106
+ const message = providerMessage(error);
2107
+ const attempt = lastAttemptError(error);
2108
+ const status = extractStatus(attempt, message);
2109
+ const kind = options.kind ?? classifyProviderError(status, message, extractTransportKind(attempt));
2110
+ const retryable = !TERMINAL_KINDS.has(kind) && (options.retryable ?? RETRYABLE_KINDS.has(kind));
2111
+ return new ProviderError({
2112
+ cause: error,
2113
+ kind,
2114
+ modelId: options.modelId,
2115
+ retryable,
2116
+ retryAfterMs: extractRetryAfterMs(attempt, message),
2117
+ status
2118
+ });
2119
+ }
2120
+ const REFUSAL_STOP_REASONS = /* @__PURE__ */ new Set(["refusal", "sensitive"]);
2121
+ /** Return whether the provider refused to answer a Pi assistant message. */
2122
+ function isProviderRefusal(message) {
2123
+ return message.rawStopReason !== void 0 && REFUSAL_STOP_REASONS.has(message.rawStopReason);
2124
+ }
2125
+ /** Normalize a failed Pi assistant message. A provider refusal is a content policy block. */
2126
+ function createAssistantProviderError(message, options = {}) {
2127
+ return createProviderError(message.errorMessage ?? "", {
2128
+ ...options,
2129
+ ...isProviderRefusal(message) ? { kind: "content_policy" } : void 0
2130
+ });
2131
+ }
2132
+ /** Return whether a provider-boundary error should be retried. */
2133
+ function isProviderRetryError(error) {
2134
+ return error instanceof ProviderError && error.retryable;
2135
+ }
2136
+ /** Find the provider failure preserved inside a domain error cause chain. */
2137
+ function findProviderError(error) {
2138
+ const visited = /* @__PURE__ */ new Set();
2139
+ let current = error;
2140
+ while (current instanceof Error && !visited.has(current)) {
2141
+ if (current instanceof ProviderError) return current;
2142
+ visited.add(current);
2143
+ current = current.cause;
2144
+ }
2145
+ }
2146
+ const PROVIDER_NAMES = {
2147
+ anthropic: "Anthropic",
2148
+ google: "Google",
2149
+ openai: "OpenAI",
2150
+ xai: "xAI"
2280
2151
  };
2281
- const diarizedWordsSchema = z.object({ elevenlabs: z.object({ words: z.array(z.object({
2282
- speaker_id: z.string().nullish(),
2283
- start: z.number(),
2284
- text: z.string(),
2285
- type: z.string()
2286
- })) }) });
2287
2152
  /**
2288
- * Group diarized words into entries. A speech entry ends when the speaker
2289
- * changes or a sentence ends. Each audio event is its own sound entry.
2290
- * Spaces join words and never start an entry.
2153
+ * Name the failing model for user copy, such as `OpenAI (gpt-6-luna)`. A
2154
+ * model that serves another step, such as action review, says so, because
2155
+ * the person did not pick it.
2156
+ */
2157
+ function providerSubject(modelId, purpose) {
2158
+ const slash = modelId?.indexOf("/") ?? -1;
2159
+ if (!modelId || slash <= 0) return purpose ? `The model provider used for ${purpose}` : "The model provider";
2160
+ const vendor = modelId.slice(0, slash);
2161
+ const model = modelId.slice(slash + 1);
2162
+ const details = purpose ? `${model}, used for ${purpose}` : model;
2163
+ return `${PROVIDER_NAMES[vendor] ?? vendor} (${details})`;
2164
+ }
2165
+ const UPSTREAM = "This is an upstream provider problem, not something you did. Please try again shortly.";
2166
+ const PROVIDER_ERROR_MESSAGES = {
2167
+ capacity: (subject) => `${subject} is at capacity right now. ${UPSTREAM}`,
2168
+ rate_limit: (subject) => `${subject} is rate-limiting requests right now. Please try again shortly.`,
2169
+ timeout: (subject) => `${subject} is timing out right now. ${UPSTREAM}`,
2170
+ network: (subject) => `${subject} cannot be reached right now. ${UPSTREAM}`,
2171
+ server: (subject) => `${subject} is returning errors right now. ${UPSTREAM}`,
2172
+ auth: (subject) => `${subject} rejected the configured credentials. This needs an administrator or configuration fix.`,
2173
+ permission: (subject) => `${subject} denied access to this model or request. Ask an administrator to check model access, organization policy, and region availability.`,
2174
+ quota: (subject) => `${subject} reports that the usage quota is exhausted. This needs an administrator or billing configuration fix.`,
2175
+ content_policy: (subject) => `${subject} blocked this request under its content policy. Please revise the request and try again.`,
2176
+ invalid_request: (subject) => `${subject} rejected this request as invalid. Please revise the request or ask an administrator to check the model configuration.`,
2177
+ invalid_response: (subject) => `${subject} returned an invalid response. ${UPSTREAM}`,
2178
+ unknown: (subject) => `${subject} returned an error. ${UPSTREAM}`
2179
+ };
2180
+ /**
2181
+ * Return stable, sanitized copy suitable for a terminal user response. It
2182
+ * names the provider and model, and `purpose` names the step that the model
2183
+ * serves when it is not the agent model.
2291
2184
  */
2292
- function transcriptEntries(words) {
2293
- const entries = [];
2294
- let current;
2295
- for (const word of words) {
2296
- if (word.type === "spacing") {
2297
- if (current) current.text += word.text;
2185
+ function getProviderErrorUserMessage(error, options = {}) {
2186
+ const subject = providerSubject(error.modelId, options.purpose);
2187
+ if (error.kind === "rate_limit" && error.retryAfterMs) return `${subject} is rate-limiting requests right now. Please try again in about ${Math.max(1, Math.ceil(error.retryAfterMs / 1e3))} seconds.`;
2188
+ return PROVIDER_ERROR_MESSAGES[error.kind](subject);
2189
+ }
2190
+ /** Return safe structured fields for terminal failure telemetry. */
2191
+ function getProviderErrorAttributes(error) {
2192
+ const cause = error.cause;
2193
+ const causeMessage = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : void 0;
2194
+ const summary = causeMessage ? summarizeProviderErrorMessage(causeMessage) : void 0;
2195
+ return {
2196
+ "app.ai.provider_error.kind": error.kind,
2197
+ "app.ai.provider_error.retryable": error.retryable,
2198
+ ...error.status !== void 0 ? { "app.ai.provider_error.status": error.status } : void 0,
2199
+ ...error.retryAfterMs !== void 0 ? { "app.ai.provider_error.retry_after_ms": error.retryAfterMs } : void 0,
2200
+ ...summary ? { "app.ai.provider_error.summary": summary } : void 0,
2201
+ ...error.modelId ? { "gen_ai.request.model": error.modelId } : void 0
2202
+ };
2203
+ }
2204
+ // src/chat/services/context-compaction-marker.ts
2205
+ const COMPACTION_SUMMARY_PREFIX = "Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:";
2206
+ /** Return whether text is one of Junior's durable compacted-context markers. */
2207
+ function isCompactionSummaryText(text) {
2208
+ const normalized = (unwrapCurrentInstruction(text) ?? text).trimStart();
2209
+ return normalized.startsWith("Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:") || normalized.startsWith("Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:");
2210
+ }
2211
+ /** Return whether model-visible history contains a durable compacted context marker. */
2212
+ function hasCompactedConversationContext(messages) {
2213
+ return messages.some((message) => {
2214
+ const content = message.content;
2215
+ if (typeof content === "string") return isCompactionSummaryText(content);
2216
+ if (!Array.isArray(content)) return false;
2217
+ return content.some((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string" && isCompactionSummaryText(part.text));
2218
+ });
2219
+ }
2220
+ // src/chat/pi/gateway-routing-attributes.ts
2221
+ const providerAttemptSchema = z.object({
2222
+ success: z.boolean().optional(),
2223
+ credentialType: z.string().optional(),
2224
+ inferenceEndpoint: z.object({ geoRegion: z.string().optional() }).optional()
2225
+ });
2226
+ const routingSchema = z.object({
2227
+ finalProvider: z.string().optional(),
2228
+ totalProviderAttemptCount: z.number().optional(),
2229
+ clientSessionIdSource: z.string().optional(),
2230
+ affinity: z.object({
2231
+ pinned: z.boolean().optional(),
2232
+ pinnedProvider: z.string().optional(),
2233
+ outcome: z.string().optional()
2234
+ }).optional(),
2235
+ modelAttempts: z.array(z.object({ providerAttempts: z.array(providerAttemptSchema).optional() })).optional()
2236
+ });
2237
+ const messageDeltaSchema = z.object({
2238
+ type: z.literal("message_delta"),
2239
+ provider_metadata: z.object({ gateway: z.object({ routing: routingSchema }) })
2240
+ });
2241
+ /**
2242
+ * Read the AI Gateway routing of one Anthropic Messages stream event as
2243
+ * `app.ai.gateway.*` span attributes. Returns undefined for any other event.
2244
+ */
2245
+ function gatewayRoutingAttributes(event) {
2246
+ const parsed = messageDeltaSchema.safeParse(event);
2247
+ if (!parsed.success) return;
2248
+ const routing = parsed.data.provider_metadata.gateway.routing;
2249
+ const served = routing.modelAttempts?.flatMap((attempt) => attempt.providerAttempts ?? []).find((attempt) => attempt.success === true);
2250
+ const attributes = {};
2251
+ const set = (key, value) => {
2252
+ if (value !== void 0) attributes[`app.ai.gateway.${key}`] = value;
2253
+ };
2254
+ set("provider", routing.finalProvider);
2255
+ set("credential_type", served?.credentialType);
2256
+ set("region", served?.inferenceEndpoint?.geoRegion);
2257
+ set("provider_attempts", routing.totalProviderAttemptCount);
2258
+ set("session_id_source", routing.clientSessionIdSource);
2259
+ set("affinity.pinned", routing.affinity?.pinned);
2260
+ set("affinity.pinned_provider", routing.affinity?.pinnedProvider);
2261
+ set("affinity.outcome", routing.affinity?.outcome);
2262
+ return attributes;
2263
+ }
2264
+ // src/chat/services/image-dimensions.ts
2265
+ const HEADER_BASE64_CHARS = 65536;
2266
+ const READERS = {
2267
+ "image/png": readPng,
2268
+ "image/jpeg": readJpeg,
2269
+ "image/gif": readGif,
2270
+ "image/webp": readWebp
2271
+ };
2272
+ /**
2273
+ * Read the pixel size from an image header without decoding the image.
2274
+ * Returns undefined when the type is unknown or the header is not valid.
2275
+ */
2276
+ function readImageDimensions(image) {
2277
+ const read = READERS[image.mimeType.toLowerCase()];
2278
+ if (!read) return void 0;
2279
+ const prefix = Buffer.from(image.data.slice(0, HEADER_BASE64_CHARS), "base64");
2280
+ const canReadMore = read === readJpeg && image.data.length > HEADER_BASE64_CHARS;
2281
+ const dimensions = read(prefix) ?? (canReadMore ? read(Buffer.from(image.data, "base64")) : void 0);
2282
+ return dimensions && dimensions.width > 0 && dimensions.height > 0 ? dimensions : void 0;
2283
+ }
2284
+ function hasAscii(bytes, offset, text) {
2285
+ return bytes.toString("latin1", offset, offset + text.length) === text;
2286
+ }
2287
+ function readPng(bytes) {
2288
+ if (bytes.length < 24) return void 0;
2289
+ if (bytes.readUInt32BE(0) !== 2303741511 || !hasAscii(bytes, 12, "IHDR")) return;
2290
+ return {
2291
+ width: bytes.readUInt32BE(16),
2292
+ height: bytes.readUInt32BE(20)
2293
+ };
2294
+ }
2295
+ function readGif(bytes) {
2296
+ if (bytes.length < 10) return void 0;
2297
+ if (!hasAscii(bytes, 0, "GIF87a") && !hasAscii(bytes, 0, "GIF89a")) return;
2298
+ return {
2299
+ width: bytes.readUInt16LE(6),
2300
+ height: bytes.readUInt16LE(8)
2301
+ };
2302
+ }
2303
+ function readJpeg(bytes) {
2304
+ if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216) return;
2305
+ let offset = 2;
2306
+ while (offset + 4 <= bytes.length) {
2307
+ if (bytes[offset] !== 255) return void 0;
2308
+ const marker = bytes[offset + 1];
2309
+ if (marker === 255) {
2310
+ offset += 1;
2298
2311
  continue;
2299
2312
  }
2300
- if (word.type === "audio_event") {
2301
- entries.push({
2302
- kind: "sound",
2303
- startSeconds: word.start,
2304
- text: word.text.replace(/^[[(]+|[\])]+$/g, "")
2305
- });
2306
- current = void 0;
2313
+ if (marker === 1 || marker >= 208 && marker <= 215) {
2314
+ offset += 2;
2307
2315
  continue;
2308
2316
  }
2309
- const speaker = word.speaker_id ?? void 0;
2310
- if (!current || current.speaker !== speaker) {
2311
- current = {
2312
- kind: "speech",
2313
- startSeconds: word.start,
2314
- text: "",
2315
- ...speaker ? { speaker } : void 0
2317
+ const length = bytes.readUInt16BE(offset + 2);
2318
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
2319
+ if (offset + 9 > bytes.length) return void 0;
2320
+ return {
2321
+ height: bytes.readUInt16BE(offset + 5),
2322
+ width: bytes.readUInt16BE(offset + 7)
2316
2323
  };
2317
- entries.push(current);
2318
2324
  }
2319
- current.text += word.text;
2320
- if (SENTENCE_END_PATTERN.test(word.text)) current = void 0;
2325
+ if (length < 2) return void 0;
2326
+ offset += 2 + length;
2327
+ }
2328
+ }
2329
+ function readWebp(bytes) {
2330
+ if (bytes.length < 30) return void 0;
2331
+ if (!hasAscii(bytes, 0, "RIFF") || !hasAscii(bytes, 8, "WEBP")) return;
2332
+ if (hasAscii(bytes, 12, "VP8 ")) {
2333
+ if (bytes.readUIntBE(23, 3) !== 10289450) return void 0;
2334
+ return {
2335
+ width: bytes.readUInt16LE(26) & 16383,
2336
+ height: bytes.readUInt16LE(28) & 16383
2337
+ };
2338
+ }
2339
+ if (hasAscii(bytes, 12, "VP8L")) {
2340
+ if (bytes[20] !== 47) return void 0;
2341
+ const bits = bytes.readUInt32LE(21);
2342
+ return {
2343
+ width: (bits & 16383) + 1,
2344
+ height: (bits >>> 14 & 16383) + 1
2345
+ };
2346
+ }
2347
+ if (hasAscii(bytes, 12, "VP8X")) return {
2348
+ width: bytes.readUIntLE(24, 3) + 1,
2349
+ height: bytes.readUIntLE(27, 3) + 1
2350
+ };
2351
+ }
2352
+ // src/chat/services/token-estimate.ts
2353
+ const CLAUDE_TOKEN_ESTIMATE = {
2354
+ charsPerToken: 2.5,
2355
+ toolResultOverheadTokens: 150
2356
+ };
2357
+ const DEFAULT_TOKEN_ESTIMATE = {
2358
+ charsPerToken: 4,
2359
+ toolResultOverheadTokens: 0
2360
+ };
2361
+ const IMAGE_CHARS = 4800;
2362
+ const CLAUDE_HIGH_RES_IMAGE = {
2363
+ maxEdge: 2576,
2364
+ maxTokens: 4784
2365
+ };
2366
+ const CLAUDE_STANDARD_IMAGE = {
2367
+ maxEdge: 1568,
2368
+ maxTokens: 1568
2369
+ };
2370
+ const CLAUDE_STANDARD_IMAGE_MODEL = /^anthropic\/claude-(?:3\b|[a-z]+-4(?:\.[0-6])?(?![.\d]))/;
2371
+ const CLAUDE_IMAGE_PATCH_PX = 28;
2372
+ function getTokenEstimateProfile(modelId) {
2373
+ return modelId.startsWith("anthropic/") ? CLAUDE_TOKEN_ESTIMATE : DEFAULT_TOKEN_ESTIMATE;
2374
+ }
2375
+ function tokensForChars(chars, profile) {
2376
+ return Math.ceil(chars / profile.charsPerToken);
2377
+ }
2378
+ function messageChars(message) {
2379
+ switch (message.role) {
2380
+ case "system": return renderSystemMessageUpdate(message).length;
2381
+ case "user":
2382
+ case "toolResult": return contentChars(message.content);
2383
+ case "assistant": {
2384
+ let chars = 0;
2385
+ for (const block of message.content) if (block.type === "text") chars += block.text.length;
2386
+ else if (block.type === "thinking") chars += block.thinking.length;
2387
+ else chars += block.name.length + JSON.stringify(block.arguments).length;
2388
+ return chars;
2389
+ }
2390
+ default: return 0;
2321
2391
  }
2322
- return entries.map((entry) => ({
2323
- ...entry,
2324
- text: entry.text.trim()
2325
- })).filter((entry) => entry.text.length > 0);
2392
+ }
2393
+ function contentChars(content) {
2394
+ if (typeof content === "string") return content.length;
2395
+ return content.reduce((chars, block) => chars + (block.type === "text" ? block.text.length : 0), 0);
2396
+ }
2397
+ function messageImages(message) {
2398
+ if (message.role !== "user" && message.role !== "toolResult") return [];
2399
+ if (typeof message.content === "string") return [];
2400
+ return message.content.filter((block) => block.type === "image");
2401
+ }
2402
+ function claudeImagePatches(width, height) {
2403
+ return Math.ceil(width / CLAUDE_IMAGE_PATCH_PX) * Math.ceil(height / CLAUDE_IMAGE_PATCH_PX);
2404
+ }
2405
+ function roundHalfToEven(value) {
2406
+ const floor = Math.floor(value);
2407
+ if (value - floor !== .5) return Math.round(value);
2408
+ return floor % 2 === 0 ? floor : floor + 1;
2326
2409
  }
2327
2410
  /**
2328
- * Keep the classification of a failed call, but not the SDK error. That
2329
- * error keeps the request body, and the body holds the signed URL.
2411
+ * The size Claude resizes an image to before it counts patches. This is the
2412
+ * reference implementation in "How Claude resizes and pads images" in
2413
+ * https://platform.claude.com/docs/en/build-with-claude/vision-coordinates:
2414
+ * the largest aspect-preserving size whose padded edges and patch count fit
2415
+ * the tier limits.
2330
2416
  */
2331
- function withoutSourceUrl(error, sourceUrl, modelId) {
2332
- const failure = error instanceof Error ? error : void 0;
2333
- const message = (failure?.message ?? String(error)).replaceAll(sourceUrl, "<signed URL>");
2334
- const classified = createProviderError(Object.assign(new Error(message, { cause: failure?.cause }), {
2335
- code: failure && "code" in failure ? failure.code : void 0,
2336
- statusCode: failure && "statusCode" in failure ? failure.statusCode : void 0
2337
- }), { modelId });
2338
- return new ProviderError({
2339
- cause: new Error(message),
2340
- kind: classified.kind,
2341
- modelId,
2342
- retryable: classified.retryable,
2343
- retryAfterMs: classified.retryAfterMs,
2344
- status: classified.status
2345
- });
2417
+ function claudeResizedImageSize(width, height, limits) {
2418
+ const fits = (w, h) => Math.ceil(w / CLAUDE_IMAGE_PATCH_PX) * CLAUDE_IMAGE_PATCH_PX <= limits.maxEdge && Math.ceil(h / CLAUDE_IMAGE_PATCH_PX) * CLAUDE_IMAGE_PATCH_PX <= limits.maxEdge && claudeImagePatches(w, h) <= limits.maxTokens;
2419
+ if (fits(width, height)) return [width, height];
2420
+ if (height > width) {
2421
+ const [resizedHeight, resizedWidth] = claudeResizedImageSize(height, width, limits);
2422
+ return [resizedWidth, resizedHeight];
2423
+ }
2424
+ const aspectRatio = width / height;
2425
+ const shortEdge = (longEdge) => Math.max(roundHalfToEven(longEdge / aspectRatio), 1);
2426
+ let low = 1;
2427
+ let high = width;
2428
+ while (low + 1 < high) {
2429
+ const mid = Math.floor((low + high) / 2);
2430
+ if (fits(mid, shortEdge(mid))) low = mid;
2431
+ else high = mid;
2432
+ }
2433
+ return [low, shortEdge(low)];
2346
2434
  }
2347
2435
  /**
2348
- * Transcribe speech in a file that the provider downloads from `sourceUrl`.
2349
- *
2350
- * The URL goes to the provider as `sourceUrl` with empty audio, so the file
2351
- * never passes through this process. The URL is a bearer credential: it is
2352
- * not put on spans, logs, or errors.
2436
+ * The largest size that any Claude model reads an image at. Claude scales a
2437
+ * larger image down to this size, so an image at this size loses no detail.
2353
2438
  */
2354
- async function transcribeFromUrl$1(params) {
2355
- const credential = await resolveGatewayCredential();
2356
- const provider = createGatewayProvider({ apiKey: credential.token });
2357
- try {
2358
- return await withSpan(`${GEN_AI_OPERATION_TRANSCRIPTION} ${params.modelId}`, "gen_ai.transcription", {
2359
- modelId: params.modelId,
2360
- ...params.conversationId ? { conversationId: params.conversationId } : void 0
2361
- }, async (setSpanAttributes) => {
2362
- const result = await transcribe({
2363
- model: provider.transcriptionModel(params.modelId),
2364
- audio: /* @__PURE__ */ new Uint8Array(),
2365
- providerOptions: { elevenlabs: {
2366
- diarize: true,
2367
- sourceUrl: params.sourceUrl,
2368
- tagAudioEvents: true
2369
- } },
2370
- ...params.signal ? { abortSignal: params.signal } : void 0
2371
- }).catch((error) => {
2372
- if (error instanceof Error && NO_AUDIO_PATTERN.test(error.message)) {
2373
- setSpanAttributes({ "error.type": "invalid_audio" });
2439
+ function claudeMaxImageSize(width, height) {
2440
+ return claudeResizedImageSize(width, height, CLAUDE_HIGH_RES_IMAGE);
2441
+ }
2442
+ /**
2443
+ * Estimate one image for a model with the rule that `estimateMessagesTokens`
2444
+ * uses. `sized` is false when the image used the flat per-image value.
2445
+ */
2446
+ function estimateImageTokens(image, modelId) {
2447
+ const dimensions = modelId.startsWith("anthropic/") ? readImageDimensions(image) : void 0;
2448
+ if (!dimensions) return {
2449
+ tokens: tokensForChars(IMAGE_CHARS, getTokenEstimateProfile(modelId)),
2450
+ sized: false
2451
+ };
2452
+ const limits = CLAUDE_STANDARD_IMAGE_MODEL.test(modelId) ? CLAUDE_STANDARD_IMAGE : CLAUDE_HIGH_RES_IMAGE;
2453
+ const [width, height] = claudeResizedImageSize(dimensions.width, dimensions.height, limits);
2454
+ return {
2455
+ tokens: claudeImagePatches(width, height),
2456
+ sized: true
2457
+ };
2458
+ }
2459
+ /** Estimate text tokens for local budgets that have no model. */
2460
+ function estimateTextTokens(text) {
2461
+ return tokensForChars(text.length, DEFAULT_TOKEN_ESTIMATE);
2462
+ }
2463
+ /** Convert a local text token budget to the characters it allows. */
2464
+ function textCharsForTokens(tokens) {
2465
+ return tokens * DEFAULT_TOKEN_ESTIMATE.charsPerToken;
2466
+ }
2467
+ /**
2468
+ * Estimate messages from their text size at the model's characters per token,
2469
+ * plus the tokens of each image.
2470
+ */
2471
+ function estimateMessagesTokens(messages, modelId) {
2472
+ const profile = getTokenEstimateProfile(modelId);
2473
+ return messages.reduce((total, message) => {
2474
+ const overhead = message.role === "toolResult" ? profile.toolResultOverheadTokens : 0;
2475
+ const images = messageImages(message).reduce((tokens, image) => tokens + estimateImageTokens(image, modelId).tokens, 0);
2476
+ return total + tokensForChars(messageChars(message), profile) + images + overhead;
2477
+ }, 0);
2478
+ }
2479
+ /** Estimate the tokens that the system prompt and tool definitions add to a model request. */
2480
+ function estimateRequestOverheadTokens(systemPrompt, tools, modelId) {
2481
+ const definitions = tools.map(({ name, description, parameters }) => ({
2482
+ name,
2483
+ description,
2484
+ parameters
2485
+ }));
2486
+ return tokensForChars(systemPrompt.length + JSON.stringify(definitions).length, getTokenEstimateProfile(modelId));
2487
+ }
2488
+ // src/chat/pi/request-prefix-attributes.ts
2489
+ const HASH_HEX_CHARS = 16;
2490
+ const MESSAGE_SEPARATOR = "\n";
2491
+ function withoutCacheControl(key, value) {
2492
+ return key === "cache_control" ? void 0 : value;
2493
+ }
2494
+ function canonicalMessageValue(key, value) {
2495
+ if (key === "content" && typeof value === "string") return [{
2496
+ type: "text",
2497
+ text: value
2498
+ }];
2499
+ return withoutCacheControl(key, value);
2500
+ }
2501
+ function digest$2(hash) {
2502
+ return hash.digest("hex").slice(0, HASH_HEX_CHARS);
2503
+ }
2504
+ function hashJson(value, replacer = withoutCacheControl) {
2505
+ return digest$2(createHash("sha256").update(JSON.stringify(value, replacer)));
2506
+ }
2507
+ function lastAssistantIndex(messages) {
2508
+ for (let index = messages.length - 1; index >= 0; index--) {
2509
+ const message = messages[index];
2510
+ if (typeof message === "object" && message !== null && message.role === "assistant") return index;
2511
+ }
2512
+ return -1;
2513
+ }
2514
+ function messagesHashes(messages) {
2515
+ const lastReply = lastAssistantIndex(messages);
2516
+ const hash = createHash("sha256");
2517
+ let beforeLastReply;
2518
+ for (const [index, message] of messages.entries()) {
2519
+ if (index === lastReply) beforeLastReply = digest$2(hash.copy());
2520
+ hash.update(JSON.stringify(message, canonicalMessageValue)).update(MESSAGE_SEPARATOR);
2521
+ }
2522
+ return {
2523
+ full: digest$2(hash),
2524
+ beforeLastReply
2525
+ };
2526
+ }
2527
+ function sortedKeys(_key, value) {
2528
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
2529
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
2530
+ }
2531
+ function prefixHash(parts) {
2532
+ return digest$2(createHash("sha256").update(parts.map((part) => part ?? "").join("\n")));
2533
+ }
2534
+ function readableString(value, key) {
2535
+ if (typeof value !== "object" || value === null) return;
2536
+ const field = value[key];
2537
+ return typeof field === "string" ? field : void 0;
2538
+ }
2539
+ function requestImages(messages) {
2540
+ const images = [];
2541
+ const visit = (content) => {
2542
+ if (!Array.isArray(content)) return;
2543
+ for (const block of content) {
2544
+ if (typeof block !== "object" || block === null) continue;
2545
+ const { type, source, content: nested } = block;
2546
+ if (type === "image") images.push({
2547
+ type: "image",
2548
+ data: readableString(source, "data") ?? "",
2549
+ mimeType: readableString(source, "media_type") ?? ""
2550
+ });
2551
+ else if (type === "tool_result") visit(nested);
2552
+ }
2553
+ };
2554
+ for (const message of messages) visit(message?.content);
2555
+ return images;
2556
+ }
2557
+ function imageAttributes(messages, model) {
2558
+ const images = Array.isArray(messages) ? requestImages(messages) : [];
2559
+ if (images.length === 0) return {};
2560
+ const modelId = typeof model === "string" ? model : "";
2561
+ let estimate = 0;
2562
+ let unsized = 0;
2563
+ for (const image of images) {
2564
+ const { tokens, sized } = estimateImageTokens(image, modelId);
2565
+ estimate += tokens;
2566
+ if (!sized) unsized += 1;
2567
+ }
2568
+ return {
2569
+ "app.ai.request.images.count": images.length,
2570
+ "app.ai.request.images.estimate": estimate,
2571
+ "app.ai.request.images.unsized": unsized
2572
+ };
2573
+ }
2574
+ function payloadAttributes(payload) {
2575
+ const { model, system, tools, messages, thinking, output_config } = payload;
2576
+ const systemHash = system !== void 0 ? hashJson(system) : void 0;
2577
+ const toolsHash = Array.isArray(tools) ? hashJson(tools) : void 0;
2578
+ const messagesHash = Array.isArray(messages) ? messagesHashes(messages) : void 0;
2579
+ const settingsHash = hashJson({
2580
+ thinking,
2581
+ output_config
2582
+ }, sortedKeys);
2583
+ const prefixParts = [
2584
+ typeof model === "string" ? model : void 0,
2585
+ settingsHash,
2586
+ toolsHash,
2587
+ systemHash
2588
+ ];
2589
+ const thinkingType = readableString(thinking, "type");
2590
+ const effort = readableString(output_config, "effort");
2591
+ return {
2592
+ ...systemHash ? { "app.ai.request.system_instructions.hash": systemHash } : void 0,
2593
+ "app.ai.request.tools.count": Array.isArray(tools) ? tools.length : 0,
2594
+ ...toolsHash ? { "app.ai.request.tools.hash": toolsHash } : void 0,
2595
+ ...Array.isArray(messages) ? { "app.ai.request.messages.count": messages.length } : void 0,
2596
+ ...messagesHash ? { "app.ai.request.messages.hash": messagesHash.full } : void 0,
2597
+ ...messagesHash?.beforeLastReply ? { "app.ai.request.messages.before_last_reply.hash": messagesHash.beforeLastReply } : void 0,
2598
+ "app.ai.request.prefix.hash": prefixHash([...prefixParts, messagesHash?.full]),
2599
+ ...messagesHash?.beforeLastReply ? { "app.ai.request.prefix.before_last_reply.hash": prefixHash([...prefixParts, messagesHash.beforeLastReply]) } : void 0,
2600
+ ...thinkingType ? { "app.ai.request.thinking.type": thinkingType } : void 0,
2601
+ ...effort ? { "app.ai.request.effort": effort } : void 0,
2602
+ ...imageAttributes(messages, model)
2603
+ };
2604
+ }
2605
+ /**
2606
+ * Hashes of the cache prefix parts of one provider request body, plus its
2607
+ * thinking and effort settings, to tell a changed cache prefix apart from an
2608
+ * expired cache. Also counts and estimates the request's images.
2609
+ * Pass the payload that Pi gives to `onPayload`. Never throws: telemetry must
2610
+ * not fail the request.
2611
+ *
2612
+ * To classify a cache miss, compare a `gen_ai.chat` span with the previous
2613
+ * call in the same `gen_ai.conversation.id`:
2614
+ * 1. `prefix.before_last_reply.hash` differs from the previous
2615
+ * `prefix.hash`: Junior changed the prefix. The system or tools hash shows
2616
+ * a prompt or tool change; `thinking.type` or `effort` shows a settings
2617
+ * change; with all part hashes equal, the model or a thinking budget
2618
+ * changed. `messages.before_last_reply.hash` not equal to the previous
2619
+ * `messages.hash` means a history rewrite, expected with
2620
+ * `gen_ai.conversation.compacted`.
2621
+ * 2. Equal, with a gap of 5 minutes or more: the cache expired.
2622
+ * 3. Equal, with a shorter gap: the provider or the gateway did not use it.
2623
+ *
2624
+ * `images.estimate` is the only per-image number, because Anthropic usage has
2625
+ * no per-image split. Check it against the change in
2626
+ * `gen_ai.usage.input_tokens` from the previous call.
2627
+ */
2628
+ function requestPrefixAttributes(payload) {
2629
+ if (typeof payload !== "object" || payload === null) return {};
2630
+ try {
2631
+ return payloadAttributes(payload);
2632
+ } catch {
2633
+ return {};
2634
+ }
2635
+ }
2636
+ // src/chat/state/cache.ts
2637
+ const MAX_CACHE_KEY_LENGTH = 512;
2638
+ const LOAD_WAIT_MS = 1e4;
2639
+ const LAST_GOOD_MS = 864e5;
2640
+ const WRITE_MARK_TTL_MS = 36e5;
2641
+ function isFresh(entry) {
2642
+ return entry.freshUntilMs === void 0 || Date.now() < entry.freshUntilMs;
2643
+ }
2644
+ async function storeEntry(state, cacheKey, entry) {
2645
+ if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
2646
+ await state.set(cacheKey, entry.staleIfError ? {
2647
+ freshUntilMs: Date.now() + entry.ttlMs,
2648
+ value: entry.value
2649
+ } : { value: entry.value }, entry.staleIfError ? entry.ttlMs + LAST_GOOD_MS : entry.ttlMs);
2650
+ }
2651
+ function writeMarkKey(cacheKey) {
2652
+ return `${cacheKey}:written`;
2653
+ }
2654
+ async function writeUnderLoadLock(state, cacheKey, write) {
2655
+ await state.connect();
2656
+ if ((await withLock(state, `${cacheKey}:load`, async () => await write(cacheKey), {
2657
+ keepAlive: true,
2658
+ waitMs: LOAD_WAIT_MS
2659
+ })).acquired) return;
2660
+ await state.set(writeMarkKey(cacheKey), randomUUID(), WRITE_MARK_TTL_MS);
2661
+ await state.delete(cacheKey);
2662
+ }
2663
+ /** The prefix of every state key of one cache namespace. */
2664
+ function cacheKeyPrefix(namespace) {
2665
+ return `junior:cache:${namespace}:`;
2666
+ }
2667
+ /**
2668
+ * Create a cache in the state adapter under `junior:cache:{namespace}:`.
2669
+ * Entries are wrapped, so `null` and `false` values are cache hits. A stale
2670
+ * `staleIfError` entry is returned when its reload throws, unless the caller
2671
+ * asked for `refresh`.
2672
+ */
2673
+ function createCache(state, namespace) {
2674
+ const stateKey = (key) => {
2675
+ if (!key.trim()) throw new Error("Cache key is required");
2676
+ if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
2677
+ return `${cacheKeyPrefix(namespace)}${key}`;
2678
+ };
2679
+ return {
2680
+ async get(key) {
2681
+ const cacheKey = stateKey(key);
2682
+ await state.connect();
2683
+ const hit = await state.get(cacheKey);
2684
+ return hit && isFresh(hit) ? hit.value : void 0;
2685
+ },
2686
+ async getOrLoad(key, load, options) {
2687
+ const cacheKey = stateKey(key);
2688
+ const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
2689
+ await state.connect();
2690
+ const hit = await cached();
2691
+ if (hit && isFresh(hit)) return hit.value;
2692
+ try {
2693
+ const attempt = await withLock(state, `${cacheKey}:load`, async () => {
2694
+ const loadedMeanwhile = await cached();
2695
+ if (loadedMeanwhile && isFresh(loadedMeanwhile)) return loadedMeanwhile.value;
2696
+ const mark = await state.get(writeMarkKey(cacheKey));
2697
+ const entry = await load();
2698
+ if (entry.ttlMs !== void 0) {
2699
+ await storeEntry(state, cacheKey, {
2700
+ ...entry,
2701
+ ttlMs: entry.ttlMs
2702
+ });
2703
+ const markNow = await state.get(writeMarkKey(cacheKey));
2704
+ if (markNow && markNow !== mark) await state.delete(cacheKey);
2705
+ }
2706
+ return entry.value;
2707
+ }, {
2708
+ keepAlive: true,
2709
+ waitMs: LOAD_WAIT_MS
2710
+ });
2711
+ if (attempt.acquired) return attempt.value;
2712
+ return (await load()).value;
2713
+ } catch (error) {
2714
+ if (hit) return hit.value;
2715
+ throw error;
2716
+ }
2717
+ },
2718
+ async update(key, next) {
2719
+ await writeUnderLoadLock(state, stateKey(key), async (cacheKey) => {
2720
+ const entry = next((await state.get(cacheKey))?.value);
2721
+ if (entry?.ttlMs !== void 0) await storeEntry(state, cacheKey, {
2722
+ ...entry,
2723
+ ttlMs: entry.ttlMs
2724
+ });
2725
+ });
2726
+ },
2727
+ async delete(key) {
2728
+ await writeUnderLoadLock(state, stateKey(key), async (cacheKey) => {
2729
+ await state.delete(cacheKey);
2730
+ });
2731
+ }
2732
+ };
2733
+ }
2734
+ // src/chat/gateway-providers/routing.ts
2735
+ const ENABLED_PROVIDERS_KEY = "junior:gateway:enabled_providers";
2736
+ const MODEL_ENDPOINTS_URL = "https://ai-gateway.vercel.sh/v1/models";
2737
+ const SERVED_PROVIDERS_CACHE_NAMESPACE = "gateway-served-providers";
2738
+ const SERVED_PROVIDERS_TTL_MS = 36e5;
2739
+ const ENDPOINTS_TIMEOUT_MS = 5e3;
2740
+ const PROVIDER_SLUGS = { vertexAnthropic: "vertex" };
2741
+ const LOCAL_TTL_MS = 6e4;
2742
+ const localEnabledProviders = /* @__PURE__ */ new Map();
2743
+ const localServedProviders = /* @__PURE__ */ new Map();
2744
+ function readLocal(entries, key, load) {
2745
+ const entry = entries.get(key);
2746
+ if (entry && entry.expiresAtMs > Date.now()) return entry.value;
2747
+ const value = load();
2748
+ entries.set(key, {
2749
+ value,
2750
+ expiresAtMs: Date.now() + LOCAL_TTL_MS
2751
+ });
2752
+ value.catch(() => {
2753
+ if (entries.get(key)?.value === value) entries.delete(key);
2754
+ });
2755
+ return value;
2756
+ }
2757
+ const enabledProvidersSchema = z.array(z.string());
2758
+ const messagesBodySchema = z.looseObject({ providerOptions: z.looseObject({ gateway: z.looseObject({}).optional() }).optional() });
2759
+ const modelEndpointsSchema = z.object({ data: z.object({ endpoints: z.array(z.object({ provider_name: z.string() })) }) });
2760
+ /** Read the enabled providers. Null means every provider is enabled. */
2761
+ async function readEnabledProviders(state) {
2762
+ const stored = await state.get(ENABLED_PROVIDERS_KEY);
2763
+ return stored === null ? null : enabledProvidersSchema.parse(stored);
2764
+ }
2765
+ /**
2766
+ * Save the enabled providers. Null enables every provider again.
2767
+ *
2768
+ * Model calls in this process see the change right away. Other processes see
2769
+ * it when their local copy expires.
2770
+ */
2771
+ async function saveEnabledProviders(state, enabled) {
2772
+ if (enabled === null) await state.delete(ENABLED_PROVIDERS_KEY);
2773
+ else await state.set(ENABLED_PROVIDERS_KEY, [...new Set(enabled)].sort());
2774
+ localEnabledProviders.clear();
2775
+ }
2776
+ async function fetchServedProviders(modelId) {
2777
+ const path = modelId.split("/").map(encodeURIComponent).join("/");
2778
+ const response = await fetch(`${MODEL_ENDPOINTS_URL}/${path}/endpoints`, { signal: AbortSignal.timeout(ENDPOINTS_TIMEOUT_MS) });
2779
+ if (response.status === 404) return [];
2780
+ if (!response.ok) throw new Error(`AI Gateway endpoints returned ${response.status}`);
2781
+ const { data } = modelEndpointsSchema.parse(await response.json());
2782
+ const slugs = data.endpoints.map(({ provider_name }) => PROVIDER_SLUGS[provider_name] ?? provider_name);
2783
+ return [...new Set(slugs)];
2784
+ }
2785
+ /** List the providers that AI Gateway can route one model to. */
2786
+ async function readServedProviders(state, modelId) {
2787
+ return await createCache(state, SERVED_PROVIDERS_CACHE_NAMESPACE).getOrLoad(modelId, async () => ({
2788
+ value: await fetchServedProviders(modelId),
2789
+ ttlMs: SERVED_PROVIDERS_TTL_MS
2790
+ }));
2791
+ }
2792
+ async function gatewayOnlyForModel(modelId) {
2793
+ const { getStateAdapter } = await import("./context-BKF_5zzI.js").then((n) => n.g);
2794
+ const state = getStateAdapter();
2795
+ const enabled = await readLocal(localEnabledProviders, "enabled", () => readEnabledProviders(state));
2796
+ if (enabled === null) return void 0;
2797
+ let served;
2798
+ try {
2799
+ served = await readLocal(localServedProviders, modelId, () => readServedProviders(state, modelId));
2800
+ } catch (error) {
2801
+ logWarn("ai.gateway.served_providers.failed", {
2802
+ "gen_ai.request.model": modelId,
2803
+ "exception.message": error instanceof Error ? error.message : String(error)
2804
+ });
2805
+ return;
2806
+ }
2807
+ return gatewayOnlyProviders(enabled, served);
2808
+ }
2809
+ function withGatewayOnly(payload, only) {
2810
+ const body = messagesBodySchema.parse(payload);
2811
+ return {
2812
+ ...body,
2813
+ providerOptions: {
2814
+ ...body.providerOptions,
2815
+ gateway: {
2816
+ ...body.providerOptions?.gateway,
2817
+ only
2818
+ }
2819
+ }
2820
+ };
2821
+ }
2822
+ /**
2823
+ * Wrap a Pi Messages stream so each request body carries the `only` list of
2824
+ * the enabled providers. AI Gateway reads it from
2825
+ * `providerOptions.gateway.only` in the Messages API body.
2826
+ */
2827
+ function withEnabledGatewayProviders(stream) {
2828
+ return (model, context, options) => stream(model, context, Object.assign({}, options, { onPayload: async (payload, payloadModel) => {
2829
+ const replaced = await options?.onPayload?.(payload, payloadModel);
2830
+ const only = await gatewayOnlyForModel(model.id);
2831
+ return only ? withGatewayOnly(replaced ?? payload, only) : replaced;
2832
+ } }));
2833
+ }
2834
+ // src/chat/pi/client.ts
2835
+ registerApiProvider({
2836
+ api: "anthropic-messages",
2837
+ stream: withEnabledGatewayProviders(streamAnthropic),
2838
+ streamSimple: withEnabledGatewayProviders(streamSimpleAnthropic)
2839
+ });
2840
+ const GEN_AI_PROVIDER_NAME = GATEWAY_PROVIDER;
2841
+ const GEN_AI_SERVER_ADDRESS = "ai-gateway.vercel.sh";
2842
+ const GEN_AI_OPERATION_CHAT = "chat";
2843
+ const GEN_AI_OPERATION_EMBEDDINGS = "embeddings";
2844
+ const GEN_AI_OPERATION_RERANK = "rerank";
2845
+ const GEN_AI_OPERATION_DECIDE = "decide";
2846
+ const EMBEDDING_INPUT_COST_USD_PER_MILLION_TOKENS = {
2847
+ "cohere/embed-v4.0": .12,
2848
+ "google/gemini-embedding-001": .15,
2849
+ "google/text-embedding-005": .025,
2850
+ "mistral/mistral-embed": .1,
2851
+ "openai/text-embedding-3-large": .13,
2852
+ "openai/text-embedding-3-small": .02,
2853
+ "openai/text-embedding-ada-002": .1,
2854
+ "voyage/voyage-3.5": .06,
2855
+ "voyage/voyage-3.5-lite": .02,
2856
+ "voyage/voyage-4": .06,
2857
+ "voyage/voyage-4-large": .12,
2858
+ "voyage/voyage-4-lite": .02
2859
+ };
2860
+ const DECISION_INPUT_COST_USD_PER_MILLION_TOKENS = {
2861
+ "openai/gpt-6-luna-decisions": .1,
2862
+ "typesafe-ai/jev": .042
2863
+ };
2864
+ function decisionCostUsd(modelId, inputTokens) {
2865
+ const costPerMillionTokens = DECISION_INPUT_COST_USD_PER_MILLION_TOKENS[modelId];
2866
+ return costPerMillionTokens === void 0 || inputTokens === void 0 ? void 0 : inputTokens * costPerMillionTokens / 1e6;
2867
+ }
2868
+ function embeddingCostUsd(modelId, inputTokens) {
2869
+ const costPerMillionTokens = EMBEDDING_INPUT_COST_USD_PER_MILLION_TOKENS[modelId];
2870
+ return costPerMillionTokens === void 0 ? void 0 : inputTokens * costPerMillionTokens / 1e6;
2871
+ }
2872
+ function extractText(message) {
2873
+ return (message.content ?? []).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text ?? "").join("").trim();
2874
+ }
2875
+ /** Execute a direct chat completion inside a dedicated `gen_ai.chat` span. */
2876
+ async function completeText$1(params) {
2877
+ const model = resolveGatewayModel(params.modelId);
2878
+ const credential = await resolveGatewayCredential();
2879
+ const apiKey = credential.token;
2880
+ const authMode = credential.mode;
2881
+ const effectivePrivacy = getCurrentConversationPrivacy() ?? "private";
2882
+ const recordContent = (params.messageAttributeMode ?? (effectivePrivacy === "public" ? "content" : "metadata")) === "content";
2883
+ const baseAttributes = {
2884
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
2885
+ "gen_ai.operation.name": GEN_AI_OPERATION_CHAT,
2886
+ "gen_ai.request.model": params.modelId,
2887
+ "gen_ai.prompt.name": params.promptName,
2888
+ "server.address": GEN_AI_SERVER_ADDRESS,
2889
+ "gen_ai.conversation.compacted": hasCompactedConversationContext(params.messages) || void 0,
2890
+ "app.conversation.privacy": effectivePrivacy,
2891
+ "gen_ai.request.reasoning.level": params.thinkingLevel,
2892
+ "gen_ai.request.max_tokens": params.maxTokens
2893
+ };
2894
+ const startAttributes = {
2895
+ ...baseAttributes,
2896
+ ...toGenAiMessagesTraceAttributes("gen_ai.input", params.messages),
2897
+ "gen_ai.system_instructions.content_chars": params.system?.length,
2898
+ "gen_ai.system_instructions": recordContent && params.system ? serializeGenAiAttribute([{
2899
+ type: "text",
2900
+ content: params.system
2901
+ }]) : void 0,
2902
+ "gen_ai.input.messages": recordContent ? serializeGenAiAttribute(params.messages.map(toCanonicalInputMessage)) : void 0,
2903
+ "gen_ai.provider.auth_mode": authMode
2904
+ };
2905
+ return withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
2906
+ let message;
2907
+ try {
2908
+ message = await completeSimple(model, {
2909
+ systemPrompt: params.system,
2910
+ messages: params.messages,
2911
+ ...params.tools ? { tools: params.tools } : void 0
2912
+ }, {
2913
+ apiKey,
2914
+ maxTokens: params.maxTokens,
2915
+ reasoning: params.thinkingLevel,
2916
+ cacheRetention: params.cacheRetention,
2917
+ signal: params.signal,
2918
+ metadata: params.metadata,
2919
+ sessionId: params.sessionId,
2920
+ onPayload: (payload) => {
2921
+ setSpanAttributes(requestPrefixAttributes(payload));
2922
+ },
2923
+ onResponse: (response) => {
2924
+ setSpanAttributes({ "app.ai.gateway.vercel_id": response.headers["x-vercel-id"] });
2925
+ },
2926
+ onProviderStreamEvent: (event) => {
2927
+ setSpanAttributes(gatewayRoutingAttributes(event) ?? {});
2928
+ }
2929
+ });
2930
+ } catch (error) {
2931
+ throw createProviderError(error, { modelId: params.modelId });
2932
+ }
2933
+ const outputText = extractText(message);
2934
+ setSpanAttributes({
2935
+ ...toGenAiMessagesTraceAttributes("gen_ai.output", [{
2936
+ role: "assistant",
2937
+ content: outputText ? [{
2938
+ type: "text",
2939
+ text: outputText
2940
+ }] : []
2941
+ }]),
2942
+ "gen_ai.output.messages": recordContent ? serializeGenAiAttribute([toCanonicalOutputMessage(message)]) : void 0,
2943
+ ...extractGenAiUsageAttributes(message),
2944
+ "gen_ai.response.finish_reasons": [message.stopReason],
2945
+ "gen_ai.response.model": message.model,
2946
+ "gen_ai.response.id": message.responseId
2947
+ });
2948
+ if (message.stopReason === "error") {
2949
+ const providerMessage = message.errorMessage?.trim() || "Unknown provider error";
2950
+ logWarn("ai.completion.provider_error", {
2951
+ ...baseAttributes,
2952
+ "exception.message": providerMessage
2953
+ });
2954
+ throw createProviderError(providerMessage, { modelId: params.modelId });
2955
+ }
2956
+ return {
2957
+ message,
2958
+ text: outputText
2959
+ };
2960
+ }, startAttributes);
2961
+ }
2962
+ function logContextFromMetadata(modelId, metadata) {
2963
+ const conversationId = typeof metadata?.["conversationId"] === "string" && metadata["conversationId"] ? metadata["conversationId"] : void 0;
2964
+ const messageConversationId = typeof metadata?.["threadId"] === "string" ? metadata["threadId"] : void 0;
2965
+ const destinationName = typeof metadata?.["channelId"] === "string" ? metadata["channelId"] : void 0;
2966
+ const runId = typeof metadata?.["runId"] === "string" ? metadata["runId"] : void 0;
2967
+ return {
2968
+ modelId,
2969
+ ...conversationId ? { conversationId } : void 0,
2970
+ ...messageConversationId ? { messageConversationId } : void 0,
2971
+ ...destinationName ? { destinationName } : void 0,
2972
+ ...runId ? { runId } : void 0
2973
+ };
2974
+ }
2975
+ function objectCompletionCost(modelId, usage) {
2976
+ const cacheRead = usage.inputTokenDetails.cacheReadTokens;
2977
+ const cacheWrite = usage.inputTokenDetails.cacheWriteTokens;
2978
+ const input = usage.inputTokenDetails.noCacheTokens ?? (usage.inputTokens === void 0 ? void 0 : Math.max(0, usage.inputTokens - (cacheRead ?? 0) - (cacheWrite ?? 0)));
2979
+ if (input === void 0 && usage.outputTokens === void 0 && cacheRead === void 0 && cacheWrite === void 0) return;
2980
+ return calculateCost(resolveGatewayModel(modelId), {
2981
+ input: input ?? 0,
2982
+ output: usage.outputTokens ?? 0,
2983
+ cacheRead: cacheRead ?? 0,
2984
+ cacheWrite: cacheWrite ?? 0,
2985
+ ...usage.outputTokenDetails.reasoningTokens !== void 0 ? { reasoning: usage.outputTokenDetails.reasoningTokens } : void 0,
2986
+ totalTokens: usage.totalTokens ?? (input ?? 0) + (usage.outputTokens ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0),
2987
+ cost: {
2988
+ input: 0,
2989
+ output: 0,
2990
+ cacheRead: 0,
2991
+ cacheWrite: 0,
2992
+ total: 0
2993
+ }
2994
+ }).total;
2995
+ }
2996
+ /** Estimate cost without changing the outcome of a successful completion. */
2997
+ function bestEffortObjectCompletionCost(modelId, usage) {
2998
+ try {
2999
+ return objectCompletionCost(modelId, usage);
3000
+ } catch (error) {
3001
+ logWarn("ai.completion.cost_estimate.failed", {
3002
+ "exception.message": error instanceof Error ? error.message : String(error),
3003
+ "gen_ai.request.model": modelId
3004
+ });
3005
+ return;
3006
+ }
3007
+ }
3008
+ /** Execute a schema-constrained completion using the AI SDK structured output path. */
3009
+ async function completeObject$1(params) {
3010
+ const maxOutputTokens = structuredOutputTokenLimit(params.maxTokens, findGatewayModel(params.modelId)?.maxTokens);
3011
+ const credential = await resolveGatewayCredential();
3012
+ const provider = createGatewayProvider({ apiKey: credential.token });
3013
+ let result;
3014
+ try {
3015
+ result = await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
3016
+ const result = await generateObject({
3017
+ model: provider.chat(params.modelId),
3018
+ schema: params.schema,
3019
+ prompt: params.prompt,
3020
+ ...params.system !== void 0 ? { system: params.system } : void 0,
3021
+ ...maxOutputTokens !== void 0 ? { maxOutputTokens } : void 0,
3022
+ ...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
3023
+ }).catch((error) => {
3024
+ if (NoObjectGeneratedError.isInstance(error)) setSpanAttributes(objectCompletionAttributes(error.finishReason, error.usage));
3025
+ throw error;
3026
+ });
3027
+ setSpanAttributes(objectCompletionAttributes(result.finishReason, result.usage));
3028
+ return result;
3029
+ }, {
3030
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
3031
+ "gen_ai.operation.name": GEN_AI_OPERATION_CHAT,
3032
+ "gen_ai.request.model": params.modelId,
3033
+ "gen_ai.prompt.name": params.promptName,
3034
+ "server.address": GEN_AI_SERVER_ADDRESS,
3035
+ "gen_ai.provider.auth_mode": credential.mode,
3036
+ "gen_ai.request.reasoning.level": params.thinkingLevel,
3037
+ "gen_ai.request.max_tokens": maxOutputTokens
3038
+ });
3039
+ } catch (error) {
3040
+ if (NoObjectGeneratedError.isInstance(error)) throw createProviderError(structuredOutputErrorCause(error), {
3041
+ kind: "invalid_response",
3042
+ modelId: params.modelId
3043
+ });
3044
+ throw createProviderError(error, { modelId: params.modelId });
3045
+ }
3046
+ const costUsd = bestEffortObjectCompletionCost(params.modelId, result.usage);
3047
+ return {
3048
+ object: result.object,
3049
+ ...costUsd !== void 0 ? { costUsd } : void 0
3050
+ };
3051
+ }
3052
+ /** Answer typed decision questions with an AI Gateway decision model, such as Jev. */
3053
+ async function completeDecision$1(params) {
3054
+ const credential = await resolveGatewayCredential();
3055
+ const provider = createGatewayProvider({ apiKey: credential.token });
3056
+ try {
3057
+ const result = await withSpan(`${GEN_AI_OPERATION_DECIDE} ${params.modelId}`, "gen_ai.decide", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
3058
+ const result = await experimental_decide({
3059
+ model: provider.decisionModel(params.modelId),
3060
+ state: params.state,
3061
+ questions: params.questions,
3062
+ ...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
3063
+ });
3064
+ const costUsd = decisionCostUsd(params.modelId, result.usage.inputTokens);
3065
+ setSpanAttributes(extractGenAiUsageAttributes(result.usage, { cost: {
3066
+ input: costUsd,
3067
+ total: costUsd
3068
+ } }));
3069
+ return {
3070
+ answers: result.answers,
3071
+ costUsd
3072
+ };
3073
+ }, {
3074
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
3075
+ "gen_ai.operation.name": GEN_AI_OPERATION_DECIDE,
3076
+ "gen_ai.request.model": params.modelId,
3077
+ "gen_ai.prompt.name": params.promptName,
3078
+ "server.address": GEN_AI_SERVER_ADDRESS,
3079
+ "gen_ai.provider.auth_mode": credential.mode
3080
+ });
3081
+ return {
3082
+ answers: result.answers,
3083
+ ...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0
3084
+ };
3085
+ } catch (error) {
3086
+ throw createProviderError(error, {
3087
+ ...Experimental_DecisionRefusalError.isInstance(error) ? { kind: "invalid_response" } : void 0,
3088
+ modelId: params.modelId
3089
+ });
3090
+ }
3091
+ }
3092
+ /** Map the input type to the provider option for models that embed queries and documents differently. */
3093
+ function embeddingProviderOptions(modelId, inputType) {
3094
+ if (inputType === void 0 || !modelId.startsWith("voyage/")) return;
3095
+ return { voyage: { inputType } };
3096
+ }
3097
+ /** Generate text embeddings through the host-owned AI Gateway provider. */
3098
+ async function embedTexts$1(params) {
3099
+ const texts = params.texts.map((text) => text.trim());
3100
+ if (texts.length === 0 || texts.some((text) => text.length === 0)) throw new Error("Embedding text is required.");
3101
+ const credential = await resolveGatewayCredential();
3102
+ const provider = createGatewayProvider({ apiKey: credential.token });
3103
+ const providerOptions = embeddingProviderOptions(params.modelId, params.inputType);
3104
+ try {
3105
+ const result = await withSpan(`${GEN_AI_OPERATION_EMBEDDINGS} ${params.modelId}`, "gen_ai.embeddings", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
3106
+ const result = await embedMany({
3107
+ model: provider.embeddingModel(params.modelId),
3108
+ values: texts,
3109
+ ...providerOptions !== void 0 ? { providerOptions } : void 0,
3110
+ ...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
3111
+ });
3112
+ const dimensions = result.embeddings[0]?.length;
3113
+ if (result.embeddings.length !== texts.length || !dimensions || !result.embeddings.every((embedding) => embedding.length === dimensions)) throw createProviderError("Embedding provider returned invalid vectors.", {
3114
+ kind: "invalid_response",
3115
+ modelId: params.modelId
3116
+ });
3117
+ const costUsd = embeddingCostUsd(params.modelId, result.usage.tokens);
3118
+ setSpanAttributes({
3119
+ "gen_ai.embeddings.dimension.count": dimensions,
3120
+ ...extractGenAiUsageAttributes({
3121
+ inputTokens: result.usage.tokens,
3122
+ cost: {
3123
+ input: costUsd,
3124
+ total: costUsd
3125
+ }
3126
+ })
3127
+ });
3128
+ return {
3129
+ costUsd,
3130
+ dimensions,
3131
+ result
3132
+ };
3133
+ }, {
3134
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
3135
+ "gen_ai.operation.name": GEN_AI_OPERATION_EMBEDDINGS,
3136
+ "gen_ai.request.model": params.modelId,
3137
+ "server.address": GEN_AI_SERVER_ADDRESS,
3138
+ "gen_ai.provider.auth_mode": credential.mode
3139
+ });
3140
+ return {
3141
+ ...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0,
3142
+ dimensions: result.dimensions,
3143
+ model: params.modelId,
3144
+ provider: GEN_AI_PROVIDER_NAME,
3145
+ vectors: result.result.embeddings
3146
+ };
3147
+ } catch (error) {
3148
+ const providerError = createProviderError(error, { modelId: params.modelId });
3149
+ if (isProviderRetryError(providerError)) throw providerError;
3150
+ logException(providerError, "ai.embeddings.failed", {
3151
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
3152
+ "gen_ai.operation.name": GEN_AI_OPERATION_EMBEDDINGS,
3153
+ "gen_ai.request.model": params.modelId
3154
+ });
3155
+ throw providerError;
3156
+ }
3157
+ }
3158
+ /** Read the billed cost that AI Gateway reports in provider metadata. */
3159
+ function gatewayCostUsd(providerMetadata) {
3160
+ const cost = providerMetadata?.gateway?.cost;
3161
+ const value = typeof cost === "string" ? Number(cost) : cost;
3162
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
3163
+ }
3164
+ /** Score documents against one query through the host-owned AI Gateway provider. */
3165
+ async function rerankTexts(params) {
3166
+ const query = params.query.trim();
3167
+ if (!query || params.documents.length === 0) throw new Error("Reranking query and documents are required.");
3168
+ const credential = await resolveGatewayCredential();
3169
+ const provider = createGatewayProvider({ apiKey: credential.token });
3170
+ try {
3171
+ return await withSpan(`${GEN_AI_OPERATION_RERANK} ${params.modelId}`, "gen_ai.rerank", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
3172
+ const result = await rerank({
3173
+ model: provider.rerankingModel(params.modelId),
3174
+ query,
3175
+ documents: params.documents
3176
+ });
3177
+ const scores = params.documents.map(() => NaN);
3178
+ for (const { originalIndex, score } of result.ranking) scores[originalIndex] = score;
3179
+ if (result.ranking.length !== params.documents.length || !scores.every(Number.isFinite)) throw createProviderError("Reranking provider returned invalid scores.", {
3180
+ kind: "invalid_response",
3181
+ modelId: params.modelId
3182
+ });
3183
+ const costUsd = gatewayCostUsd(result.providerMetadata);
3184
+ setSpanAttributes(extractGenAiUsageAttributes({ cost: { total: costUsd } }));
3185
+ return {
3186
+ ...costUsd !== void 0 ? { costUsd } : void 0,
3187
+ scores
3188
+ };
3189
+ }, {
3190
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
3191
+ "gen_ai.operation.name": GEN_AI_OPERATION_RERANK,
3192
+ "gen_ai.request.model": params.modelId,
3193
+ "server.address": GEN_AI_SERVER_ADDRESS,
3194
+ "gen_ai.provider.auth_mode": credential.mode,
3195
+ "app.rerank.document.count": params.documents.length
3196
+ });
3197
+ } catch (error) {
3198
+ const providerError = createProviderError(error, { modelId: params.modelId });
3199
+ if (isProviderRetryError(providerError)) throw providerError;
3200
+ logException(providerError, "ai.rerank.failed", {
3201
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
3202
+ "gen_ai.operation.name": GEN_AI_OPERATION_RERANK,
3203
+ "gen_ai.request.model": params.modelId
3204
+ });
3205
+ throw providerError;
3206
+ }
3207
+ }
3208
+ const WEB_SEARCH_TOOL_NAME = "parallelSearch";
3209
+ /** Run one AI Gateway parallel search inside a `gen_ai.chat` span. */
3210
+ async function searchWeb$1(params) {
3211
+ const credential = await resolveGatewayCredential();
3212
+ const provider = createGatewayProvider({ apiKey: credential.token });
3213
+ return await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", {}, async (setSpanAttributes) => {
3214
+ const response = await generateText({
3215
+ model: provider.chat(params.modelId),
3216
+ prompt: params.query,
3217
+ tools: { [WEB_SEARCH_TOOL_NAME]: provider.tools.parallelSearch({
3218
+ mode: "agentic",
3219
+ maxResults: params.maxResults
3220
+ }) },
3221
+ toolChoice: {
3222
+ type: "tool",
3223
+ toolName: WEB_SEARCH_TOOL_NAME
3224
+ },
3225
+ abortSignal: params.signal
3226
+ });
3227
+ const costUsd = gatewayCostUsd(response.providerMetadata);
3228
+ setSpanAttributes({
3229
+ "gen_ai.response.finish_reasons": [response.finishReason],
3230
+ ...extractGenAiUsageAttributes(response.usage, { cost: { total: costUsd } })
3231
+ });
3232
+ return {
3233
+ ...costUsd !== void 0 ? { costUsd } : void 0,
3234
+ outputs: response.toolResults.filter((result) => result.toolName === WEB_SEARCH_TOOL_NAME).map((result) => result.output)
3235
+ };
3236
+ }, {
3237
+ "gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
3238
+ "gen_ai.operation.name": GEN_AI_OPERATION_CHAT,
3239
+ "gen_ai.request.model": params.modelId,
3240
+ "gen_ai.prompt.name": params.promptName,
3241
+ "server.address": GEN_AI_SERVER_ADDRESS,
3242
+ "gen_ai.provider.auth_mode": credential.mode
3243
+ });
3244
+ }
3245
+ /** Generate or edit images with an AI Gateway image model. */
3246
+ async function generateImages$1(params) {
3247
+ const provider = createGatewayProvider({
3248
+ apiKey: await getGatewayApiKey(),
3249
+ ...params.fetch ? { fetch: params.fetch } : void 0
3250
+ });
3251
+ try {
3252
+ const result = await generateImage({
3253
+ model: provider.imageModel(params.modelId),
3254
+ prompt: params.prompt,
3255
+ n: 1
3256
+ });
3257
+ const costUsd = gatewayCostUsd(result.providerMetadata);
3258
+ return {
3259
+ ...costUsd !== void 0 ? { costUsd } : void 0,
3260
+ images: result.images
3261
+ };
3262
+ } catch (error) {
3263
+ if (NoImageGeneratedError.isInstance(error)) return { images: [] };
3264
+ throw error;
3265
+ }
3266
+ }
3267
+ // src/chat/pi/transcription.ts
3268
+ const GEN_AI_OPERATION_TRANSCRIPTION = "transcription";
3269
+ const NO_AUDIO_PATTERN = /\(invalid_audio\)\s*$/;
3270
+ const SENTENCE_END_PATTERN = /[.?!]["')\]]*$/;
3271
+ /** The file has no audio that the model can transcribe. */
3272
+ var NoAudioError = class extends Error {
3273
+ name = "NoAudioError";
3274
+ };
3275
+ const diarizedWordsSchema = z.object({ elevenlabs: z.object({ words: z.array(z.object({
3276
+ speaker_id: z.string().nullish(),
3277
+ start: z.number(),
3278
+ text: z.string(),
3279
+ type: z.string()
3280
+ })) }) });
3281
+ /**
3282
+ * Group diarized words into entries. A speech entry ends when the speaker
3283
+ * changes or a sentence ends. Each audio event is its own sound entry.
3284
+ * Spaces join words and never start an entry.
3285
+ */
3286
+ function transcriptEntries(words) {
3287
+ const entries = [];
3288
+ let current;
3289
+ for (const word of words) {
3290
+ if (word.type === "spacing") {
3291
+ if (current) current.text += word.text;
3292
+ continue;
3293
+ }
3294
+ if (word.type === "audio_event") {
3295
+ entries.push({
3296
+ kind: "sound",
3297
+ startSeconds: word.start,
3298
+ text: word.text.replace(/^[[(]+|[\])]+$/g, "")
3299
+ });
3300
+ current = void 0;
3301
+ continue;
3302
+ }
3303
+ const speaker = word.speaker_id ?? void 0;
3304
+ if (!current || current.speaker !== speaker) {
3305
+ current = {
3306
+ kind: "speech",
3307
+ startSeconds: word.start,
3308
+ text: "",
3309
+ ...speaker ? { speaker } : void 0
3310
+ };
3311
+ entries.push(current);
3312
+ }
3313
+ current.text += word.text;
3314
+ if (SENTENCE_END_PATTERN.test(word.text)) current = void 0;
3315
+ }
3316
+ return entries.map((entry) => ({
3317
+ ...entry,
3318
+ text: entry.text.trim()
3319
+ })).filter((entry) => entry.text.length > 0);
3320
+ }
3321
+ /**
3322
+ * Keep the classification of a failed call, but not the SDK error. That
3323
+ * error keeps the request body, and the body holds the signed URL.
3324
+ */
3325
+ function withoutSourceUrl(error, sourceUrl, modelId) {
3326
+ const failure = error instanceof Error ? error : void 0;
3327
+ const message = (failure?.message ?? String(error)).replaceAll(sourceUrl, "<signed URL>");
3328
+ const classified = createProviderError(Object.assign(new Error(message, { cause: failure?.cause }), {
3329
+ code: failure && "code" in failure ? failure.code : void 0,
3330
+ statusCode: failure && "statusCode" in failure ? failure.statusCode : void 0
3331
+ }), { modelId });
3332
+ return new ProviderError({
3333
+ cause: new Error(message),
3334
+ kind: classified.kind,
3335
+ modelId,
3336
+ retryable: classified.retryable,
3337
+ retryAfterMs: classified.retryAfterMs,
3338
+ status: classified.status
3339
+ });
3340
+ }
3341
+ /**
3342
+ * Transcribe speech in a file that the provider downloads from `sourceUrl`.
3343
+ *
3344
+ * The URL goes to the provider as `sourceUrl` with empty audio, so the file
3345
+ * never passes through this process. The URL is a bearer credential: it is
3346
+ * not put on spans, logs, or errors.
3347
+ */
3348
+ async function transcribeFromUrl$1(params) {
3349
+ const credential = await resolveGatewayCredential();
3350
+ const provider = createGatewayProvider({ apiKey: credential.token });
3351
+ try {
3352
+ return await withSpan(`${GEN_AI_OPERATION_TRANSCRIPTION} ${params.modelId}`, "gen_ai.transcription", {
3353
+ modelId: params.modelId,
3354
+ ...params.conversationId ? { conversationId: params.conversationId } : void 0
3355
+ }, async (setSpanAttributes) => {
3356
+ const result = await transcribe({
3357
+ model: provider.transcriptionModel(params.modelId),
3358
+ audio: /* @__PURE__ */ new Uint8Array(),
3359
+ providerOptions: { elevenlabs: {
3360
+ diarize: true,
3361
+ sourceUrl: params.sourceUrl,
3362
+ tagAudioEvents: true
3363
+ } },
3364
+ ...params.signal ? { abortSignal: params.signal } : void 0
3365
+ }).catch((error) => {
3366
+ if (error instanceof Error && NO_AUDIO_PATTERN.test(error.message)) {
3367
+ setSpanAttributes({ "error.type": "invalid_audio" });
2374
3368
  throw new NoAudioError("The file has no audio to transcribe.");
2375
3369
  }
2376
3370
  throw error;
@@ -2642,17 +3636,9 @@ function conversationSimilarity(query) {
2642
3636
  return sql`CASE WHEN ${table.provider} = ${query.provider} AND ${table.model} = ${query.model} THEN 1 - ${distance} END`;
2643
3637
  }
2644
3638
  // src/chat/conversations/event-embedding-config.ts
2645
- var event_embedding_config_exports = /* @__PURE__ */ __exportAll({ setEventEmbeddingsConfig: () => setEventEmbeddingsConfig });
2646
- let configuredEventEmbeddings = {};
2647
- /** Replace app-level event embedding settings and return the previous setting. */
2648
- function setEventEmbeddingsConfig(config) {
2649
- const previous = { ...configuredEventEmbeddings };
2650
- configuredEventEmbeddings = config ? { ...config } : {};
2651
- return previous;
2652
- }
2653
3639
  /** Return whether event embeddings and meaning search are enabled. */
2654
3640
  function isEventEmbeddingsEnabled() {
2655
- return configuredEventEmbeddings.enabled === true;
3641
+ return getChatConfig().eventEmbeddings.enabled === true;
2656
3642
  }
2657
3643
  // src/chat/conversations/sql/message-json.ts
2658
3644
  const UNICODE_ESCAPE = String.raw`\u`;
@@ -2887,45 +3873,230 @@ async function indexConversationEvents(args) {
2887
3873
  })).acquired) logInfo("event_search.index.busy", { conversationId });
2888
3874
  }
2889
3875
  /**
2890
- * Index the events of a Turn that ended without the event search task: a
2891
- * failed or stopped Turn, or a completed Turn of a kind without session
2892
- * tasks. A failure is logged, so indexing never changes the Turn's outcome.
3876
+ * Index the events of a Turn that ended without the event search task: a
3877
+ * failed or stopped Turn, or a completed Turn of a kind without session
3878
+ * tasks. A failure is logged, so indexing never changes the Turn's outcome.
3879
+ */
3880
+ async function indexEndedTurnEvents(args) {
3881
+ const { conversationId, turnId } = args;
3882
+ try {
3883
+ await indexConversationEvents({
3884
+ conversationId,
3885
+ embedEvents: isEventEmbeddingsEnabled(),
3886
+ turnId
3887
+ });
3888
+ } catch (error) {
3889
+ logException(error, "event_search.index.failed", {
3890
+ conversationId,
3891
+ turnId
3892
+ });
3893
+ }
3894
+ }
3895
+ /**
3896
+ * Core task registration that indexes the events of a completed Turn:
3897
+ * lexemes, and vectors when `embedEvents` is set.
3898
+ */
3899
+ function eventSearchTaskRegistration(options) {
3900
+ return {
3901
+ manifest: {
3902
+ name: "event-search",
3903
+ displayName: "Event search",
3904
+ description: "Lexemes and embeddings for Conversation history search"
3905
+ },
3906
+ tasks: { indexEvents: { async run(context) {
3907
+ const run = await context.run.load();
3908
+ await indexConversationEvents({
3909
+ conversationId: run.conversationId,
3910
+ embedEvents: options.embedEvents,
3911
+ turnId: run.runId
3912
+ });
3913
+ } } }
3914
+ };
3915
+ }
3916
+ // src/chat/tool-support/tool-input-error.ts
3917
+ /** Thrown when a tool fails due to invalid model/user input, not a system error. */
3918
+ var ToolInputError = class extends Error {
3919
+ constructor(message, options) {
3920
+ super(message, options);
3921
+ this.name = "ToolInputError";
3922
+ }
3923
+ };
3924
+ /** Whether an error is an expected tool input failure that is not a Sentry exception. */
3925
+ function isToolInputError(error) {
3926
+ return error instanceof ToolInputError || error instanceof PluginToolInputError || error instanceof Error && error.name === "PluginToolInputError";
3927
+ }
3928
+ // src/chat/events/catalog.ts
3929
+ /** A source with nothing enabled, for a namespace that the catalog lacks. */
3930
+ const NO_SOURCE = {
3931
+ resourceTypes: [],
3932
+ events: {},
3933
+ anyResourceFields: {}
3934
+ };
3935
+ /**
3936
+ * Build one catalog entry. It merges the filters of every resource type here,
3937
+ * once, so trigger checks for each event copy and each row do not merge them
3938
+ * again.
3939
+ */
3940
+ function eventCatalogEntry(registration) {
3941
+ return {
3942
+ ...registration,
3943
+ anyResourceFields: anyResourceMatchFields(registration.resourceTypes)
3944
+ };
3945
+ }
3946
+ /** Core-owned event namespace. Not a plugin publisher. */
3947
+ const CORE_EVENT_NAMESPACE = "junior";
3948
+ /** True when the catalog has any enabled registration. */
3949
+ function hasEventCatalogEntries(catalog) {
3950
+ return Object.keys(catalog).length > 0;
3951
+ }
3952
+ /**
3953
+ * Catalog entries that durable event automations may select.
3954
+ *
3955
+ * Resource types with `automation: false` stay out of create/update schemas
3956
+ * and trigger availability. A namespace with no such resource type left is
3957
+ * removed.
3958
+ */
3959
+ function automationEventCatalog(catalog) {
3960
+ return Object.fromEntries(Object.entries(catalog).flatMap(([namespace, registration]) => {
3961
+ const resourceTypes = registration.resourceTypes.filter((resourceType) => registration.limits?.[resourceType.type]?.automation !== false);
3962
+ if (resourceTypes.length === 0) return [];
3963
+ if (resourceTypes.length === registration.resourceTypes.length) return [[namespace, registration]];
3964
+ const supported = new Set(resourceTypes.flatMap((resourceType) => resourceType.supportedEvents));
3965
+ return [[namespace, eventCatalogEntry({
3966
+ ...registration,
3967
+ resourceTypes,
3968
+ events: Object.fromEntries(Object.entries(registration.events).filter(([eventType]) => supported.has(eventType)))
3969
+ })]];
3970
+ }));
3971
+ }
3972
+ /** Return why watchEvents cannot watch one resource type, if it cannot. */
3973
+ function eventWatchUnavailable(catalog, namespace, resourceType) {
3974
+ const limits = catalog[namespace]?.limits?.[resourceType];
3975
+ return limits?.watch === false ? limits.watchUnavailableMessage : void 0;
3976
+ }
3977
+ function enumSchema(values, unavailableMessage) {
3978
+ if (values.length === 0) return z.string().refine(() => false, unavailableMessage);
3979
+ return z.enum(values);
3980
+ }
3981
+ /** Build the model-facing namespace enum from enabled event plugins. */
3982
+ function eventNamespaceSchema(catalog) {
3983
+ return enumSchema(Object.keys(catalog).sort(), "No event namespaces are enabled.");
3984
+ }
3985
+ /** Build the model-facing event enum from enabled plugin registrations. */
3986
+ function registeredEventTypeSchema(catalog) {
3987
+ return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.flatMap((resourceType) => resourceType.supportedEvents)))].sort(), "No event types are enabled.");
3988
+ }
3989
+ /** Build the model-facing resource type enum from enabled plugin registrations. */
3990
+ function registeredResourceTypeSchema(catalog) {
3991
+ return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.map((resourceType) => resourceType.type)))].sort(), "No resource types are enabled.");
3992
+ }
3993
+ /**
3994
+ * Return app guidance for one event of a namespace. The source declares it
3995
+ * once for the event, so every resource type and a trigger with no resource
3996
+ * type get the same guidance.
3997
+ */
3998
+ function eventGuidance(catalog, namespace, eventType) {
3999
+ return catalog[namespace]?.events[eventType]?.guidance;
4000
+ }
4001
+ /** Build the match object the tools accept for one resource type. */
4002
+ function registeredEventMatchSchema() {
4003
+ return agentEventMatchSchema.optional().describe("Optional filters: exact values for the resource type match_fields, with snake_case keys. A single value must equal the event data. A list means the event value may be any one entry. For a field with list: true, the event value is a list, and it matches when it includes the value or any entry. A field with events is set only on those events, so every selected event must be in that list. Omit a key to ignore it. Unmatched events are dropped with no agent turn.");
4004
+ }
4005
+ /**
4006
+ * List why a selection cannot work with the enabled plugins. Use it for new
4007
+ * selections and for saved triggers, which can go stale after a plugin renames
4008
+ * or removes a resource type, event, or filter.
4009
+ */
4010
+ function registeredEventTriggerProblems(catalog, selection, options) {
4011
+ return eventTriggerProblems(catalog[selection.namespace] ?? NO_SOURCE, selection, options);
4012
+ }
4013
+ /**
4014
+ * Describe a selection with the enabled plugins, for the dashboard and Slack.
4015
+ * Its problems are the same as `registeredEventTriggerProblems`.
4016
+ */
4017
+ function describeRegisteredEventTrigger(catalog, selection) {
4018
+ return describeEventTrigger(catalog[selection.namespace] ?? NO_SOURCE, selection);
4019
+ }
4020
+ function uniqueMatchValues(match) {
4021
+ if (!match || Object.keys(match).length === 0) return void 0;
4022
+ return Object.fromEntries(Object.entries(match).map(([key, value]) => [key, Array.isArray(value) ? [...new Set(value)] : value]));
4023
+ }
4024
+ /**
4025
+ * Reject an event automation trigger or a Watch that cannot work, with every
4026
+ * problem in one message for the agent. Return its match as it is saved:
4027
+ * each text value in the case that its plugin declares, with no repeated
4028
+ * list values. The dashboard clears `inputKeys` so messages name the filters
4029
+ * as its plugin declares them.
2893
4030
  */
2894
- async function indexEndedTurnEvents(args) {
2895
- const { conversationId, turnId } = args;
2896
- try {
2897
- await indexConversationEvents({
2898
- conversationId,
2899
- embedEvents: isEventEmbeddingsEnabled(),
2900
- turnId
2901
- });
2902
- } catch (error) {
2903
- logException(error, "event_search.index.failed", {
2904
- conversationId,
2905
- turnId
2906
- });
4031
+ function requireValidEventTrigger(catalog, selection, target, options = { inputKeys: true }) {
4032
+ const fields = eventTriggerChoices(catalog[selection.namespace] ?? NO_SOURCE, selection)?.fields ?? {};
4033
+ const normalized = {
4034
+ ...selection,
4035
+ match: normalizeEventMatch(fields, selection.match)
4036
+ };
4037
+ const problems = registeredEventTriggerProblems(catalog, normalized, options);
4038
+ if (problems.length > 0) {
4039
+ const source = catalog[selection.namespace]?.displayName ?? selection.namespace;
4040
+ const resource = selection.resourceType ? `${source} ${selection.resourceType.replaceAll("_", " ")}` : source;
4041
+ throw new ToolInputError([target === "watch" ? `This ${resource} watch cannot be created.` : `This ${resource} trigger cannot be saved.`, ...problems.map((problem) => problem.message)].join(" "));
2907
4042
  }
4043
+ return uniqueMatchValues(normalized.match);
2908
4044
  }
2909
4045
  /**
2910
- * Core task registration that indexes the events of a completed Turn:
2911
- * lexemes, and vectors when `embedEvents` is set.
4046
+ * Normalize one selector with the convention declared by its plugin.
4047
+ *
4048
+ * Reject a selector that does not fit its resource type. Resource types can
4049
+ * share event types, so only the identifier shows which one a selector names.
2912
4050
  */
2913
- function eventSearchTaskRegistration(options) {
2914
- return {
2915
- manifest: {
2916
- name: "event-search",
2917
- displayName: "Event search",
2918
- description: "Lexemes and embeddings for Conversation history search"
2919
- },
2920
- tasks: { indexEvents: { async run(context) {
2921
- const run = await context.run.load();
2922
- await indexConversationEvents({
2923
- conversationId: run.conversationId,
2924
- embedEvents: options.embedEvents,
2925
- turnId: run.runId
2926
- });
2927
- } } }
2928
- };
4051
+ function requireEventIdentifier(catalog, input) {
4052
+ const registration = catalog[input.namespace];
4053
+ const identifier = normalizeEventIdentifier(registration, input.identifier);
4054
+ const resourceTypes = registration?.resourceTypes ?? [];
4055
+ const fits = (resourceType) => resourceType.identifier !== void 0 && new RegExp(resourceType.identifier.pattern).test(identifier);
4056
+ const resourceType = resourceTypes.find((candidate) => candidate.type === input.resourceType);
4057
+ if (!resourceType?.identifier || fits(resourceType)) return identifier;
4058
+ const fitting = resourceTypes.filter(fits).map((candidate) => candidate.type);
4059
+ throw new ToolInputError([`Identifier "${identifier}" does not fit resource_type "${input.resourceType}" in namespace "${input.namespace}". Expected format: "${resourceType.identifier.format}".`, ...fitting.length > 0 ? [`If the identifier is correct, use one of these resource_type values: ${fitting.map((type) => `"${type}"`).join(", ")}.`] : []].join(" "));
4060
+ }
4061
+ // src/chat/events/actor.ts
4062
+ /**
4063
+ * System author ID stamped on event mailbox messages.
4064
+ *
4065
+ * Keep this stable so conversation history can recognize the same system input
4066
+ * for event Turns.
4067
+ *
4068
+ * TODO(dcramer): Delete this ID after resumes read event Source.kind
4069
+ * from the Turn checkpoint instead of Message author data.
4070
+ */
4071
+ const EVENT_AUTHOR_ID = "UJRNEVENT";
4072
+ /** System Message author for event input. */
4073
+ const EVENT_MESSAGE_AUTHOR = {
4074
+ fullName: "System event",
4075
+ isBot: true,
4076
+ userId: EVENT_AUTHOR_ID,
4077
+ userName: "junior-event"
4078
+ };
4079
+ /** System execution actor for every event turn. */
4080
+ const EVENT_SYSTEM_ACTOR = {
4081
+ platform: "system",
4082
+ name: "event"
4083
+ };
4084
+ /**
4085
+ * Whether a saved Message started a event Turn.
4086
+ *
4087
+ * TODO(dcramer): Delete this marker check after deployed Turn cursors all store
4088
+ * Source and Actor. `eventType` only supports saved synthetic Slack input.
4089
+ */
4090
+ function isEventConversationMessage(message) {
4091
+ return Boolean(message.meta?.eventType) || isEventAuthorId(message.author?.userId);
4092
+ }
4093
+ /** Author id of an Event Message by a listed bot, which has no Identity. */
4094
+ function eventBotAuthorId(provider, handle) {
4095
+ return `${EVENT_AUTHOR_ID}:${provider}:${handle.toLowerCase()}`;
4096
+ }
4097
+ /** Whether an author id belongs to an Event Message, system or listed bot. */
4098
+ function isEventAuthorId(id) {
4099
+ return id === "UJRNEVENT" || Boolean(id?.startsWith(`UJRNEVENT:`));
2929
4100
  }
2930
4101
  // src/chat/conversations/kind-behavior.ts
2931
4102
  const ROOT = {
@@ -3114,12 +4285,13 @@ function hasConversationMetadata(kind) {
3114
4285
  return kind !== "task";
3115
4286
  }
3116
4287
  /**
3117
- * Return whether a person can put a Conversation in a Space: a top-level
3118
- * `thread`. A child agent is in the Space of its tree, and a Lead, an
3119
- * Automation run, or a Task never moves.
4288
+ * Return whether a person can put a Conversation in a Space: a `thread` that
4289
+ * is a root or a Lead's child. A deeper child agent is in the Space of its
4290
+ * tree, and a Lead, an Automation run, or a Task never moves.
3120
4291
  */
3121
4292
  function canMoveToSpace(conversation) {
3122
- return conversation.kind === "thread" && isTopLevelWork(conversation);
4293
+ if (conversation.kind !== "thread") return false;
4294
+ return isTopLevel(conversation) || conversation.spaceId !== void 0 && conversation.parentConversationId === conversation.rootConversationId;
3123
4295
  }
3124
4296
  /**
3125
4297
  * Return whether a Conversation copies its root's visibility: it has a
@@ -3129,21 +4301,6 @@ function copiesRootVisibility(conversation) {
3129
4301
  return !isTopLevel(conversation);
3130
4302
  }
3131
4303
  /**
3132
- * Return whether a parent of this kind has a cap on its active child agents.
3133
- * A Lead's children are its Space's Conversations, so a Lead has none.
3134
- */
3135
- function capsActiveChildren(kind) {
3136
- return kind !== "lead";
3137
- }
3138
- /**
3139
- * Return whether the children of a parent of this kind are top-level work:
3140
- * a Lead's children are its Space's Conversations. They count as roots for
3141
- * `limits.maxAgentDepth`, and each gets its own Destination.
3142
- */
3143
- function childrenAreTopLevel(kind) {
3144
- return kind === "lead";
3145
- }
3146
- /**
3147
4304
  * Return whether a parent of this kind gets a reminder with a child's status
3148
4305
  * update that it can end the Turn with no reply. A Lead's members read each
3149
4306
  * reply that it posts.
@@ -3156,28 +4313,12 @@ function storesSpace(kind) {
3156
4313
  return kind === "lead";
3157
4314
  }
3158
4315
  /**
3159
- * Return whether a Conversation is top-level work: it has no parent, or it
3160
- * is a Lead's child. Top-level lists show it, and its child
3161
- * agents move with it.
3162
- */
3163
- function isTopLevelWork(conversation) {
3164
- return isTopLevel(conversation) || conversation.spaceId !== void 0 && conversation.parentConversationId === conversation.rootConversationId;
3165
- }
3166
- /**
3167
- * Return whether a Conversation delivers to its Location: it has no parent,
3168
- * or its Location is its own, such as a Slack Conversation in a Space.
3169
- */
3170
- function ownsLocation(conversation) {
3171
- return isTopLevel(conversation) || conversation.ownLocation === true;
3172
- }
3173
- /**
3174
- * Return whether a write may keep a stored parent that is not its own. A
3175
- * move into, out of, or between Spaces changes the parent only between no
3176
- * parent and a Lead, so a write from before the move keeps the stored one.
4316
+ * Return whether a write keeps the stored parent: only when it names the
4317
+ * same one. A move into or out of a Space changes the parent under the
4318
+ * Conversation's lock, so no write from before the move reaches the row.
3177
4319
  */
3178
4320
  function keepsStoredParent(stored, incoming) {
3179
- if (stored.id === (incoming.id ?? null)) return true;
3180
- return (!stored.id || stored.isLead) && (!incoming.id || incoming.isLead);
4321
+ return stored === (incoming ?? null);
3181
4322
  }
3182
4323
  /** Return whether a Conversation has no parent. */
3183
4324
  function isTopLevel(conversation) {
@@ -3211,6 +4352,17 @@ function watcherStartedConversation(target, watcherConversationId) {
3211
4352
  function isPersonInput(source) {
3212
4353
  return source === "web" || source === "slack";
3213
4354
  }
4355
+ /**
4356
+ * Return the Actor that a child Turn's update carries to its parent, whose
4357
+ * Turn for it runs as that Actor. Only a Turn that agent work started, a
4358
+ * parent message or an Event such as a child result, keeps its Actor. Any
4359
+ * other Turn, such as a person's Turn in a Thread or a saved Turn with no
4360
+ * Source, reports as the Event system Actor, so the parent never gets a
4361
+ * person's access.
4362
+ */
4363
+ function parentResultActor(actor, source) {
4364
+ return source === "parent_message" || source === "event" ? actor : EVENT_SYSTEM_ACTOR;
4365
+ }
3214
4366
  /** Narrow a Source to one that a person sent input from. */
3215
4367
  function isPersonSource(source) {
3216
4368
  return isPersonInput(source.kind);
@@ -3231,6 +4383,24 @@ function personSourcePlatform(source) {
3231
4383
  case "parent_message": return;
3232
4384
  }
3233
4385
  }
4386
+ /**
4387
+ * Return who wrote the current instruction of a Run from this Source:
4388
+ * a person, an Automation's stored instruction, an agent's brief, or an
4389
+ * Event. A parent agent's task and another top-level agent's message are
4390
+ * briefs.
4391
+ */
4392
+ function instructionAuthor(source) {
4393
+ switch (source.kind) {
4394
+ case "slack":
4395
+ case "local":
4396
+ case "web": return "person";
4397
+ case "scheduled_automation":
4398
+ case "event_automation": return "automation";
4399
+ case "parent_message": return "brief";
4400
+ case "event": return source.namespace === "junior" && source.eventType === "agent.top_level_message" ? "brief" : "event";
4401
+ case "plugin_dispatch": return "event";
4402
+ }
4403
+ }
3234
4404
  /** Return a short label that names a Source, such as `slack:T1:C1`. */
3235
4405
  function sourceLabel(source) {
3236
4406
  switch (source.kind) {
@@ -6882,14 +8052,11 @@ function createMemoryUserPage() {
6882
8052
  };
6883
8053
  }
6884
8054
  // src/chat/memory/registration.ts
6885
- const MEMORY_MODEL_ENV = "AI_MEMORY_MODEL";
6886
8055
  const HEARTBEAT_REEMBED_BATCH_SIZE = 100;
6887
8056
  const HEARTBEAT_REEMBED_BUDGET_MS = 15e3;
6888
8057
  const HEARTBEAT_EXPIRED_ARCHIVE_LIMIT = 100;
6889
8058
  function memoryModelId(options) {
6890
- const explicitModelId = options.modelId?.trim();
6891
- if (explicitModelId) return explicitModelId;
6892
- return process.env[MEMORY_MODEL_ENV]?.trim() || void 0;
8059
+ return options.modelId?.trim() || void 0;
6893
8060
  }
6894
8061
  function memoryToolContext(ctx) {
6895
8062
  const agent = createMemoryAgent(ctx.model);
@@ -6996,18 +8163,9 @@ function createMemoryRegistration(options = {}) {
6996
8163
  }
6997
8164
  });
6998
8165
  }
6999
- let configuredOptions = {};
7000
- let registration = createMemoryRegistration();
7001
- /** Replace the app's Memory settings and return the previous settings. */
7002
- function setMemoryConfig(options = {}) {
7003
- const previous = configuredOptions;
7004
- configuredOptions = { ...options };
7005
- registration = createMemoryRegistration(configuredOptions);
7006
- return previous;
7007
- }
7008
8166
  /** Return the Memory registration for the current app settings. */
7009
8167
  function memoryRegistration() {
7010
- return registration;
8168
+ return createMemoryRegistration(getChatConfig().memory);
7011
8169
  }
7012
8170
  // src/chat/conversations/message-projection.ts
7013
8171
  function isMessageEvent(event) {
@@ -7074,7 +8232,10 @@ function projectConversationMessages(history) {
7074
8232
  });
7075
8233
  }
7076
8234
  // src/chat/dashboard-link.ts
7077
- let dashboardConversationLinkOptions;
8235
+ function dashboardLinkOptions() {
8236
+ const options = getChatConfig().dashboard;
8237
+ return options?.disabled ? void 0 : options;
8238
+ }
7078
8239
  function withHttps(host) {
7079
8240
  return host.startsWith("https://") || host.startsWith("http://") ? host : `https://${host}`;
7080
8241
  }
@@ -7091,16 +8252,11 @@ function resolveDashboardBaseURL(config) {
7091
8252
  const baseUrl = config.baseURL?.trim() || getChatConfig().deployment.baseUrl;
7092
8253
  return baseUrl ? stripTrailingSlashes(withHttps(baseUrl)) : "http://localhost:3000";
7093
8254
  }
7094
- /** Configure core dashboard links. */
7095
- function setDashboardConversationLinkOptions(options) {
7096
- const previous = dashboardConversationLinkOptions;
7097
- dashboardConversationLinkOptions = options?.disabled ? void 0 : options;
7098
- return previous;
7099
- }
7100
8255
  function resolveDashboardPath(segmentPath) {
7101
- if (!dashboardConversationLinkOptions) return;
7102
- const baseURL = resolveDashboardBaseURL(dashboardConversationLinkOptions);
7103
- const basePath = normalizeDashboardPath(dashboardConversationLinkOptions.basePath, "/");
8256
+ const options = dashboardLinkOptions();
8257
+ if (!options) return;
8258
+ const baseURL = resolveDashboardBaseURL(options);
8259
+ const basePath = normalizeDashboardPath(options.basePath, "/");
7104
8260
  return `${baseURL}${basePath === "/" ? segmentPath : `${basePath}${segmentPath}`}`;
7105
8261
  }
7106
8262
  /** Build the dashboard conversation URL when the core dashboard is enabled. */
@@ -7175,164 +8331,20 @@ function getDashboardTaskLink(taskId) {
7175
8331
  function getDashboardInboxItemLink(itemId) {
7176
8332
  return resolveDashboardPath(`/inbox?item=${encodeURIComponent(itemId)}`);
7177
8333
  }
7178
- /**
7179
- * Build the dashboard URL that opens the snooze form of one Inbox item. A
7180
- * chat card links it, since a message there looks the same to everyone.
7181
- */
7182
- function getDashboardInboxItemSnoozeLink(itemId) {
7183
- return resolveDashboardPath(`/inbox?item=${encodeURIComponent(itemId)}&snooze=1`);
7184
- }
7185
- /** Public icon asset URL. Headless and local installs keep text-only identity. */
7186
- function getDashboardObjectIconLink(icon) {
7187
- if (!dashboardConversationLinkOptions) return void 0;
7188
- const url = new URL(objectIconPath(icon), resolveDashboardBaseURL(dashboardConversationLinkOptions));
7189
- if (url.protocol !== "https:" || url.hostname === "localhost") return void 0;
7190
- return url.href;
7191
- }
7192
- // src/chat/tool-support/tool-input-error.ts
7193
- /** Thrown when a tool fails due to invalid model/user input, not a system error. */
7194
- var ToolInputError = class extends Error {
7195
- constructor(message, options) {
7196
- super(message, options);
7197
- this.name = "ToolInputError";
7198
- }
7199
- };
7200
- /** Whether an error is an expected tool input failure that is not a Sentry exception. */
7201
- function isToolInputError(error) {
7202
- return error instanceof ToolInputError || error instanceof PluginToolInputError || error instanceof Error && error.name === "PluginToolInputError";
7203
- }
7204
- // src/chat/events/catalog.ts
7205
- /** A source with nothing enabled, for a namespace that the catalog lacks. */
7206
- const NO_SOURCE = {
7207
- resourceTypes: [],
7208
- events: {},
7209
- anyResourceFields: {}
7210
- };
7211
- /**
7212
- * Build one catalog entry. It merges the filters of every resource type here,
7213
- * once, so trigger checks for each event copy and each row do not merge them
7214
- * again.
7215
- */
7216
- function eventCatalogEntry(registration) {
7217
- return {
7218
- ...registration,
7219
- anyResourceFields: anyResourceMatchFields(registration.resourceTypes)
7220
- };
7221
- }
7222
- /** Core-owned event namespace. Not a plugin publisher. */
7223
- const CORE_EVENT_NAMESPACE = "junior";
7224
- /** True when the catalog has any enabled registration. */
7225
- function hasEventCatalogEntries(catalog) {
7226
- return Object.keys(catalog).length > 0;
7227
- }
7228
- /**
7229
- * Catalog entries that durable event automations may select.
7230
- *
7231
- * Resource types with `automation: false` stay out of create/update schemas
7232
- * and trigger availability. A namespace with no such resource type left is
7233
- * removed.
7234
- */
7235
- function automationEventCatalog(catalog) {
7236
- return Object.fromEntries(Object.entries(catalog).flatMap(([namespace, registration]) => {
7237
- const resourceTypes = registration.resourceTypes.filter((resourceType) => registration.limits?.[resourceType.type]?.automation !== false);
7238
- if (resourceTypes.length === 0) return [];
7239
- if (resourceTypes.length === registration.resourceTypes.length) return [[namespace, registration]];
7240
- const supported = new Set(resourceTypes.flatMap((resourceType) => resourceType.supportedEvents));
7241
- return [[namespace, eventCatalogEntry({
7242
- ...registration,
7243
- resourceTypes,
7244
- events: Object.fromEntries(Object.entries(registration.events).filter(([eventType]) => supported.has(eventType)))
7245
- })]];
7246
- }));
7247
- }
7248
- /** Return why watchEvents cannot watch one resource type, if it cannot. */
7249
- function eventWatchUnavailable(catalog, namespace, resourceType) {
7250
- const limits = catalog[namespace]?.limits?.[resourceType];
7251
- return limits?.watch === false ? limits.watchUnavailableMessage : void 0;
7252
- }
7253
- function enumSchema(values, unavailableMessage) {
7254
- if (values.length === 0) return z.string().refine(() => false, unavailableMessage);
7255
- return z.enum(values);
7256
- }
7257
- /** Build the model-facing namespace enum from enabled event plugins. */
7258
- function eventNamespaceSchema(catalog) {
7259
- return enumSchema(Object.keys(catalog).sort(), "No event namespaces are enabled.");
7260
- }
7261
- /** Build the model-facing event enum from enabled plugin registrations. */
7262
- function registeredEventTypeSchema(catalog) {
7263
- return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.flatMap((resourceType) => resourceType.supportedEvents)))].sort(), "No event types are enabled.");
7264
- }
7265
- /** Build the model-facing resource type enum from enabled plugin registrations. */
7266
- function registeredResourceTypeSchema(catalog) {
7267
- return enumSchema([...new Set(Object.values(catalog).flatMap((registration) => registration.resourceTypes.map((resourceType) => resourceType.type)))].sort(), "No resource types are enabled.");
7268
- }
7269
- /**
7270
- * Return app guidance for one event of a namespace. The source declares it
7271
- * once for the event, so every resource type and a trigger with no resource
7272
- * type get the same guidance.
7273
- */
7274
- function eventGuidance(catalog, namespace, eventType) {
7275
- return catalog[namespace]?.events[eventType]?.guidance;
7276
- }
7277
- /** Build the match object the tools accept for one resource type. */
7278
- function registeredEventMatchSchema() {
7279
- return agentEventMatchSchema.optional().describe("Optional filters: exact values for the resource type match_fields, with snake_case keys. A single value must equal the event data. A list means the event value may be any one entry. For a field with list: true, the event value is a list, and it matches when it includes the value or any entry. A field with events is set only on those events, so every selected event must be in that list. Omit a key to ignore it. Unmatched events are dropped with no agent turn.");
7280
- }
7281
- /**
7282
- * List why a selection cannot work with the enabled plugins. Use it for new
7283
- * selections and for saved triggers, which can go stale after a plugin renames
7284
- * or removes a resource type, event, or filter.
7285
- */
7286
- function registeredEventTriggerProblems(catalog, selection, options) {
7287
- return eventTriggerProblems(catalog[selection.namespace] ?? NO_SOURCE, selection, options);
7288
- }
7289
- /**
7290
- * Describe a selection with the enabled plugins, for the dashboard and Slack.
7291
- * Its problems are the same as `registeredEventTriggerProblems`.
7292
- */
7293
- function describeRegisteredEventTrigger(catalog, selection) {
7294
- return describeEventTrigger(catalog[selection.namespace] ?? NO_SOURCE, selection);
7295
- }
7296
- function uniqueMatchValues(match) {
7297
- if (!match || Object.keys(match).length === 0) return void 0;
7298
- return Object.fromEntries(Object.entries(match).map(([key, value]) => [key, Array.isArray(value) ? [...new Set(value)] : value]));
7299
- }
7300
- /**
7301
- * Reject an event automation trigger or a Watch that cannot work, with every
7302
- * problem in one message for the agent. Return its match as it is saved:
7303
- * each text value in the case that its plugin declares, with no repeated
7304
- * list values. The dashboard clears `inputKeys` so messages name the filters
7305
- * as its plugin declares them.
7306
- */
7307
- function requireValidEventTrigger(catalog, selection, target, options = { inputKeys: true }) {
7308
- const fields = eventTriggerChoices(catalog[selection.namespace] ?? NO_SOURCE, selection)?.fields ?? {};
7309
- const normalized = {
7310
- ...selection,
7311
- match: normalizeEventMatch(fields, selection.match)
7312
- };
7313
- const problems = registeredEventTriggerProblems(catalog, normalized, options);
7314
- if (problems.length > 0) {
7315
- const source = catalog[selection.namespace]?.displayName ?? selection.namespace;
7316
- const resource = selection.resourceType ? `${source} ${selection.resourceType.replaceAll("_", " ")}` : source;
7317
- throw new ToolInputError([target === "watch" ? `This ${resource} watch cannot be created.` : `This ${resource} trigger cannot be saved.`, ...problems.map((problem) => problem.message)].join(" "));
7318
- }
7319
- return uniqueMatchValues(normalized.match);
7320
- }
7321
- /**
7322
- * Normalize one selector with the convention declared by its plugin.
7323
- *
7324
- * Reject a selector that does not fit its resource type. Resource types can
7325
- * share event types, so only the identifier shows which one a selector names.
8334
+ /**
8335
+ * Build the dashboard URL that opens the snooze form of one Inbox item. A
8336
+ * chat card links it, since a message there looks the same to everyone.
7326
8337
  */
7327
- function requireEventIdentifier(catalog, input) {
7328
- const registration = catalog[input.namespace];
7329
- const identifier = normalizeEventIdentifier(registration, input.identifier);
7330
- const resourceTypes = registration?.resourceTypes ?? [];
7331
- const fits = (resourceType) => resourceType.identifier !== void 0 && new RegExp(resourceType.identifier.pattern).test(identifier);
7332
- const resourceType = resourceTypes.find((candidate) => candidate.type === input.resourceType);
7333
- if (!resourceType?.identifier || fits(resourceType)) return identifier;
7334
- const fitting = resourceTypes.filter(fits).map((candidate) => candidate.type);
7335
- throw new ToolInputError([`Identifier "${identifier}" does not fit resource_type "${input.resourceType}" in namespace "${input.namespace}". Expected format: "${resourceType.identifier.format}".`, ...fitting.length > 0 ? [`If the identifier is correct, use one of these resource_type values: ${fitting.map((type) => `"${type}"`).join(", ")}.`] : []].join(" "));
8338
+ function getDashboardInboxItemSnoozeLink(itemId) {
8339
+ return resolveDashboardPath(`/inbox?item=${encodeURIComponent(itemId)}&snooze=1`);
8340
+ }
8341
+ /** Public icon asset URL. Headless and local installs keep text-only identity. */
8342
+ function getDashboardObjectIconLink(icon) {
8343
+ const options = dashboardLinkOptions();
8344
+ if (!options) return void 0;
8345
+ const url = new URL(objectIconPath(icon), resolveDashboardBaseURL(options));
8346
+ if (url.protocol !== "https:" || url.hostname === "localhost") return void 0;
8347
+ return url.href;
7336
8348
  }
7337
8349
  // src/chat/inbox-items/deliveries.ts
7338
8350
  /** Keep at most this many closed items in one push. */
@@ -9608,151 +10620,6 @@ async function saveNotificationSchedule(db, userId, schedule, nowMs) {
9608
10620
  updatedAt: new Date(nowMs)
9609
10621
  }).where(eq(juniorUsers.id, userId)).returning({ id: juniorUsers.id })).length > 0;
9610
10622
  }
9611
- // src/chat/actor.ts
9612
- /**
9613
- * Canonical actor identity.
9614
- *
9615
- * Runtime actors are platform-scoped actors. Stored Slack actor parsing
9616
- * remains explicit so durable conversation metadata is not repaired on read.
9617
- */
9618
- const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
9619
- const EMAIL_PATTERN = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
9620
- const exactStoredStringSchema = z.string().min(1).refine((value) => value === value.trim());
9621
- const storedSlackActorSchema = z.object({
9622
- email: exactStoredStringSchema.optional(),
9623
- fullName: exactStoredStringSchema.optional(),
9624
- platform: z.literal("slack").optional(),
9625
- slackUserId: exactStoredStringSchema.optional(),
9626
- slackUserName: exactStoredStringSchema.optional(),
9627
- teamId: exactStoredStringSchema.optional()
9628
- }).strict();
9629
- /** Return whether an actor is a platform-scoped user actor. */
9630
- function isUserActor(actor) {
9631
- return Boolean(actor && "userId" in actor);
9632
- }
9633
- function clean(value) {
9634
- const trimmed = value?.trim();
9635
- return trimmed ? trimmed : void 0;
9636
- }
9637
- function isSyntheticActorUserId(value) {
9638
- return value.toLowerCase() === "unknown";
9639
- }
9640
- /** Return whether a value has the shape of a Slack user id. */
9641
- function isSlackUserId(value) {
9642
- return SLACK_USER_ID_DISPLAY_PATTERN.test(value);
9643
- }
9644
- function cleanActorDisplayName(value, userId) {
9645
- const displayName = clean(value);
9646
- if (!displayName) return;
9647
- if (displayName.toLowerCase() === "unknown") return;
9648
- if (userId && displayName === userId) return;
9649
- return isSlackUserId(displayName) ? void 0 : displayName;
9650
- }
9651
- function cleanActorEmail(value) {
9652
- const email = clean(value);
9653
- return email && EMAIL_PATTERN.test(email) ? email : void 0;
9654
- }
9655
- /** Keep actor ids exact at platform boundaries before they enter owned state. */
9656
- function parseActorUserId(value) {
9657
- if (typeof value !== "string" || value.length === 0) return;
9658
- if (value !== value.trim() || isSyntheticActorUserId(value)) return;
9659
- return value;
9660
- }
9661
- /** Assert persisted actor ids without read-side repair. */
9662
- function isActorUserId(value) {
9663
- return parseActorUserId(value) === value;
9664
- }
9665
- /** Build Junior's canonical platform actor from exact actor ids and profile data. */
9666
- function createActor(input, context) {
9667
- const platform = context.platform ?? input?.platform;
9668
- if (!platform) return;
9669
- const contextUserId = parseActorUserId(context.userId);
9670
- if (context.userId !== void 0 && !contextUserId) return;
9671
- const inputUserId = parseActorUserId(input?.userId);
9672
- if (input?.userId !== void 0 && !inputUserId) return;
9673
- const actorUserId = contextUserId ?? inputUserId;
9674
- if (!actorUserId) return;
9675
- const contextTeamId = parseSlackTeamId(context.teamId);
9676
- if (context.teamId !== void 0 && !contextTeamId) return;
9677
- const inputTeamId = parseSlackTeamId(input?.teamId);
9678
- if (input?.teamId !== void 0 && !inputTeamId) return;
9679
- const actorTeamId = contextTeamId ?? inputTeamId;
9680
- if (platform === "slack" && !actorTeamId) return;
9681
- const canUseInputProfile = (!contextUserId || !inputUserId || contextUserId === inputUserId) && (platform !== "slack" || !contextTeamId || !inputTeamId || contextTeamId === inputTeamId);
9682
- const actor = {
9683
- ...canUseInputProfile && cleanActorEmail(input?.email) ? { email: cleanActorEmail(input?.email) } : void 0,
9684
- ...canUseInputProfile && cleanActorDisplayName(input?.fullName, actorUserId) ? { fullName: cleanActorDisplayName(input?.fullName, actorUserId) } : void 0,
9685
- platform,
9686
- userId: actorUserId,
9687
- ...canUseInputProfile && cleanActorDisplayName(input?.userName, actorUserId) ? { userName: cleanActorDisplayName(input?.userName, actorUserId) } : void 0
9688
- };
9689
- if (platform === "slack") return {
9690
- ...actor,
9691
- platform,
9692
- teamId: actorTeamId
9693
- };
9694
- return {
9695
- ...actor,
9696
- platform
9697
- };
9698
- }
9699
- /** Build Junior's canonical actor from Slack profile data. */
9700
- function createSlackActor(teamId, userId, profile) {
9701
- const actorUserId = parseActorUserId(userId);
9702
- const actorTeamId = parseSlackTeamId(teamId);
9703
- if (!actorTeamId || !actorUserId) throw new Error("Slack actor requires team and user ids");
9704
- const actor = createActor({
9705
- email: profile?.email,
9706
- fullName: profile?.fullName,
9707
- platform: "slack",
9708
- teamId: actorTeamId,
9709
- userId: actorUserId,
9710
- userName: profile?.userName
9711
- }, {
9712
- teamId: actorTeamId,
9713
- userId: actorUserId
9714
- });
9715
- if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
9716
- return actor;
9717
- }
9718
- /** Parse a serialized Slack actor that crossed a runtime boundary. */
9719
- function parseStoredSlackActor(value) {
9720
- const parsed = storedSlackActorSchema.safeParse(value);
9721
- if (!parsed.success) return;
9722
- if (parsed.data.slackUserId !== void 0 && !parseActorUserId(parsed.data.slackUserId)) return;
9723
- if (parsed.data.teamId !== void 0 && !parseSlackTeamId(parsed.data.teamId)) return;
9724
- if ((parsed.data.platform !== void 0 || parsed.data.teamId !== void 0) && (!parsed.data.platform || !parsed.data.teamId)) return;
9725
- return parsed.data;
9726
- }
9727
- /** Convert a runtime Slack actor into its durable session shape. */
9728
- function toStoredSlackActor(actor) {
9729
- return {
9730
- ...actor.email ? { email: actor.email } : void 0,
9731
- ...actor.fullName ? { fullName: actor.fullName } : void 0,
9732
- platform: actor.platform,
9733
- slackUserId: actor.userId,
9734
- ...actor.userName ? { slackUserName: actor.userName } : void 0,
9735
- teamId: actor.teamId
9736
- };
9737
- }
9738
- /**
9739
- * Resolve a Slack resume actor from stored profile data and the active actor.
9740
- *
9741
- * TODO(dcramer): Require Actor and remove ID-only construction after no
9742
- * deployed Turn cursor can omit Actor.
9743
- */
9744
- function createSlackResumeActor(args) {
9745
- if (args.actor) {
9746
- if (args.actor.platform !== "slack" || args.actor.teamId !== args.teamId || args.actor.userId !== args.userId) throw new Error("Stored Slack actor did not match resume actor");
9747
- }
9748
- const actor = createActor(args.actor, {
9749
- platform: "slack",
9750
- teamId: args.teamId,
9751
- userId: args.userId
9752
- });
9753
- if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
9754
- return actor;
9755
- }
9756
10623
  // src/chat/slack/user.ts
9757
10624
  const slackUserInfoSchema = z.object({
9758
10625
  ok: z.literal(true),
@@ -9875,10 +10742,9 @@ async function lookupSlackUserNames(teamId, userIds) {
9875
10742
  return names;
9876
10743
  }
9877
10744
  // src/chat/identities/timezone.ts
9878
- const DEFAULT_TIMEZONE = "America/Los_Angeles";
9879
10745
  /** The install timezone, used when Junior does not know a person's timezone. */
9880
10746
  function defaultTimezone() {
9881
- return process.env["JUNIOR_TIMEZONE"]?.trim() || DEFAULT_TIMEZONE;
10747
+ return getChatConfig().deployment.timezone;
9882
10748
  }
9883
10749
  /**
9884
10750
  * Find a person's timezone: their Slack profile, then the saved user
@@ -10208,80 +11074,6 @@ const notificationsTaskRegistration = {
10208
11074
  await notifyReply(context);
10209
11075
  } } }
10210
11076
  };
10211
- // src/chat/conversations/sql/subtree.ts
10212
- /** Columns of the `conversation_subtree` table that `conversationSubtree` returns. */
10213
- const conversationSubtreeColumns = {
10214
- conversationId: sql`conversation_subtree.conversation_id`,
10215
- scopeConversationId: sql`conversation_subtree.scope_conversation_id`
10216
- };
10217
- /**
10218
- * Return a joinable `conversation_subtree` table. It maps each selected
10219
- * Conversation to itself and to each descendant child Conversation at any
10220
- * depth. Reports use it so that a total for a Conversation always includes the
10221
- * work of all its child agents.
10222
- *
10223
- * A descendant must have the same root as the selected Conversation. Thus a
10224
- * Conversation that has no valid root gets only its own work. A selected root
10225
- * gets every Conversation that stores it as their root.
10226
- */
10227
- function conversationSubtree(conversationIds) {
10228
- const selectedIds = sql.join(conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
10229
- return sql`(
10230
- with recursive tree_member as materialized (
10231
- select member.conversation_id, member.parent_conversation_id, member.root_conversation_id
10232
- from junior_conversations member
10233
- where member.root_conversation_id in (
10234
- select selected.root_conversation_id
10235
- from junior_conversations selected
10236
- where selected.conversation_id in (${selectedIds})
10237
- and selected.root_conversation_id is distinct from selected.conversation_id
10238
- )
10239
- ),
10240
- walk(scope_conversation_id, conversation_id, root_conversation_id) as (
10241
- select selected.conversation_id, selected.conversation_id, selected.root_conversation_id
10242
- from junior_conversations selected
10243
- where selected.conversation_id in (${selectedIds})
10244
- and selected.root_conversation_id is distinct from selected.conversation_id
10245
- union
10246
- select walk.scope_conversation_id, child.conversation_id, child.root_conversation_id
10247
- from tree_member child
10248
- join walk
10249
- on child.parent_conversation_id = walk.conversation_id
10250
- and child.root_conversation_id = walk.root_conversation_id
10251
- )
10252
- select selected.conversation_id as scope_conversation_id, selected.conversation_id
10253
- from junior_conversations selected
10254
- where selected.conversation_id in (${selectedIds})
10255
- union
10256
- select selected.conversation_id, member.conversation_id
10257
- from junior_conversations selected
10258
- join junior_conversations member
10259
- on member.root_conversation_id = selected.conversation_id
10260
- where selected.conversation_id in (${selectedIds})
10261
- and selected.root_conversation_id = selected.conversation_id
10262
- union
10263
- select scope_conversation_id, conversation_id from walk
10264
- ) conversation_subtree`;
10265
- }
10266
- /**
10267
- * Return a subquery of the given Conversations and each of their ancestors.
10268
- * A list filter keeps the row that matches its own rules, so a match deep
10269
- * in a tree finds its top-level Conversation, such as a Lead's child.
10270
- */
10271
- function conversationAncestorsOrSelf(selectedIds) {
10272
- return sql`(
10273
- with recursive ancestor(conversation_id, parent_conversation_id) as (
10274
- select selected.conversation_id, selected.parent_conversation_id
10275
- from junior_conversations selected
10276
- where selected.conversation_id in (${selectedIds})
10277
- union
10278
- select parent.conversation_id, parent.parent_conversation_id
10279
- from junior_conversations parent
10280
- join ancestor on parent.conversation_id = ancestor.parent_conversation_id
10281
- )
10282
- select conversation_id from ancestor
10283
- )`;
10284
- }
10285
11077
  // src/chat/conversations/sql/privacy.ts
10286
11078
  const privacyRoot = alias(juniorConversations, "privacy_root");
10287
11079
  /** Accept only a structurally valid persisted root as privacy authority. */
@@ -10330,17 +11122,6 @@ function isPublicConversation(table) {
10330
11122
  return eq(table.visibility, "public");
10331
11123
  }
10332
11124
  /**
10333
- * Set the visibility of one Conversation and its child agents, when they
10334
- * move into a private Space's tree. The caller moves them in the same
10335
- * transaction, so the whole tree keeps one value.
10336
- */
10337
- async function setMovedWorkVisibility(executor, conversationId, visibility) {
10338
- await executor.db().update(juniorConversations).set({
10339
- visibility,
10340
- detailVersion: nextDetailVersion
10341
- }).where(inArray(juniorConversations.conversationId, sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`));
10342
- }
10343
- /**
10344
11125
  * Give the rows of a tree that have no visibility yet the root's value,
10345
11126
  * once the root first gets one. Rows that have a value keep it.
10346
11127
  */
@@ -10402,6 +11183,80 @@ async function writeConversationMetadata(db, input) {
10402
11183
  }).where(and(eq(juniorConversations.conversationId, input.conversationId), or(isNull(juniorConversations.metadataThroughSeq), lt(juniorConversations.metadataThroughSeq, input.throughSeq)))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
10403
11184
  });
10404
11185
  }
11186
+ // src/chat/conversations/sql/subtree.ts
11187
+ /** Columns of the `conversation_subtree` table that `conversationSubtree` returns. */
11188
+ const conversationSubtreeColumns = {
11189
+ conversationId: sql`conversation_subtree.conversation_id`,
11190
+ scopeConversationId: sql`conversation_subtree.scope_conversation_id`
11191
+ };
11192
+ /**
11193
+ * Return a joinable `conversation_subtree` table. It maps each selected
11194
+ * Conversation to itself and to each descendant child Conversation at any
11195
+ * depth. Reports use it so that a total for a Conversation always includes the
11196
+ * work of all its child agents.
11197
+ *
11198
+ * A descendant must have the same root as the selected Conversation. Thus a
11199
+ * Conversation that has no valid root gets only its own work. A selected root
11200
+ * gets every Conversation that stores it as their root.
11201
+ */
11202
+ function conversationSubtree(conversationIds) {
11203
+ const selectedIds = sql.join(conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
11204
+ return sql`(
11205
+ with recursive tree_member as materialized (
11206
+ select member.conversation_id, member.parent_conversation_id, member.root_conversation_id
11207
+ from junior_conversations member
11208
+ where member.root_conversation_id in (
11209
+ select selected.root_conversation_id
11210
+ from junior_conversations selected
11211
+ where selected.conversation_id in (${selectedIds})
11212
+ and selected.root_conversation_id is distinct from selected.conversation_id
11213
+ )
11214
+ ),
11215
+ walk(scope_conversation_id, conversation_id, root_conversation_id) as (
11216
+ select selected.conversation_id, selected.conversation_id, selected.root_conversation_id
11217
+ from junior_conversations selected
11218
+ where selected.conversation_id in (${selectedIds})
11219
+ and selected.root_conversation_id is distinct from selected.conversation_id
11220
+ union
11221
+ select walk.scope_conversation_id, child.conversation_id, child.root_conversation_id
11222
+ from tree_member child
11223
+ join walk
11224
+ on child.parent_conversation_id = walk.conversation_id
11225
+ and child.root_conversation_id = walk.root_conversation_id
11226
+ )
11227
+ select selected.conversation_id as scope_conversation_id, selected.conversation_id
11228
+ from junior_conversations selected
11229
+ where selected.conversation_id in (${selectedIds})
11230
+ union
11231
+ select selected.conversation_id, member.conversation_id
11232
+ from junior_conversations selected
11233
+ join junior_conversations member
11234
+ on member.root_conversation_id = selected.conversation_id
11235
+ where selected.conversation_id in (${selectedIds})
11236
+ and selected.root_conversation_id = selected.conversation_id
11237
+ union
11238
+ select scope_conversation_id, conversation_id from walk
11239
+ ) conversation_subtree`;
11240
+ }
11241
+ /**
11242
+ * Return a subquery of the given Conversations and each of their ancestors.
11243
+ * A list filter keeps the row that matches its own rules, so a match deep
11244
+ * in a tree finds its top-level Conversation, such as a Lead's child.
11245
+ */
11246
+ function conversationAncestorsOrSelf(selectedIds) {
11247
+ return sql`(
11248
+ with recursive ancestor(conversation_id, parent_conversation_id) as (
11249
+ select selected.conversation_id, selected.parent_conversation_id
11250
+ from junior_conversations selected
11251
+ where selected.conversation_id in (${selectedIds})
11252
+ union
11253
+ select parent.conversation_id, parent.parent_conversation_id
11254
+ from junior_conversations parent
11255
+ join ancestor on parent.conversation_id = ancestor.parent_conversation_id
11256
+ )
11257
+ select conversation_id from ancestor
11258
+ )`;
11259
+ }
10405
11260
  // src/chat/plugins/annotations.ts
10406
11261
  function annotationFromRow(row) {
10407
11262
  const parsed = conversationAnnotationInputSchema.safeParse(row.annotation);
@@ -10843,9 +11698,9 @@ const relatedConversationsRegistration = {
10843
11698
  hooks: { userPrompt: findRelatedConversations }
10844
11699
  };
10845
11700
  // src/chat/conversations/delivery-pause.ts
10846
- /** True when the Conversation delivers to a Location of its own. */
11701
+ /** True when the Conversation is a root that delivers to a Location. */
10847
11702
  function canPauseConversationDelivery(conversation) {
10848
- return ownsLocation(conversation) && conversation.location !== void 0;
11703
+ return isTopLevel(conversation) && conversation.location !== void 0;
10849
11704
  }
10850
11705
  const rootConversation$1 = (conversationId) => and(eq(juniorConversations.conversationId, conversationId), topLevelConversation());
10851
11706
  /**
@@ -10869,14 +11724,12 @@ async function resumeConversationDelivery(conversationId) {
10869
11724
  }).where(and(rootConversation$1(conversationId), isNotNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
10870
11725
  }
10871
11726
  /**
10872
- * True while this Conversation is detached from its Location. Only a
10873
- * top-level Conversation with its own Location stores the pause, so a child
10874
- * agent reads the pause of its top-level ancestor. A Lead's pause covers
10875
- * only the Lead: its children, such as Slack Conversations in its Space,
10876
- * own their Locations.
11727
+ * True while this Conversation is detached from its Location. Only a root
11728
+ * with a Location stores the pause, so a child agent reads the pause of its
11729
+ * root.
10877
11730
  */
10878
11731
  async function isConversationDeliveryPaused(conversationId) {
10879
- const [row] = await getSqlExecutor().db().select({ id: juniorConversations.conversationId }).from(juniorConversations).where(and(sql`${juniorConversations.conversationId} IN ${conversationAncestorsOrSelf(sql`${conversationId}`)}`, isNotNull(juniorConversations.deliveryPausedAt), or(eq(juniorConversations.conversationId, conversationId), sql`${juniorConversations.kind} is distinct from 'lead'`))).limit(1);
11732
+ const [row] = await getSqlExecutor().db().select({ id: juniorConversations.conversationId }).from(juniorConversations).where(and(sql`${juniorConversations.conversationId} IN ${conversationAncestorsOrSelf(sql`${conversationId}`)}`, isNotNull(juniorConversations.deliveryPausedAt))).limit(1);
10880
11733
  return Boolean(row);
10881
11734
  }
10882
11735
  // src/chat/code/links.ts
@@ -10953,153 +11806,6 @@ async function readSubjectLinks(db, items, plugins = getPlugins()) {
10953
11806
  }
10954
11807
  return links;
10955
11808
  }
10956
- // src/chat/credentials/context.ts
10957
- const exactActorIdSchema = z.string().refine((value) => parseActorUserId(value) === value);
10958
- const exactNonBlankStringSchema = z.string().min(1).refine((value) => value === value.trim());
10959
- const slackDirectCredentialSubjectBindingSchema = z.object({
10960
- type: z.literal("slack-direct-conversation"),
10961
- teamId: z.string().min(1),
10962
- channelId: z.string().min(1),
10963
- signature: z.string().min(1)
10964
- }).strict();
10965
- const scheduledAutomationCredentialSubjectBindingSchema = z.object({
10966
- type: z.literal("scheduled-automation"),
10967
- plugin: z.string().min(1),
10968
- taskId: exactNonBlankStringSchema,
10969
- signature: z.string().min(1)
10970
- }).strict();
10971
- const eventAutomationCredentialSubjectBindingSchema = z.object({
10972
- type: z.literal("event-automation"),
10973
- plugin: z.string().min(1),
10974
- taskId: exactNonBlankStringSchema,
10975
- signature: z.string().min(1)
10976
- }).strict();
10977
- const timerWatchCredentialSubjectBindingSchema = z.object({
10978
- type: z.literal("timer-watch"),
10979
- conversationId: exactNonBlankStringSchema,
10980
- watchId: exactNonBlankStringSchema,
10981
- signature: z.string().min(1)
10982
- }).strict();
10983
- z.discriminatedUnion("type", [
10984
- slackDirectCredentialSubjectBindingSchema,
10985
- scheduledAutomationCredentialSubjectBindingSchema,
10986
- eventAutomationCredentialSubjectBindingSchema,
10987
- timerWatchCredentialSubjectBindingSchema
10988
- ]);
10989
- const credentialUserActorSchema = z.object({
10990
- type: z.literal("user"),
10991
- userId: exactActorIdSchema
10992
- }).strict();
10993
- const credentialSystemActorSchema = z.object({
10994
- platform: z.literal("system"),
10995
- name: exactActorIdSchema
10996
- }).strict();
10997
- const credentialSubjectSchema = z.discriminatedUnion("allowedWhen", [
10998
- z.object({
10999
- type: z.literal("user"),
11000
- userId: exactActorIdSchema,
11001
- allowedWhen: z.literal("private-direct-conversation"),
11002
- binding: slackDirectCredentialSubjectBindingSchema
11003
- }).strict(),
11004
- z.object({
11005
- type: z.literal("user"),
11006
- userId: exactActorIdSchema,
11007
- allowedWhen: z.literal("scheduled-automation"),
11008
- taskId: exactNonBlankStringSchema,
11009
- binding: scheduledAutomationCredentialSubjectBindingSchema
11010
- }).strict().refine((subject) => subject.binding.taskId === subject.taskId, {
11011
- message: "Scheduled automation credential subject requires task binding",
11012
- path: ["binding"]
11013
- }),
11014
- z.object({
11015
- type: z.literal("user"),
11016
- userId: exactActorIdSchema,
11017
- allowedWhen: z.literal("event-automation"),
11018
- taskId: exactNonBlankStringSchema,
11019
- binding: eventAutomationCredentialSubjectBindingSchema
11020
- }).strict().refine((subject) => subject.binding.taskId === subject.taskId, {
11021
- message: "Event automation credential subject requires task binding",
11022
- path: ["binding"]
11023
- }),
11024
- z.object({
11025
- type: z.literal("user"),
11026
- userId: exactActorIdSchema,
11027
- allowedWhen: z.literal("timer-watch"),
11028
- binding: timerWatchCredentialSubjectBindingSchema
11029
- }).strict()
11030
- ]);
11031
- const credentialContextSchema = z.union([z.object({ actor: credentialUserActorSchema }).strict(), z.object({
11032
- actor: credentialSystemActorSchema,
11033
- subject: credentialSubjectSchema.optional()
11034
- }).strict()]);
11035
- /**
11036
- * Build credential authority from the run actor.
11037
- *
11038
- * `actor` is the rich execution principal. This projects the credential stub
11039
- * tools/auth need from it:
11040
- * - user actor → `{ actor: { type: "user", userId } }`
11041
- * - system actor → `{ actor: systemActor, subject? }`
11042
- *
11043
- * They only diverge when a system run carries an explicit delegated `subject`
11044
- * (scheduled/event-automation creator credentials). Callers should set `actor` first,
11045
- * then derive this — do not hand-build parallel shapes.
11046
- */
11047
- function credentialContextForActor(actor, subject) {
11048
- if (actor.platform === "system") return subject ? {
11049
- actor,
11050
- subject
11051
- } : { actor };
11052
- if (subject) throw new TypeError("Delegated credential subjects require a system actor");
11053
- return { actor: {
11054
- type: "user",
11055
- userId: actor.userId
11056
- } };
11057
- }
11058
- /**
11059
- * Name the person accountable for credential authority in logs.
11060
- *
11061
- * `userId` is the user actor, or the owner of delegated credentials when the
11062
- * system acts for an Automation or Watch. `actorType` says who acted.
11063
- */
11064
- function credentialLogContext(context) {
11065
- if ("type" in context.actor) return {
11066
- userId: context.actor.userId,
11067
- actorType: "user",
11068
- actorId: context.actor.userId
11069
- };
11070
- const subject = "subject" in context ? context.subject : void 0;
11071
- return {
11072
- actorType: "system",
11073
- actorId: context.actor.name,
11074
- ...subject ? {
11075
- userId: subject.userId,
11076
- credentialAllowedWhen: subject.allowedWhen,
11077
- ..."taskId" in subject ? { taskId: subject.taskId } : void 0
11078
- } : void 0
11079
- };
11080
- }
11081
- /**
11082
- * Name the run's people in logs: the accountable person and who acted.
11083
- *
11084
- * A user actor is the accountable person. A system actor names the owner of
11085
- * delegated credentials, when the run has them.
11086
- */
11087
- function actorLogContext(actor, credentialContext) {
11088
- const credential = credentialContext ? credentialLogContext(credentialContext) : {};
11089
- if (!isUserActor(actor)) return credential;
11090
- return {
11091
- ...credential,
11092
- userId: actor.userId,
11093
- userName: actor.userName,
11094
- userEmail: actor.email,
11095
- userFullName: actor.fullName
11096
- };
11097
- }
11098
- /** Return the user whose OAuth token may satisfy this credential request. */
11099
- function credentialUserSubjectId(context) {
11100
- if ("type" in context.actor) return context.actor.userId;
11101
- return "subject" in context ? context.subject?.userId : void 0;
11102
- }
11103
11809
  // src/chat/state/ttl.ts
11104
11810
  /** Retain expiring conversation/runtime state long enough for resume and dashboard history. */
11105
11811
  const JUNIOR_THREAD_STATE_TTL_MS = 6048e5;
@@ -11856,7 +12562,7 @@ async function publishAgentUpdate(conversationId, key, options) {
11856
12562
  const eventKey = updateEventKey(conversationId, key);
11857
12563
  let update;
11858
12564
  const readUpdate = () => update ??= options.update();
11859
- const delivery = () => import("./agent-update-delivery-B_YIZcgf.js");
12565
+ const delivery = () => import("./agent-update-delivery-DH8bx7jU.js");
11860
12566
  if (options.starter !== false) {
11861
12567
  const { deliverToStarter } = await delivery();
11862
12568
  await deliverToStarter({
@@ -13508,6 +14214,14 @@ function truncateStatusText(text) {
13508
14214
  if (trimmed.length <= SLACK_STATUS_MAX_LENGTH) return trimmed;
13509
14215
  return `${trimmed.slice(0, 47).trimEnd()}...`;
13510
14216
  }
14217
+ // src/chat/configuration/defaults.ts
14218
+ /**
14219
+ * Return the install-wide configuration defaults (empty object when none set).
14220
+ * Each call returns a copy, so a caller cannot change config.
14221
+ */
14222
+ function getConfigDefaults() {
14223
+ return structuredClone(getChatConfig().configDefaults);
14224
+ }
13511
14225
  // src/chat/plugins/cache.ts
13512
14226
  /** Create the cache scoped to one plugin. */
13513
14227
  function createPluginCache(plugin) {
@@ -13744,9 +14458,8 @@ function createPluginModelCostRecorder(args) {
13744
14458
  /** Create the host-owned structured model capability exposed to plugins. */
13745
14459
  function createPluginModel(pluginName, options = {}, runtime = {}) {
13746
14460
  return { async completeObject(input) {
13747
- const modelId = options.structuredModelId ?? (options.structuredModel === "default" ? botConfig.modelId : botConfig.fastModelId);
13748
14461
  const result = await completeObject$1({
13749
- modelId,
14462
+ modelId: options.structuredModelId ?? (options.structuredModel === "default" ? botConfig.modelId : botConfig.fastModelId),
13750
14463
  schema: input.schema,
13751
14464
  prompt: input.prompt,
13752
14465
  ...input.system !== void 0 ? { system: input.system } : void 0,
@@ -14659,7 +15372,7 @@ async function postSlackMessage(input) {
14659
15372
  ...threadTs ? { "app.slack.thread_ts": threadTs } : void 0,
14660
15373
  "app.slack.work_object.count": entities?.length ?? 0
14661
15374
  };
14662
- const messageTs = parseSlackMessageTs((await withSlackRetries(async () => {
15375
+ const response = await withSlackRetries(async () => {
14663
15376
  const response = await getSlackClient().chat.postMessage({
14664
15377
  channel: channelId,
14665
15378
  text,
@@ -14679,7 +15392,8 @@ async function postSlackMessage(input) {
14679
15392
  }, 3, {
14680
15393
  action: "chat.postMessage",
14681
15394
  attributes
14682
- })).ts);
15395
+ });
15396
+ const messageTs = parseSlackMessageTs(response.ts);
14683
15397
  if (!messageTs) throw new Error("Slack message posted without ts");
14684
15398
  return {
14685
15399
  ts: messageTs,
@@ -15575,6 +16289,48 @@ function renderSlackCard(card, conversationId) {
15575
16289
  case "automation": return renderSlackAutomationCard(card);
15576
16290
  }
15577
16291
  }
16292
+ // src/chat/sentry-links.ts
16293
+ function getSentryOrgSlug() {
16294
+ return getChatConfig().deployment.sentryOrgSlug;
16295
+ }
16296
+ function isSentrySaasDsnHost(host) {
16297
+ return host === "sentry.io" || host.endsWith(".sentry.io");
16298
+ }
16299
+ function buildSentryWebBaseUrl(dsn) {
16300
+ if (isSentrySaasDsnHost(dsn.host)) return "https://sentry.io";
16301
+ const port = dsn.port ? `:${dsn.port}` : "";
16302
+ const path = dsn.path ? `/${dsn.path}` : "";
16303
+ return `${dsn.protocol}://${dsn.host}${port}${path}`;
16304
+ }
16305
+ function buildSentryOrgPath(args) {
16306
+ const dsn = getClient$1()?.getDsn();
16307
+ if (!dsn?.host || !dsn.projectId) return;
16308
+ const orgSlug = getSentryOrgSlug();
16309
+ if (!orgSlug) return;
16310
+ const params = new URLSearchParams();
16311
+ params.set("project", dsn.projectId);
16312
+ if (args.query) for (const [key, value] of Object.entries(args.query)) params.set(key, value);
16313
+ const path = `${args.path}?${params.toString()}`;
16314
+ if (isSentrySaasDsnHost(dsn.host)) return `https://${orgSlug}.sentry.io/${path}`;
16315
+ return `${buildSentryWebBaseUrl(dsn)}/organizations/${orgSlug}/${path}`;
16316
+ }
16317
+ /** Build a Sentry conversation URL only when the runtime has enough Sentry config. */
16318
+ function buildSentryConversationUrl(conversationId) {
16319
+ return buildSentryOrgPath({ path: `explore/conversations/${encodeURIComponent(conversationId)}/` });
16320
+ }
16321
+ /** Build a Sentry event URL only when the runtime has enough Sentry config. */
16322
+ function buildSentryEventUrl(eventId) {
16323
+ return buildSentryOrgPath({
16324
+ path: "issues/",
16325
+ query: { query: eventId }
16326
+ });
16327
+ }
16328
+ /** Format a failure reference, linked to the Sentry event when the runtime can build the URL. */
16329
+ function formatSentryEventReference(eventId) {
16330
+ const reference = `event_id=${eventId}`;
16331
+ const url = buildSentryEventUrl(eventId);
16332
+ return url ? `[${reference}](${url})` : `\`${reference}\``;
16333
+ }
15578
16334
  // src/chat/queue/vercel.ts
15579
16335
  function defaultQueueClientOptions() {
15580
16336
  const { apiUrl } = getChatConfig().queue;
@@ -15756,9 +16512,13 @@ function toDelaySeconds(options) {
15756
16512
  if (!options?.delayMs || options.delayMs <= 0) return;
15757
16513
  return Math.ceil(options.delayMs / 1e3);
15758
16514
  }
16515
+ /** Resolve the conversation work topic: the given topic, config, then the default. */
16516
+ function resolveConversationWorkTopic(topic) {
16517
+ return topic?.trim() || getChatConfig().queue.conversationWorkTopic || "junior_conversation_work";
16518
+ }
15759
16519
  /** Create the Vercel Queue implementation for conversation wake-up nudges. */
15760
16520
  function createVercelConversationWorkQueue(options = {}) {
15761
- const topic = resolveConversationWorkQueueTopic(options);
16521
+ const topic = resolveConversationWorkTopic(options.topic);
15762
16522
  const client = options.client ?? getQueueProvider();
15763
16523
  return { async send(message, sendOptions) {
15764
16524
  const payload = signConversationQueueMessage(message);
@@ -15922,25 +16682,22 @@ function conversationAccessFromRows(rows, participantRootIds) {
15922
16682
  }));
15923
16683
  }
15924
16684
  /**
15925
- * Whether the viewer may add a Message to a Conversation. A signed-in person
15926
- * may post in a public Conversation, the same as in a public Slack thread.
15927
- * A web Message does not make them a Participant: they Join explicitly. A
15928
- * private one takes Messages only from its Participants.
16685
+ * Whether the viewer may add a Message to a Conversation. Only its
16686
+ * Participants act on a Conversation. A person who can read a public root
16687
+ * Joins it first.
15929
16688
  */
15930
16689
  function canAddConversationMessages(access) {
15931
- return Boolean(access?.isParticipant || access?.visibility === "public");
16690
+ return Boolean(access?.isParticipant);
15932
16691
  }
15933
16692
  /**
15934
- * Whether the viewer may add a person to a Conversation's Participants. In a
15935
- * public one, anyone who can post may Invite; it grants no access. In a
15936
- * private one, only a Participant may, and it shares the Conversation. A
15937
- * Slack-backed private Conversation follows its Slack channel, so it takes
15938
- * no Invites.
16693
+ * Whether the viewer may add a person to a Conversation's Participants. Only
16694
+ * a Participant may. In a public one it grants no access. In a private one
16695
+ * it shares the Conversation, except that a Slack-backed private
16696
+ * Conversation follows its Slack channel, so it takes no Invites.
15939
16697
  */
15940
16698
  function canInviteToConversation(access) {
15941
- if (!access?.rootConversationId) return false;
15942
- if (access.visibility === "public") return true;
15943
- return access.isParticipant && !isSlackBacked(access);
16699
+ if (!access?.rootConversationId || !access.isParticipant) return false;
16700
+ return access.visibility === "public" || !isSlackBacked(access);
15944
16701
  }
15945
16702
  /**
15946
16703
  * Whether Leave ends the viewer's access: it removes their own Participant
@@ -16660,7 +17417,7 @@ function pluginTaskCallback(options) {
16660
17417
  onRejected: logPluginTaskQueueMessageRejected,
16661
17418
  retryDelaySeconds: pluginTaskRetryDelaySeconds,
16662
17419
  run: async (message, metadata) => {
16663
- const { processPluginTask } = await import("./task-runner-C9Yc2_ae.js").then((n) => n.r);
17420
+ const { processPluginTask } = await import("./task-runner-BJ9Up3bG.js").then((n) => n.r);
16664
17421
  await processPluginTask(message, {
16665
17422
  ...options,
16666
17423
  deliveryCount: metadata.deliveryCount
@@ -18228,7 +18985,7 @@ const parentMessageSchema = z.object({
18228
18985
  }).strict();
18229
18986
  /**
18230
18987
  * Read the parent message that one mailbox input is, if it is one. Check its
18231
- * sender with `readChildOfStoredParent` before it gets any authority.
18988
+ * sender with `isDroppedChildInput` before it gets any authority.
18232
18989
  */
18233
18990
  function readParentMessage(message) {
18234
18991
  if (message.source !== "internal") return;
@@ -18940,7 +19697,8 @@ async function getConversationWorkState$1(args) {
18940
19697
  * read. A Conversation with no record has no entry.
18941
19698
  */
18942
19699
  async function getConversationWorkStates$1(conversationIds) {
18943
- const values = await getStateValues(await getConnectedState(), conversationIds.map(conversationKey));
19700
+ const state = await getConnectedState();
19701
+ const values = await getStateValues(state, conversationIds.map(conversationKey));
18944
19702
  const workStates = /* @__PURE__ */ new Map();
18945
19703
  for (const [index, conversationId] of conversationIds.entries()) {
18946
19704
  const conversation = conversationFromValue(conversationId, values[index]);
@@ -20093,7 +20851,7 @@ async function runDeferredMove(args) {
20093
20851
  const move = await takeDeferredConversationMove(args);
20094
20852
  if (move === void 0) return;
20095
20853
  try {
20096
- const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-DxVmhbGP.js").then((n) => n.r);
20854
+ const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-BNQLC12R.js").then((n) => n.r);
20097
20855
  await continueDeferredSlackClick(move, args.getSlackAdapter);
20098
20856
  } catch (error) {
20099
20857
  logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
@@ -20889,7 +21647,7 @@ const todosRegistration = {
20889
21647
  function isCoreRegistrationName(name) {
20890
21648
  return [
20891
21649
  eventSearchTaskRegistration({ embedEvents: false }),
20892
- memoryRegistration(),
21650
+ createMemoryRegistration(),
20893
21651
  notificationsTaskRegistration,
20894
21652
  relatedConversationsRegistration,
20895
21653
  todosRegistration
@@ -21589,9 +22347,8 @@ function conversationStarterUserIdSql(conversation) {
21589
22347
  *
21590
22348
  * - The latest Turn failed.
21591
22349
  * - The starter has not read the latest assistant Message. The starter read
21592
- * it when Slack accepted it for a Top-level Conversation's Location, when
21593
- * the starter wrote a later Message, or when their dashboard read
21594
- * position reaches it.
22350
+ * it when Slack accepted it for a root's Location, when the starter wrote
22351
+ * a later Message, or when their dashboard read position reaches it.
21595
22352
  * With no starter, nobody reads it, so an answer does not wait.
21596
22353
  */
21597
22354
  function conversationWaitsOnStarterSql(conversation) {
@@ -21602,7 +22359,7 @@ function conversationWaitsOnStarterSql(conversation) {
21602
22359
  const replySeq = sql`${reply}.seq`;
21603
22360
  const replyInSlack = sql`${reply}.in_slack`;
21604
22361
  const latestReply = sql`(select ${juniorConversationEvents.seq} as seq, coalesce(${juniorConversationEvents.payload}->'meta'->>'source' = 'slack', ${juniorConversationEvents.createdAt} < ${DELIVERY_PAUSE_START}) as in_slack from ${juniorConversationEvents} where ${and(eq(juniorConversationEvents.conversationId, id), sql`${juniorConversationEvents.type} = 'message'`, sql`${juniorConversationEvents.payload}->>'role' = 'assistant'`)} order by ${desc(juniorConversationEvents.seq)} limit 1)`;
21605
- const readByStarter = or(and(sql`(${conversation.parentConversationId} is null or ${isLeadSql(conversation.parentConversationId)})`, sql`${conversation.location} is not null`, sql`coalesce(${replyInSlack}, false)`), sql`exists (select 1 from ${juniorConversationEvents} join ${juniorIdentities} as ${replyReader} on ${eq(replyReader.id, juniorConversationEvents.actorIdentityId)} where ${and(eq(juniorConversationEvents.conversationId, id), eq(juniorConversationEvents.type, "message"), gt(juniorConversationEvents.seq, replySeq), eq(replyReader.userId, starterUserId))})`, sql`exists (select 1 from ${juniorConversationReadPositions} where ${and(eq(juniorConversationReadPositions.conversationId, id), eq(juniorConversationReadPositions.userId, starterUserId), gte(juniorConversationReadPositions.lastReadSeq, replySeq))})`);
22362
+ const readByStarter = or(and(isNull(conversation.parentConversationId), sql`${conversation.location} is not null`, sql`coalesce(${replyInSlack}, false)`), sql`exists (select 1 from ${juniorConversationEvents} join ${juniorIdentities} as ${replyReader} on ${eq(replyReader.id, juniorConversationEvents.actorIdentityId)} where ${and(eq(juniorConversationEvents.conversationId, id), eq(juniorConversationEvents.type, "message"), gt(juniorConversationEvents.seq, replySeq), eq(replyReader.userId, starterUserId))})`, sql`exists (select 1 from ${juniorConversationReadPositions} where ${and(eq(juniorConversationReadPositions.conversationId, id), eq(juniorConversationReadPositions.userId, starterUserId), gte(juniorConversationReadPositions.lastReadSeq, replySeq))})`);
21606
22363
  const waitsOnFacts = sql`(select ${replySeq} is not null and ${starterUserId} is not null and not (${readByStarter})
21607
22364
  from (select ${conversationStarterUserIdSql(conversation)} as user_id offset 0) as ${starter}
21608
22365
  left join lateral ${latestReply} as ${reply} on true)`;
@@ -22207,9 +22964,6 @@ function destinationFromRow(destination) {
22207
22964
  } : void 0);
22208
22965
  }
22209
22966
  // src/chat/conversations/sql/store.ts
22210
- const parentConversation = alias(juniorConversations, "parent_conversation");
22211
- /** Columns of the parent that `conversationFromRow` reads. */
22212
- const parentReadColumns = { destinationId: parentConversation.destinationId };
22213
22967
  /** The Space of the row's tree, for `conversationFromRow`. */
22214
22968
  const treeSpaceIdColumn = rootSpaceIdSql(juniorConversations);
22215
22969
  const CONVERSATION_MUTATION_LOCK_PREFIX = "junior_conversation";
@@ -22248,9 +23002,7 @@ function conversationFromRow(readRow) {
22248
23002
  updatedAtMs: msFromDate(row.executionUpdatedAt) ?? requiredMsFromDate(row.updatedAt)
22249
23003
  };
22250
23004
  const location = locationFromRow(row.location, readRow.destination, sessionSource);
22251
- const { parent } = readRow;
22252
23005
  const spaceId = row.spaceId ?? readRow.treeSpaceId;
22253
- const ownLocation = parent !== null && row.location !== null && row.destinationId !== parent.destinationId ? true : void 0;
22254
23006
  return {
22255
23007
  schemaVersion: 1,
22256
23008
  conversationId: row.conversationId,
@@ -22267,7 +23019,6 @@ function conversationFromRow(readRow) {
22267
23019
  ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
22268
23020
  ...row.rootConversationId ? { rootConversationId: row.rootConversationId } : void 0,
22269
23021
  ...spaceId ? { spaceId } : void 0,
22270
- ...ownLocation ? { ownLocation } : void 0,
22271
23022
  ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
22272
23023
  ...destination ? { destination } : void 0,
22273
23024
  ...location ? { location } : void 0,
@@ -22304,6 +23055,14 @@ function assertSameConversationDestination(args) {
22304
23055
  if (!args.current || sameDestination(args.current, args.next)) return;
22305
23056
  throw new Error(`Conversation destination changed for ${args.conversationId}`);
22306
23057
  }
23058
+ /**
23059
+ * Return whether a write keeps the stored Destination, whatever Destination
23060
+ * it names. A child stores its parent's. A local one is final: Slack input
23061
+ * in a thread that moved into a Space, or left one, does not reconnect it.
23062
+ */
23063
+ function keepsStoredDestination(existing) {
23064
+ return existing !== void 0 && (!isTopLevel(existing) || existing.destination?.platform === "local");
23065
+ }
22307
23066
  var SqlStore = class {
22308
23067
  executor;
22309
23068
  constructor(executor) {
@@ -22334,7 +23093,6 @@ var SqlStore = class {
22334
23093
  }
22335
23094
  const parentRow = await this.readConversationRow(args.parentConversationId);
22336
23095
  if (!parentRow) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
22337
- const toLead = childrenAreTopLevel(parentRow.conversation.kind);
22338
23096
  const { location } = conversationFromRow(parentRow);
22339
23097
  const child = {
22340
23098
  ...emptyConversation({
@@ -22344,12 +23102,12 @@ var SqlStore = class {
22344
23102
  }),
22345
23103
  kind: args.kind,
22346
23104
  parentConversationId: args.parentConversationId,
22347
- ...toLead ? { destination: ownLocalDestination(args.childConversationId) } : location ? { location } : void 0,
23105
+ ...location ? { location } : void 0,
22348
23106
  ...args.title ? { title: args.title } : void 0
22349
23107
  };
22350
23108
  await this.upsertConversation({
22351
23109
  conversation: child,
22352
- ...toLead ? void 0 : { destinationId: parentRow.conversation.destinationId ?? void 0 }
23110
+ destinationId: parentRow.conversation.destinationId ?? void 0
22353
23111
  });
22354
23112
  });
22355
23113
  });
@@ -22368,7 +23126,7 @@ var SqlStore = class {
22368
23126
  const sessionSource = normalizeSessionSource(args.sessionSource);
22369
23127
  await this.withConversationMutation(args.conversationId, async () => {
22370
23128
  const existing = await this.get({ conversationId: args.conversationId });
22371
- if (existing && args.destination) assertSameConversationDestination({
23129
+ if (existing && args.destination && !keepsStoredDestination(existing)) assertSameConversationDestination({
22372
23130
  conversationId: args.conversationId,
22373
23131
  current: existing.destination,
22374
23132
  next: args.destination
@@ -22427,7 +23185,7 @@ var SqlStore = class {
22427
23185
  ...existing?.parentConversationId ? { parentConversationId: existing.parentConversationId } : void 0,
22428
23186
  ...existing?.location ? { location: existing.location } : void 0,
22429
23187
  ...args.channelName ? { channelName: args.channelName } : void 0,
22430
- ...args.destination ? { destination: args.destination } : void 0,
23188
+ ...args.destination && !keepsStoredDestination(existing) ? { destination: args.destination } : void 0,
22431
23189
  ...actor ? { actor } : void 0,
22432
23190
  ...source ? { source } : void 0,
22433
23191
  ...args.title ? { title: args.title } : void 0,
@@ -22458,9 +23216,8 @@ var SqlStore = class {
22458
23216
  destination: juniorDestinations,
22459
23217
  actorIdentity: juniorIdentities,
22460
23218
  actorUserDisplayName: juniorUsers.displayName,
22461
- parent: parentReadColumns,
22462
23219
  treeSpaceId: treeSpaceIdColumn
22463
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(parentConversation, eq(parentConversation.conversationId, juniorConversations.parentConversationId)).where(topLevelConversation()).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(Math.max(0, args.limit ?? 1e4)).offset(Math.max(0, args.offset ?? 0));
23220
+ }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(topLevelConversation()).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(Math.max(0, args.limit ?? 1e4)).offset(Math.max(0, args.offset ?? 0));
22464
23221
  const conversations = [];
22465
23222
  for (const row of rows) conversations.push(conversationFromRow(row));
22466
23223
  return conversations;
@@ -22498,9 +23255,8 @@ var SqlStore = class {
22498
23255
  destination: juniorDestinations,
22499
23256
  actorIdentity: juniorIdentities,
22500
23257
  actorUserDisplayName: juniorUsers.displayName,
22501
- parent: parentReadColumns,
22502
23258
  treeSpaceId: treeSpaceIdColumn
22503
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(parentConversation, eq(parentConversation.conversationId, juniorConversations.parentConversationId)).where(eq(juniorConversations.conversationId, conversationId)))[0];
23259
+ }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(eq(juniorConversations.conversationId, conversationId)))[0];
22504
23260
  }
22505
23261
  /** Upsert the conversation row while preserving previously discovered nullable metadata fields. */
22506
23262
  async upsertConversation(args) {
@@ -22603,19 +23359,11 @@ var SqlStore = class {
22603
23359
  rootConversationId: juniorConversations.rootConversationId,
22604
23360
  visibility: juniorConversations.visibility,
22605
23361
  filledVisibility: sql`exists (select 1 from ${prior} where ${prior.visibility} is null)`,
22606
- setActor: sql`not exists (select 1 from ${prior} where ${prior.actorIdentityId} is not null)`,
22607
- storedParentIsLead: isLeadSql$1(sql.raw(`"junior_conversations"."parent_conversation_id"`)),
22608
- incomingParentIsLead: isLeadSql$1(sql`${conversation.parentConversationId ?? null}`)
23362
+ setActor: sql`not exists (select 1 from ${prior} where ${prior.actorIdentityId} is not null)`
22609
23363
  }))[0];
22610
23364
  if (!row?.rootConversationId) throw new Error("Conversation parent is missing its persisted root");
22611
23365
  if (!copiesRootVisibility(conversation) && row.visibility && row.filledVisibility) await fillMissingTreeVisibility(this.executor, row.rootConversationId, row.visibility);
22612
- if (!keepsStoredParent({
22613
- id: row.parentConversationId,
22614
- isLead: row.storedParentIsLead
22615
- }, {
22616
- id: conversation.parentConversationId,
22617
- isLead: row.incomingParentIsLead
22618
- })) throw new Error(`Conversation parent changed for ${conversation.conversationId}`);
23366
+ if (!keepsStoredParent(row.parentConversationId, conversation.parentConversationId)) throw new Error(`Conversation parent changed for ${conversation.conversationId}`);
22619
23367
  if (row.actorIdentityId && row.setActor && row.parentConversationId === null) await recordConversationParticipant(this.executor, {
22620
23368
  actorIdentityId: row.actorIdentityId,
22621
23369
  conversationId: conversation.conversationId,
@@ -22842,10 +23590,16 @@ function conversationDescendants(tree, conversationId) {
22842
23590
  */
22843
23591
  async function setArchivedAt(db, conversations, archivedAt, guard) {
22844
23592
  if (!(conversations instanceof SQL) && conversations.length === 0) return 0;
22845
- return (await db.update(juniorConversations).set({
23593
+ const updated = await db.update(juniorConversations).set({
22846
23594
  archivedAt,
22847
23595
  detailVersion: nextDetailVersion
22848
- }).where(and(conversations instanceof SQL ? conversations : inArray(juniorConversations.conversationId, [...conversations]), guard)).returning({ conversationId: juniorConversations.conversationId })).length;
23596
+ }).where(and(conversations instanceof SQL ? conversations : inArray(juniorConversations.conversationId, [...conversations]), guard)).returning({
23597
+ conversationId: juniorConversations.conversationId,
23598
+ spaceId: juniorConversations.spaceId
23599
+ });
23600
+ const inSpaces = updated.filter((row) => row.spaceId);
23601
+ if (inSpaces.length > 0) await db.update(juniorSpaces).set({ archivedAt }).where(inArray(juniorSpaces.id, db.select({ id: juniorConversations.spaceId }).from(juniorConversations).where(and(inArray(juniorConversations.conversationId, inSpaces.map((row) => row.conversationId)), eq(juniorConversations.kind, "lead")))));
23602
+ return updated.length;
22849
23603
  }
22850
23604
  /**
22851
23605
  * Restore one archived Conversation and its archived ancestors, so it shows
@@ -23245,14 +23999,14 @@ var SqlConversationEventStore = class {
23245
23999
  if (!row.actorIdentityId || data.type !== "message") continue;
23246
24000
  if (data.meta?.["eventType"]) continue;
23247
24001
  const unarchives = eventUnarchivesConversation(data);
23248
- const isPerson = await recordConversationParticipant(this.executor, {
24002
+ const isParticipant = await recordConversationParticipant(this.executor, {
23249
24003
  actorIdentityId: row.actorIdentityId,
23250
24004
  conversationId,
23251
24005
  atMs: row.createdAt.getTime(),
23252
24006
  message: true,
23253
24007
  resubscribe: eventAddressesJunior(data) || rootArchived && unarchives
23254
24008
  });
23255
- restores ||= isPerson && unarchives;
24009
+ restores ||= isParticipant && unarchives;
23256
24010
  }
23257
24011
  if (restores) await restoreArchivedPath(this.executor.db(), conversationId);
23258
24012
  }
@@ -24069,4 +24823,4 @@ async function closeDb() {
24069
24823
  current = void 0;
24070
24824
  await previous?.db.close();
24071
24825
  }
24072
- export { canReadInboxItem as $, resolveAssignees as $a, deleteExpiredInboxSnoozes as $c, juniorTurns as $d, listScheduledAutomationsForTeam as $i, deliversFinalText as $l, getPluginApiRoutes as $n, pauseConversationDelivery as $o, getDispatchIdForConversation as $r, listAdminUsersFromSql as $s, drainConversationMailbox as $t, isLeadConversation as $u, setFirstConversationLocation as A, readAutomationExecutionStatusDays as Aa, listReplyActionItems as Ac, todoFuzzyTitle as Ad, wrapBareSlackUserIds as Ai, isDashboardLink as Al, isAttemptInterrupt as An, bindScheduledAutomationCredentialSubject as Ao, viewerMarksFromParticipant as Ar, listPushSubscriptions as As, makeStructuredToolOutput as At, embedConversationQuery as Au, conversationIsActiveSql as B, microUsdToUsd as Ba, questionLinks as Bc, inboxItemFuzzyTitle as Bd, renderPluginConversationEvent as Bi, memoryDb as Bl, resolveSlackInboxItemCardConversationId as Bn, credentialContextForActor as Bo, getQueueProvider as Br, isConversationChannel as Bs, appendAndEnqueueExclusiveInboundMessage as Bt, agentsInstructionsUpdatedEvent as Bu, conversationSlackTenantId as C, AutomationConflictError as Ca, closeReadReplyNotice as Cc, topLevelConversation as Cd, slackExternalRefIdSchema as Ci, getDashboardConversationLink as Cl, moveIdleConversationDestination as Cn, getWatch as Co, readConversationAccessRows as Cr, createSlackActor as Cs, registry_exports as Ct, excerptTerms as Cu, createSqlStore as D, existingConversationId as Da, getInboxItem as Dc, juniorWorkspaceRepos as Dd, normalizeSlackStatusText as Di, getDashboardSettingsLink as Dl, withIdleConversation as Dn, takeDueTimerWatches as Do, conversationPinnedForUser as Dr, parseActorUserId as Ds, coreRegistrations as Dt, setEventEmbeddingsConfig as Du, latestUserMessageQuery as E, emptyAutomationRunWindows as Ea, dismissOpenInboxItems as Ec, juniorSnapshots as Ed, formatSlackLink as Ei, getDashboardPersonLink as El, traceContextSchema as En, listWatches as Eo, conversationIsNotUnsubscribedRoot as Er, isUserActor as Es, apiRoutePrefix as Et, isEventEmbeddingsEnabled as Eu, parseSessionSource as F, readAutomationRuns as Fa, inboxItemAnswer as Fc, juniorAutomationRuns as Fd, createPluginDecider as Fi, setMemoryConfig as Fl, createSlackInboxItemToolServices as Fn, verifySlackDirectCredentialSubject as Fo, isConversationQueueMessageRejectedError as Fr, SlackActionError as Fs, agentNameSchema as Ft, generateImages as Fu, executionIsActive as G, syncAutomationAlerts as Ga, identityAvatarUrl as Gc, juniorAgentBindings as Gd, buildCommandScript as Gi, prefixMatch as Gl, parseSlackInboxItemClick as Gn, codeChangeSubjectProvider as Go, verifySlackSignature as Gr, readPrivateSlackFile as Gs, checkInConversationWork as Gt, disconnectStateAdapter as Gu, conversationStatusSql as H, usdToMicroUsdUnbiased as Ha, subjectKindPlugin as Hc, juniorInboxItemConversations as Hd, createSandboxCapability as Hi, parseTypedQuery as Hl, findSlackThreadOwnerId as Hn, credentialLogContext as Ho, annotationKeyDigest as Hr, isDmChannel as Hs, appendInboundMessage as Ht, conversationNoteEvent as Hu, conversationCostOf as I, readAutomationTitlesByConversationId as Ia, inboxItemRequest as Ic, automationFuzzyTitle as Id, createPluginEmbedder as Ii, REVALIDATED_READ_PATHS as Il, createInboxItemShow as In, verifyTimerWatchCredentialSubject as Io, nudgeIdempotencyKey as Ir, downloadPrivateSlackFile as Is, spawnChildAgentInputSchema as It, searchWeb as Iu, hasUnexpiredAuthorizationRequest as J, resolveTaskTitle as Ja, readUserAvatarUrls as Jc, juniorConversationEventLexemes as Jd, createPluginCache as Ji, scoredSearchMatches as Jl, parseSlackUserInputSubmission as Jn, codeChangeUrl as Jo, buildDispatchId as Jr, sleep$2 as Js, clearConsumedConversationWake as Jt, setStateValues as Ju, conversationKindFromRow as K, fallbackShortTitle as Ka, parseAvatarUrl as Kc, juniorConversationReadPositions as Kd, buildNonInteractiveShellScript as Ki, prefixRank as Kl, parseSlackInboxItemFormTarget as Kn, readSubjectLinks as Ko, resolveConversationRouting as Kr, streamPrivateSlackFile as Ks, claimConversationAttempt as Kt, getStateAdapter as Ku, conversationAggregateColumns as L, recordAutomationExecution as La, inboxItemTitle as Lc, automationSearchDocument as Ld, createPluginModel as Li, contentVersion as Ll, pushConversationInboxItemsNow as Ln, updateTimerIndex as Lo, QUEUE_SIGNATURE_MAX_AGE_MS as Lr, getFilePermalink as Ls, listTodos as Lt, transcribeFromUrl as Lu, locationSchema as M, readAutomationExecutionSummaries as Ma, searchInboxItems as Mc, juniorQuestions as Md, getPluginUserPromptContributions as Mi, parseDashboardPersonLink as Ml, readParentMessage as Mn, createSlackDirectCredentialSubject as Mo, verifyConversationQueueMessage as Mr, saveNotificationSchedule as Ms, getAgentBinding as Mt, completeDecision as Mu, claimProviderConversation as N, readAutomationExecutions as Na, takeInboxItem as Nc, questionFuzzyTitle as Nd, pluginMcpContext as Ni, setDashboardConversationLinkOptions as Nl, readInboundMessageSender as Nn, verifyEventAutomationCredentialSubject as No, ConversationQueueMessageRejectedError as Nr, savePushSubscription as Ns, CHILD_AGENT_KINDS as Nt, completeObject as Nu, withConversationMutationLock as O, linkAutomationRunConversation as Oa, getOpenInboxItemBySubject as Oc, juniorWorkspaces as Od, slackMention as Oi, getDashboardSpaceLink as Ol, canJoinTurn as On, turnEvents as Oo, readMemberParticipants as Or, toStoredSlackActor as Os, injectContinuationToolName as Ot, backfillConversationEmbeddings as Ou, getConversationIdByProviderConversation as P, readAutomationRowStats as Pa, updateInboxItemContent as Pc, questionSearchDocument as Pd, createPluginState as Pi, projectConversationMessages as Pl, isEventMailboxMetadata as Pn, verifyScheduledAutomationCredentialSubject as Po, conversationQueueMessageSchema as Pr, isPausedBySlack as Ps, PARENT_AGENT_TARGET as Pt, completeText as Pu, canAnswerInboxItem as Q, resolveAssignee as Qa, clearInboxWakeReasons as Qc, juniorConversationEvents as Qd, deleteScheduledAutomation as Qi, childrenAreTopLevel as Ql, createPluginEventPublisher as Qn, isConversationDeliveryPaused as Qo, getDispatchConversationId as Qr, findUserByEmail as Qs, deadLetterAttempt as Qt, hasAgentTurnUsage as Qu, conversationRangeColumns as R, refreshAutomationLastRun as Ra, itemQuestion as Rc, juniorAutomations as Rd, createPluginModelCostRecorder as Ri, contentVersionHeaders as Rl, pushInboxSnoozeWakes as Rn, JUNIOR_THREAD_STATE_TTL_MS as Ro, signQueueMessage as Rr, getHeaderString as Rs, setTodoStatusByUser as Rt, NoAudioError as Ru, setArchivedAt as S, sameDefinitionValue as Sa, closeHandledReplyNotices as Sc, notLeadConversation as Sd, slackEntitySchema as Si, isToolInputError as Sl, isInvalidConversationRecordError as Sn, findMatchingWatches as So, readConversationAccessFromSql as Sr, createActor as Ss, getRegistrations as St, eventExcerpt as Su, lastMessageAtSql as T, requireAutomationRevision as Ta, closeInboxItem as Tc, juniorTurnInbox as Td, escapeSlackMrkdwnText as Ti, getDashboardLinkFilter as Tl, releaseInboundMessage as Tn, listConversationsWithWatches as To, conversationIsMemberRoot as Tr, isActorUserId as Ts, validatePlugins as Tt, event_embedding_config_exports as Tu, conversationTurnFailedSql as U, AUTOMATION_ALERT_STEPS as Ua, subjectTodo as Uc, juniorInboxItems as Ud, pluginConfigValues as Ui, fuzzyMatch as Ul, SLACK_INBOX_ITEM_VIEW_ID as Un, credentialSubjectSchema as Uo, decodeAnnotationRef as Ur, isSlackRequestTimeout as Us, beginConversationResume as Ut, renderJuniorNativeConversationEvent as Uu, conversationLastTurnOutcomeSql as V, usdToMicroUsd as Va, subjectKindLabel as Vc, inboxItemSearchDocument as Vd, basePluginContext as Vi, searchTypedMemories as Vl, syncInboxItemSlackCards as Vn, credentialContextSchema as Vo, renderSlackObjectCard as Vr, isConversationScopedChannel as Vs, appendAndEnqueueInboundMessage as Vt, authenticationLinkedEvent as Vu, conversationWaitsOnUserSql as W, AUTOMATION_ALERT_STEP_FIELD_ID as Wa, hasUserPhoto as Wc, juniorLocationConfigurations as Wd, withPluginHookSpan as Wi, fuzzyRank as Wl, buildSlackInboxItemModal as Wn, credentialUserSubjectId as Wo, runWithSlackInstallation as Wr, normalizeSlackConversationId as Ws, cancelHumanFacingPendingMessages as Wt, adapter_exports as Wu, canActOnInboxItem as X, activeParticipantUserIds as Xa, userAvatarUrlsFromJoinedPhotos as Xc, juniorConversationEmbeddings as Xd, blockScheduledAutomation as Xi, canMoveToSpace as Xl, sendSlackReply as Xn, linkedCodeProviders as Xo, confirmDispatchMailboxAppend as Xr, runWithWorkspaceTeamId as Xs, completeConversationStop as Xt, agentTurnCostUsd as Xu, treeAwaitsAuthorization as Y, EVERYONE_ASSIGNEE as Ya, userAvatarUrlsFromIdentities as Yc, juniorConversationEventEmbeddings as Yd, truncateStatusText as Yi, fuseRankedLists as Yl, resolveSlackReplyTarget as Yn, codeRepositoryUrl as Yo, claimDispatchMailboxAppend as Yr, getWorkspaceTeamId as Ys, clearExpiredConversationLease as Yt, addAgentTurnUsage as Yu, canAgentChangeInboxItem as Z, automationCreatorUserId as Za, SNOOZE_TIMER_EVENT_TYPE as Zc, juniorConversationMetrics as Zd, createScheduledAutomation as Zi, capsActiveChildren as Zl, resolveEventMentions as Zn, canPauseConversationDelivery as Zo, createOrGetDispatch as Zr, createPluginUsers as Zs, completeConversationWork as Zt, agentTurnUsageSchema as Zu, unseenEvents as _, eventAutomationRunLimitReason as _a, readCachedUserByEmail as _c, slackMessageTsFromMs as _d, guardedCosineDistance as _f, postSlackEphemeralMessage as _i, registeredEventTypeSchema as _l, countPendingConversationMessages as _n, cancelWatch as _o, canInviteToConversation as _r, defaultTimezone as _s, requireInboxItemAssignees as _t, searchedEventTextSql as _u, getDb as a, withScheduledAutomationLock as aa, updateViewerDisplayName as ac, createSlackDestination as ad, juniorCodeRepositories as af, listPendingDispatchMailboxAppends as ai, snoozeInboxItems as al, listActiveConversationIds as an, slackChannelMessageRunsAutomation as ao, pluginTaskParamsSchema as ar, conversationSearchVector as as, inboxItemOwnedByConversation as at, isTopLevelWork as au, conversationDescendants as b, listAutomationVersions as ba, listWaitingConversations as bc, spaceLeadIds as bd, getConfigDefaults as bf, unfurlSlackLinks as bi, requireValidEventTrigger as bl, hasRunnableConversationWork as bn, createWatch as bo, createConversationAccessReader as br, lookupSlackUser as bs, inboxItemVisibility as bt, SEARCHABLE_EVENT_TYPES as bu, pendingMigrations as c, createEventAutomation as ca, saveActorAvatar as cc, parseSlackChannelId as cd, juniorMessageAttachments as cf, markDispatchCompleted as ci, CORE_EVENT_NAMESPACE as cl, releaseConversationWork as cn, WORKSPACE_SNAPSHOT_READY_EVENT as co, getTurnRequestDeadline as cr, isPublicConversation as cs, inboxItemReaderForUserInConversation as ct, promptModeTurnTools as cu, createSqlConversationEventStore as d, getEventAutomation as da, findLinkedSlackUser as dc, parseSlackUserId as dd, juniorSpaces as df, notifyAutomationBlocked as di, eventGuidance as dl, startConversationWork as dn, AGENT_RESOURCE_TYPE as do, createPluginTurnEventReader as dr, conversationAncestorsOrSelf as ds, isInboxItemForEveryone as dt, watcherStartedConversation as du, parseScheduledAutomationRow as ea, readActorIdentity as ec, resolveRootConversationId as ed, juniorApiTokens as ef, getDispatchInputMessageId as ei, inboxItemInRow as el, dropPendingMessages as en, getEventCatalog as eo, getPluginRoutes as er, resumeConversationDelivery as es, canUserReadInboxItem as et, dispatchInstructionsInvokeSkills as eu, eventFromRow as f, listDeletedEventAutomationsCreatedBy as fa, findSlackUserByPrimaryEmail as fc, slackBotIdSchema as fd, juniorIdentities as ff, addReactionToMessage as fi, eventNamespaceSchema as fl, steerWebPendingMessages as fn, agentWatch as fo, createPluginConversationChanges as fr, conversationSubtree as fs, isOnlyAssignee as ft, EVENT_INDEX_LOCK_TTL_MS as fu, readEventCursor as g, admitEventAutomationRun as ga, readCachedLinkedHandle as gc, parseSlackMessageTs as gd, juniorDestinations as gf, openSlackModal as gi, registeredEventTriggerProblems as gl, CONVERSATION_WORK_STALE_ENQUEUE_MS as gn, cancelSubscriptions as go, canAddConversationMessages as gr, resolveNotificationTimezone as gs, readInboxItemAgentScope as gt, lexemesSql as gu, insertEventRows as h, setEventAutomationStatus as ha, upsertLinkedIdentity as hc, slackUserIdSchema as hd, juniorUsers as hf, openSlackDirectMessage as hi, registeredEventMatchSchema as hl, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as hn, starterWatchId as ho, canAccessConversation as hr, sendPushNotificationToUser as hs, questionSubject as ht, indexEndedTurnEvents as hu, getConversationStore as i, scheduledRunId as ia, setUserAdminFromSql as ic, touchConversationDetail as id, juniorCodeChanges as if, isTerminalDispatchStatus as ii, settleInboxSnoozes as il, getConversationWorkStates as in, slackChannelMessageReplyThreadTs as io, pluginTaskId as ir, listConversationAnnotationsById as is, inboxItemNeedsInput as it, isTopLevel as iu, startLocationThread as j, readAutomationExecutionStatusHours as ja, ownerConversationId as jc, todoSearchDocument as jd, applyPluginFormatMarkdown as ji, parseDashboardConversationLink as jl, selectAttemptMessages as jn, bindSlackDirectCredentialSubject as jo, getVercelConversationWorkQueue as jr, readNotificationSchedule as js, findChildAgentConversationId as jt, storeConversationEmbedding as ju, locationFromRow as k, readAutomationExecutionByConversationId as ka, insertInboxItem as kc, juniorTodos as kd, slackMentionedUserIds as ki, getDashboardTaskLink as kl, canShareTurn as kn, bindEventAutomationCredentialSubject as ko, rootVisibleToViewer as kr, deletePushSubscription as ks, juniorToolOutputSchema as kt, createConversationEmbedder as ku, readMigrationRecords as l, deleteEventAutomation as la, deleteProviderIdentityForSlackUser as lc, parseSlackChannelReferenceId as ld, juniorConversations as lf, markDispatchFailed as li, automationEventCatalog as ll, requestAnotherSlice as ln, workspaceSnapshotFinishedEvent as lo, createPluginCodeChanges as lr, resolveRootVisibility as ls, inboxItemVisibleTo as lt, remindsNoReplyForChildStatus as lu, deleteMessageLinks as m, saveEventAutomation as ma, recordGoogleSignIn as mc, slackTeamIdSchema as md, slackPersonSearchDocument as mf, getSlackMessagePermalink as mi, hasEventCatalogEntries as ml, takePendingEventMessages as mn, publishAgentUpdate as mo, createPluginInboxItems as mr, readWebPushConfig as ms, itemNeedsUser as mt, eventIndexLockKey as mu, getConversationEventStore as n, saveScheduledAutomation as na, readViewerAvatarUrl as nc, conversationDetailTouch as nd, codeChangeSearchDocument as nf, getDispatchTurnId as ni, listFiringInboxSnoozeTriggers as nl, getConversation as nn, requireSlackChannelMessageScope as no, startedTaskDefinition as nr, createPluginAnnotations as ns, inboxItemAddedByAutomation as nt, isPersonInput as nu, getSqlExecutor as o, blockEventAutomation as oa, SYSTEM_IDENTITY_ID as oc, requireSlackDestination as od, juniorAttachmentUploads as of, markDispatchAwaitingResume as oi, snoozeTimerTrigger as ol, recordAttemptFailure as on, slackChannelMessageTrigger as oo, sendVercelPluginTask as or, readConversationMetadata as os, inboxItemPlugin as ot, ownsLocation as ou, copyMessageLinks as p, parseEventAutomationRow as pa, findUserByVerifiedEmails as pc, slackChannelIdSchema as pd, slackPersonPredicate as pf, deleteSlackMessage as pi, eventWatchUnavailable as pl, stopConversationWork as pn, isAgentResourceType as po, PLUGIN_CHOICE_FIELD_ID as pr, conversationSubtreeColumns as ps, isPluginInboxItem as pt, embedConversationEvents as pu, awaitsAuthorizationFrom as q, generateShortTitle as qa, readAvatarFetch as qc, juniorConversationParticipants as qd, runNonInteractiveCommand as qi, rankSearchMatches as ql, safeLinkUrl as qn, subjectKey as qo, resolveTurnResumeRouting as qr, withSlackRetries as qs, claimInboundMessage as qt, getStateValues as qu, getConversationMessageSearchStore as r, saveScheduledAutomationInLock as ra, resolveViewerUser as rc, nextDetailVersion as rd, codeRepositorySearchDocument as rf, getPluginDispatchProjection as ri, readViewerInboxSnoozes as rl, getConversationWorkState as rn, slackChannelMessageEvent as ro, createVercelPluginTaskCallback as rr, listConversationAnnotations as rs, inboxItemForUser as rt, isThread as ru, createJuniorSqlExecutor as s, collectEventAutomationMatchKeys as sa, resolveActorIdentityId as sc, sameDestination as sd, juniorAttachments as sf, markDispatchBlocked as si, unsnoozeInboxRow as sl, recordConversationRetry as sn, WORKSPACE_SNAPSHOT_FAILED_EVENT as so, queueCallback as sr, writeConversationMetadata as ss, inboxItemReaderForUser as st, postsRunNotices as su, db_exports as t, readScheduledAutomation as ta, readIdentityById as tc, rootConversationIsArchived as td, juniorConversationAnnotations as tf, getDispatchRecord as ti, inboxItemSnoozedBy as tl, ensureConversationWake as tn, SLACK_EVENT_NAMESPACE as to, createPluginTaskStarter as tr, searchConversations as ts, inboxItemAddedByAnyAutomation as tt, hasConversationMetadata as tu, isPostgresErrorCode as u, findMatchingEventAutomations as ua, deleteProviderIdentityForUser as uc, parseSlackTeamId as ud, juniorSpaceConfigurations as uf, markDispatchRunning as ui, describeRegisteredEventTrigger as ul, requestConversationWork as un, workspaceSnapshotWatch as uo, createPluginConversationEventStats as ur, setMovedWorkVisibility as us, isAutomationAlertItem as ut, turnBehavior as uu, withConversationEventLock as v, automationDefinition as va, countInboxItemsNeedingUserBySubject as vc, slackMessageTsSchema as vd, juniorArtifacts as vf, postSlackMessage as vi, registeredResourceTypeSchema as vl, deferConversationMove as vn, collectEventMatchKeys as vo, canReadConversation as vr, findActorTimezone as vs, requireInboxItemLinks as vt, seqIn as vu, loadConversationSlackTenantIds as w, automationRevision as wa, INBOX_ITEM_REPLIED_REASON as wc, juniorTurnOutbox as wd, SLACK_USER_MENTION_RE as wi, getDashboardInboxItemLink as wl, pruneActiveConversation as wn, isQuietEvent as wo, readableSlackTeamId as wr, createSlackResumeActor as ws, setPlugins as wt, storedMessageJson as wu, readConversationTrees as x, readAutomationVersion as xa, waitingConversationIdsQuery as xc, listedConversation as xd, setConfigDefaults as xf, uploadFilesToConversation as xi, ToolInputError as xl, isFinalAttempt as xn, deliverWatch as xo, leaveEndsAccess as xr, lookupSlackUserNames as xs, getPlugins as xt, callsToolSql as xu, conversationAncestors as y, automationVersionOf as ya, inboxItemsNeedingUserVersionQuery as yc, rootSpaceIdSql as yd, resolveConversationDestination as yf, removeReactionFromMessage as yi, requireEventIdentifier as yl, hasConversationStop as yn, createTimerWatch as yo, conversationAccessFromRows as yr, resolveUserTimezone as ys, inboxItemOwnerConversationId as yt, storeConversationEventLexemes as yu, conversationUsageCostExpr as z, microUsdSql as za, INBOX_SUBJECT_KINDS as zc, juniorStats as zd, createPluginConversationEvents as zi, revalidateContent as zl, runInboxItemPushTimers as zn, actorLogContext as zo, verifyQueueMessage as zr, getSlackClient as zs, ackMessages as zt, JUNIOR_NATIVE_EVENT_NAMESPACE as zu };
24826
+ export { canAgentChangeInboxItem as $, fallbackShortTitle as $a, snoozeTimerTrigger as $c, juniorConversationParticipants as $d, runNonInteractiveCommand as $i, registeredEventMatchSchema as $l, resolveEventMentions as $n, isConversationDeliveryPaused as $o, resolveTurnResumeRouting as $r, SYSTEM_IDENTITY_ID as $s, completeConversationWork as $t, findProviderError as $u, setFirstConversationLocation as A, AutomationConflictError as Aa, inboxItemTitle as Ac, juniorTurnOutbox as Ad, SLACK_USER_MENTION_RE as Ai, instructionAuthor as Al, canJoinTurn as An, getWatch as Ao, readMemberParticipants as Ar, getFilePermalink as As, injectContinuationToolName as At, transcribeFromUrl as Au, conversationRangeColumns as B, readAutomationExecutions as Ba, readAvatarFetch as Bc, questionSearchDocument as Bd, createPluginState as Bi, EVENT_AUTHOR_ID as Bl, pushInboxSnoozeWakes as Bn, verifyEventAutomationCredentialSubject as Bo, QUEUE_SIGNATURE_MAX_AGE_MS as Br, withSlackRetries as Bs, setTodoStatusByUser as Bt, claudeMaxImageSize as Bu, conversationSlackTenantId as C, admitEventAutomationRun as Ca, listReplyActionItems as Cc, sameDestination as Cd, guardedCosineDistance as Cf, postSlackEphemeralMessage as Ci, rankSearchMatches as Cl, isFinalAttempt as Cn, cancelSubscriptions as Co, leaveEndsAccess as Cr, listPushSubscriptions as Cs, getPlugins as Ct, embedConversationQuery as Cu, createSqlStore as D, listAutomationVersions as Da, updateInboxItemContent as Dc, listedConversation as Dd, uploadFilesToConversation as Di, deliversFinalText as Dl, releaseInboundMessage as Dn, createWatch as Do, conversationIsMemberRoot as Dr, isPausedBySlack as Ds, validatePlugins as Dt, completeText as Du, latestUserMessageQuery as E, automationVersionOf as Ea, takeInboxItem as Ec, spaceLeadIds as Ed, unfurlSlackLinks as Ei, canMoveToSpace as El, pruneActiveConversation as En, createTimerWatch as Eo, readableSlackTeamId as Er, savePushSubscription as Es, setPlugins as Et, completeObject as Eu, destinationUpsertFromDestination as F, linkAutomationRunConversation as Fa, subjectKindPlugin as Fc, juniorTodos as Fd, slackMentionedUserIds as Fi, postsRunNotices as Fl, readInboundMessageSender as Fn, turnEvents as Fo, verifyConversationQueueMessage as Fr, isDmChannel as Fs, CHILD_AGENT_KINDS as Ft, readServedProviders as Fu, conversationTurnFailedSql as G, refreshAutomationLastRun as Ga, clearInboxWakeReasons as Gc, juniorStats as Gd, createPluginConversationEvents as Gi, isEventConversationMessage as Gl, SLACK_INBOX_ITEM_VIEW_ID as Gn, JUNIOR_THREAD_STATE_TTL_MS as Go, buildSentryEventUrl as Gr, findUserByEmail as Gs, beginConversationResume as Gt, readImageDimensions as Gu, conversationIsActiveSql as H, readAutomationRuns as Ha, userAvatarUrlsFromIdentities as Hc, automationFuzzyTitle as Hd, createPluginEmbedder as Hi, EVENT_SYSTEM_ACTOR as Hl, resolveSlackInboxItemCardConversationId as Hn, verifySlackDirectCredentialSubject as Ho, verifyQueueMessage as Hr, getWorkspaceTeamId as Hs, appendAndEnqueueExclusiveInboundMessage as Ht, estimateRequestOverheadTokens as Hu, upsertDestination as I, readAutomationExecutionByConversationId as Ia, subjectTodo as Ic, todoFuzzyTitle as Id, wrapBareSlackUserIds as Ii, promptModeTurnTools as Il, isEventMailboxMetadata as In, bindEventAutomationCredentialSubject as Io, ConversationQueueMessageRejectedError as Ir, isSlackRequestTimeout as Is, PARENT_AGENT_TARGET as It, saveEnabledProviders as Iu, conversationKindFromRow as J, usdToMicroUsd as Ja, inboxItemSnoozedBy as Jc, juniorInboxItemConversations as Jd, createSandboxCapability as Ji, describeRegisteredEventTrigger as Jl, parseSlackInboxItemFormTarget as Jn, subjectKey as Jo, annotationKeyDigest as Jr, readIdentityById as Js, claimConversationAttempt as Jt, hasCompactedConversationContext as Ju, conversationWaitsOnUserSql as K, microUsdSql as Ka, deleteExpiredInboxSnoozes as Kc, inboxItemFuzzyTitle as Kd, renderPluginConversationEvent as Ki, CORE_EVENT_NAMESPACE as Kl, buildSlackInboxItemModal as Kn, codeChangeSubjectProvider as Ko, formatSentryEventReference as Kr, listAdminUsersFromSql as Ks, cancelHumanFacingPendingMessages as Kt, gatewayRoutingAttributes as Ku, parseSessionSource as L, readAutomationExecutionStatusDays as La, hasUserPhoto as Lc, todoSearchDocument as Ld, applyPluginFormatMarkdown as Li, remindsNoReplyForChildStatus as Ll, createSlackInboxItemToolServices as Ln, bindScheduledAutomationCredentialSubject as Lo, conversationQueueMessageSchema as Lr, normalizeSlackConversationId as Ls, agentNameSchema as Lt, cacheKeyPrefix as Lu, locationSchema as M, requireAutomationRevision as Ma, INBOX_SUBJECT_KINDS as Mc, juniorSnapshots as Md, formatSlackLink as Mi, isThread as Ml, isAttemptInterrupt as Mn, listConversationsWithWatches as Mo, viewerMarksFromParticipant as Mr, getSlackClient as Ms, makeStructuredToolOutput as Mt, GEN_AI_PROVIDER_NAME as Mu, claimProviderConversation as N, emptyAutomationRunWindows as Na, questionLinks as Nc, juniorWorkspaceRepos as Nd, normalizeSlackStatusText as Ni, isTopLevel as Nl, selectAttemptMessages as Nn, listWatches as No, getVercelConversationWorkQueue as Nr, isConversationChannel as Ns, findChildAgentConversationId as Nt, GEN_AI_SERVER_ADDRESS as Nu, withConversationMutationLock as O, readAutomationVersion as Oa, inboxItemAnswer as Oc, notLeadConversation as Od, slackEntitySchema as Oi, dispatchInstructionsInvokeSkills as Ol, traceContextSchema as On, deliverWatch as Oo, conversationIsNotUnsubscribedRoot as Or, SlackActionError as Os, apiRoutePrefix as Ot, generateImages as Ou, getConversationIdByProviderConversation as P, existingConversationId as Pa, subjectKindLabel as Pc, juniorWorkspaces as Pd, slackMention as Pi, parentResultActor as Pl, readParentMessage as Pn, takeDueTimerWatches as Po, resolveConversationWorkTopic as Pr, isConversationScopedChannel as Ps, getAgentBinding as Pt, readEnabledProviders as Pu, canActOnInboxItem as Q, syncAutomationAlerts as Qa, snoozeInboxItems as Qc, juniorConversationReadPositions as Qd, buildNonInteractiveShellScript as Qi, hasEventCatalogEntries as Ql, sendSlackReply as Qn, canPauseConversationDelivery as Qo, resolveConversationRouting as Qr, updateViewerDisplayName as Qs, completeConversationStop as Qt, createProviderError as Qu, conversationCostOf as R, readAutomationExecutionStatusHours as Ra, identityAvatarUrl as Rc, juniorQuestions as Rd, getPluginUserPromptContributions as Ri, turnBehavior as Rl, createInboxItemShow as Rn, bindSlackDirectCredentialSubject as Ro, isConversationQueueMessageRejectedError as Rr, readPrivateSlackFile as Rs, spawnChildAgentInputSchema as Rt, createCache as Ru, setArchivedAt as S, setEventAutomationStatus as Sa, insertInboxItem as Sc, requireSlackDestination as Sd, juniorDestinations as Sf, openSlackModal as Si, prefixRank as Sl, hasRunnableConversationWork as Sn, starterWatchId as So, createConversationAccessReader as Sr, deletePushSubscription as Ss, inboxItemVisibility as St, createConversationEmbedder as Su, lastMessageAtSql as T, automationDefinition as Ta, searchInboxItems as Tc, rootSpaceIdSql as Td, removeReactionFromMessage as Ti, fuseRankedLists as Tl, moveIdleConversationDestination as Tn, collectEventMatchKeys as To, readConversationAccessRows as Tr, saveNotificationSchedule as Ts, registry_exports as Tt, completeDecision as Tu, conversationLastTurnOutcomeSql as U, readAutomationTitlesByConversationId as Ua, userAvatarUrlsFromJoinedPhotos as Uc, automationSearchDocument as Ud, createPluginModel as Ui, eventBotAuthorId as Ul, syncInboxItemSlackCards as Un, verifyTimerWatchCredentialSubject as Uo, getQueueProvider as Ur, runWithWorkspaceTeamId as Us, appendAndEnqueueInboundMessage as Ut, estimateTextTokens as Uu, conversationUsageCostExpr as V, readAutomationRowStats as Va, readUserAvatarUrls as Vc, juniorAutomationRuns as Vd, createPluginDecider as Vi, EVENT_MESSAGE_AUTHOR as Vl, runInboxItemPushTimers as Vn, verifyScheduledAutomationCredentialSubject as Vo, signQueueMessage as Vr, sleep$2 as Vs, ackMessages as Vt, estimateMessagesTokens as Vu, conversationStatusSql as W, recordAutomationExecution as Wa, SNOOZE_TIMER_EVENT_TYPE as Wc, juniorAutomations as Wd, createPluginModelCostRecorder as Wi, isEventAuthorId as Wl, findSlackThreadOwnerId as Wn, updateTimerIndex as Wo, buildSentryConversationUrl as Wr, createPluginUsers as Ws, appendInboundMessage as Wt, textCharsForTokens as Wu, hasUnexpiredAuthorizationRequest as X, AUTOMATION_ALERT_STEPS as Xa, readViewerInboxSnoozes as Xc, juniorLocationConfigurations as Xd, withPluginHookSpan as Xi, eventNamespaceSchema as Xl, parseSlackUserInputSubmission as Xn, codeRepositoryUrl as Xo, runWithSlackInstallation as Xr, resolveViewerUser as Xs, clearConsumedConversationWake as Xt, ProviderError as Xu, awaitsAuthorizationFrom as Y, usdToMicroUsdUnbiased as Ya, listFiringInboxSnoozeTriggers as Yc, juniorInboxItems as Yd, pluginConfigValues as Yi, eventGuidance as Yl, safeLinkUrl as Yn, codeChangeUrl as Yo, decodeAnnotationRef as Yr, readViewerAvatarUrl as Ys, claimInboundMessage as Yt, isCompactionSummaryText as Yu, treeAwaitsAuthorization as Z, AUTOMATION_ALERT_STEP_FIELD_ID as Za, settleInboxSnoozes as Zc, juniorAgentBindings as Zd, buildCommandScript as Zi, eventWatchUnavailable as Zl, resolveSlackReplyTarget as Zn, linkedCodeProviders as Zo, verifySlackSignature as Zr, setUserAdminFromSql as Zs, clearExpiredConversationLease as Zt, createAssistantProviderError as Zu, unseenEvents as _, findMatchingEventAutomations as _a, INBOX_ITEM_REPLIED_REASON as _c, rootConversationIsArchived as _d, juniorSpaces as _f, notifyAutomationBlocked as _i, searchTypedMemories as _l, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as _n, workspaceSnapshotWatch as _o, canAccessConversation as _r, defaultTimezone as _s, questionSubject as _t, eventExcerpt as _u, getDb as a, deleteScheduledAutomation as aa, findSlackUserByPrimaryEmail as ac, JUNIOR_NATIVE_EVENT_NAMESPACE as ad, juniorTurns as af, getDispatchIdForConversation as ai, getDashboardSettingsLink as al, getConversationWorkState as an, resolveAssignee as ao, createVercelPluginTaskCallback as ar, listConversationAnnotationsById as as, inboxItemForUser as at, ToolInputError as au, conversationDescendants as b, parseEventAutomationRow as ba, getInboxItem as bc, touchConversationDetail as bd, slackPersonSearchDocument as bf, getSlackMessagePermalink as bi, fuzzyRank as bl, deferConversationMove as bn, isAgentResourceType as bo, canReadConversation as br, lookupSlackUser as bs, requireInboxItemLinks as bt, isEventEmbeddingsEnabled as bu, pendingMigrations as c, readScheduledAutomation as ca, upsertLinkedIdentity as cc, conversationNoteEvent as cd, codeChangeSearchDocument as cf, getDispatchTurnId as ci, isDashboardLink as cl, recordAttemptFailure as cn, SLACK_EVENT_NAMESPACE as co, sendVercelPluginTask as cr, conversationSubtreeColumns as cs, inboxItemPlugin as ct, embedConversationEvents as cu, createSqlConversationEventStore as d, scheduledRunId as da, countInboxItemsNeedingUserBySubject as dc, agentTurnCostUsd as dd, juniorCodeRepositories as df, listPendingDispatchMailboxAppends as di, projectConversationMessages as dl, requestAnotherSlice as dn, slackChannelMessageReplyThreadTs as do, createPluginCodeChanges as dr, writeConversationMetadata as ds, inboxItemVisibleTo as dt, lexemesSql as du, createPluginCache as ea, resolveActorIdentityId as ec, getProviderErrorAttributes as ed, juniorConversationEventLexemes as ef, buildDispatchId as ei, unsnoozeInboxRow as el, deadLetterAttempt as en, generateShortTitle as eo, createPluginEventPublisher as er, pauseConversationDelivery as es, canAnswerInboxItem as et, registeredEventTriggerProblems as eu, eventFromRow as f, withScheduledAutomationLock as fa, inboxItemsNeedingUserVersionQuery as fc, agentTurnTotalTokens as fd, juniorAttachmentUploads as ff, markDispatchAwaitingResume as fi, REVALIDATED_READ_PATHS as fl, requestConversationWork as fn, slackChannelMessageRunsAutomation as fo, createPluginConversationEventStats as fr, isPublicConversation as fs, isAutomationAlertItem as ft, searchedEventTextSql as fu, readEventCursor as g, deleteEventAutomation as ga, closeReadReplyNotice as gc, resolveRootConversationId as gd, juniorSpaceConfigurations as gf, markDispatchRunning as gi, memoryDb as gl, takePendingEventMessages as gn, workspaceSnapshotFinishedEvent as go, createPluginInboxItems as gr, resolveNotificationTimezone as gs, itemNeedsUser as gt, callsToolSql as gu, insertEventRows as h, createEventAutomation as ha, closeHandledReplyNotices as hc, isLeadConversation as hd, juniorConversations as hf, markDispatchFailed as hi, revalidateContent as hl, stopConversationWork as hn, WORKSPACE_SNAPSHOT_READY_EVENT as ho, PLUGIN_CHOICE_FIELD_ID as hr, sendPushNotificationToUser as hs, isPluginInboxItem as ht, SEARCHABLE_EVENT_TYPES as hu, getConversationStore as i, createScheduledAutomation as ia, findLinkedSlackUser as ic, getGatewayApiKey as id, juniorConversationEvents as if, getDispatchConversationId as ii, getDashboardPersonLink as il, getConversation as in, automationCreatorUserId as io, startedTaskDefinition as ir, listConversationAnnotations as is, inboxItemAddedByAutomation as it, requireValidEventTrigger as iu, startLocationThread as j, automationRevision as ja, itemQuestion as jc, juniorTurnInbox as jd, escapeSlackMrkdwnText as ji, isPersonInput as jl, canShareTurn as jn, isQuietEvent as jo, rootVisibleToViewer as jr, getHeaderString as js, juniorToolOutputSchema as jt, NoAudioError as ju, locationFromRow as k, sameDefinitionValue as ka, inboxItemRequest as kc, topLevelConversation as kd, slackExternalRefIdSchema as ki, hasConversationMetadata as kl, withIdleConversation as kn, findMatchingWatches as ko, conversationPinnedForUser as kr, downloadPrivateSlackFile as ks, coreRegistrations as kt, searchWeb as ku, readMigrationRecords as l, saveScheduledAutomation as la, readCachedLinkedHandle as lc, renderJuniorNativeConversationEvent as ld, codeRepositorySearchDocument as lf, getPluginDispatchProjection as li, parseDashboardConversationLink as ll, recordConversationRetry as ln, requireSlackChannelMessageScope as lo, queueCallback as lr, conversationSearchVector as ls, inboxItemReaderForUser as lt, eventIndexLockKey as lu, deleteMessageLinks as m, collectEventAutomationMatchKeys as ma, waitingConversationIdsQuery as mc, hasAgentTurnUsage as md, juniorMessageAttachments as mf, markDispatchCompleted as mi, contentVersionHeaders as ml, steerWebPendingMessages as mn, WORKSPACE_SNAPSHOT_FAILED_EVENT as mo, createPluginConversationChanges as mr, readWebPushConfig as ms, isOnlyAssignee as mt, storeConversationEventLexemes as mu, getConversationEventStore as n, truncateStatusText as na, deleteProviderIdentityForSlackUser as nc, isProviderRefusal as nd, juniorConversationEmbeddings as nf, confirmDispatchMailboxAppend as ni, getDashboardInboxItemLink as nl, dropPendingMessages as nn, EVERYONE_ASSIGNEE as no, getPluginRoutes as nr, searchConversations as ns, canUserReadInboxItem as nt, registeredResourceTypeSchema as nu, getSqlExecutor as o, listScheduledAutomationsForTeam as oa, findUserByVerifiedEmails as oc, agentsInstructionsUpdatedEvent as od, juniorApiTokens as of, getDispatchInputMessageId as oi, getDashboardSpaceLink as ol, getConversationWorkStates as on, resolveAssignees as oo, pluginTaskId as or, conversationAncestorsOrSelf as os, inboxItemNeedsInput as ot, isToolInputError as ou, copyMessageLinks as p, blockEventAutomation as pa, listWaitingConversations as pc, agentTurnUsageSchema as pd, juniorAttachments as pf, markDispatchBlocked as pi, contentVersion as pl, startConversationWork as pn, slackChannelMessageTrigger as po, createPluginTurnEventReader as pr, resolveRootVisibility as ps, isInboxItemForEveryone as pt, seqIn as pu, executionIsActive as q, microUsdToUsd as qa, inboxItemInRow as qc, inboxItemSearchDocument as qd, basePluginContext as qi, automationEventCatalog as ql, parseSlackInboxItemClick as qn, readSubjectLinks as qo, renderSlackObjectCard as qr, readActorIdentity as qs, checkInConversationWork as qt, COMPACTION_SUMMARY_PREFIX as qu, getConversationMessageSearchStore as r, blockScheduledAutomation as ra, deleteProviderIdentityForUser as rc, isProviderRetryError as rd, juniorConversationMetrics as rf, createOrGetDispatch as ri, getDashboardLinkFilter as rl, ensureConversationWake as rn, activeParticipantUserIds as ro, createPluginTaskStarter as rr, createPluginAnnotations as rs, inboxItemAddedByAnyAutomation as rt, requireEventIdentifier as ru, createJuniorSqlExecutor as s, parseScheduledAutomationRow as sa, recordGoogleSignIn as sc, authenticationLinkedEvent as sd, juniorConversationAnnotations as sf, getDispatchRecord as si, getDashboardTaskLink as sl, listActiveConversationIds as sn, getEventCatalog as so, pluginTaskParamsSchema as sr, conversationSubtree as ss, inboxItemOwnedByConversation as st, EVENT_INDEX_LOCK_TTL_MS as su, db_exports as t, getConfigDefaults as ta, saveActorAvatar as tc, getProviderErrorUserMessage as td, juniorConversationEventEmbeddings as tf, claimDispatchMailboxAppend as ti, getDashboardConversationLink as tl, drainConversationMailbox as tn, resolveTaskTitle as to, getPluginApiRoutes as tr, resumeConversationDelivery as ts, canReadInboxItem as tt, registeredEventTypeSchema as tu, isPostgresErrorCode as u, saveScheduledAutomationInLock as ua, readCachedUserByEmail as uc, addAgentTurnUsage as ud, juniorCodeChanges as uf, isTerminalDispatchStatus as ui, parseDashboardPersonLink as ul, releaseConversationWork as un, slackChannelMessageEvent as uo, getTurnRequestDeadline as ur, readConversationMetadata as us, inboxItemReaderForUserInConversation as ut, indexEndedTurnEvents as uu, withConversationEventLock as v, getEventAutomation as va, closeInboxItem as vc, conversationDetailTouch as vd, juniorIdentities as vf, addReactionToMessage as vi, parseTypedQuery as vl, CONVERSATION_WORK_STALE_ENQUEUE_MS as vn, AGENT_RESOURCE_TYPE as vo, canAddConversationMessages as vr, findActorTimezone as vs, readInboxItemAgentScope as vt, excerptTerms as vu, loadConversationSlackTenantIds as w, eventAutomationRunLimitReason as wa, ownerConversationId as wc, isLeadSql$1 as wd, juniorArtifacts as wf, postSlackMessage as wi, scoredSearchMatches as wl, isInvalidConversationRecordError as wn, cancelWatch as wo, readConversationAccessFromSql as wr, readNotificationSchedule as ws, getRegistrations as wt, storeConversationEmbedding as wu, readConversationTrees as x, saveEventAutomation as xa, getOpenInboxItemBySubject as xc, createSlackDestination as xd, juniorUsers as xf, openSlackDirectMessage as xi, prefixMatch as xl, hasConversationStop as xn, publishAgentUpdate as xo, conversationAccessFromRows as xr, lookupSlackUserNames as xs, inboxItemOwnerConversationId as xt, backfillConversationEmbeddings as xu, conversationAncestors as y, listDeletedEventAutomationsCreatedBy as ya, dismissOpenInboxItems as yc, nextDetailVersion as yd, slackPersonPredicate as yf, deleteSlackMessage as yi, fuzzyMatch as yl, countPendingConversationMessages as yn, agentWatch as yo, canInviteToConversation as yr, resolveUserTimezone as ys, requireInboxItemAssignees as yt, storedMessageJson as yu, conversationAggregateColumns as z, readAutomationExecutionSummaries as za, parseAvatarUrl as zc, questionFuzzyTitle as zd, pluginMcpContext as zi, watcherStartedConversation as zl, pushConversationInboxItemsNow as zn, createSlackDirectCredentialSubject as zo, nudgeIdempotencyKey as zr, streamPrivateSlackFile as zs, listTodos as zt, requestPrefixAttributes as zu };