@sentry/junior 0.238.1 → 0.240.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 (61) hide show
  1. package/dist/{admin-leAJ2k0P.js → admin-D6fRPRgC.js} +1 -1
  2. package/dist/{agent-hooks-p3UA9FI1.js → agent-hooks-JFbgedMZ.js} +116 -10
  3. package/dist/{agent-runner-DjQSEVuD.js → agent-runner-0IjJxsL1.js} +60 -121
  4. package/dist/api/schema.d.ts +43 -4
  5. package/dist/api/schema.js +2 -2
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +21 -20
  8. package/dist/{app-FB2hmHpZ.d.ts → app-MEd7wbF0.d.ts} +1 -1
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +24 -23
  11. package/dist/{automation-CrQGQ2MT.js → automation-B5_c8hEb.js} +2 -253
  12. package/dist/{briefs-mzUaJkBX.js → briefs-BGWTp-nz.js} +2 -2
  13. package/dist/cadence-D00SCzT1.js +256 -0
  14. package/dist/{catalog-runtime-xq-njrMs.js → catalog-runtime-DdigNl7s.js} +1 -1
  15. package/dist/{checkpoint-C37Xgtj-.js → checkpoint-C1ZnSz7r.js} +15 -11
  16. package/dist/cli/chat.js +12 -12
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +3 -3
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-BZdqKg6S.js → client-Cn73E7br.js} +2 -2
  24. package/dist/{config-CGK_VplU.js → config-B0S86yw9.js} +2 -2
  25. package/dist/{conversation-privacy-Ci3QLNOb.js → conversation-privacy-BKlX7D_R.js} +1 -1
  26. package/dist/{credential-sync-BBeYpK4k.js → credential-sync-DeNQm7st.js} +14 -14
  27. package/dist/{db-CWZP77Ex.d.ts → db-Ca9Nt5ci.d.ts} +1 -1
  28. package/dist/{executor-DmIad4GI.js → executor-BQ-A5nov.js} +2 -2
  29. package/dist/{images-1xUjTHGf.js → images-C7OKd6uy.js} +2 -2
  30. package/dist/instrumentation.js +2 -2
  31. package/dist/{job-queue-CXpx6KfD.js → job-queue-DgXLqoeB.js} +1 -1
  32. package/dist/{logging-Bne7JUXI.js → logging-BSNF167N.js} +1 -1
  33. package/dist/nitro.d.ts +1 -1
  34. package/dist/nitro.js +3 -3
  35. package/dist/{oauth-authorization-O8N3knp9.js → oauth-authorization-BM7g61od.js} +1 -1
  36. package/dist/{oauth-callback-server-Cb-HPZPS.js → oauth-callback-server-Dw-BwI6x.js} +2 -2
  37. package/dist/{pending-auth-C6w4Gwve.js → pending-auth-Chn_EA1_.js} +2 -2
  38. package/dist/{profile-DIcHBAxe.js → profile-3t9H_IwL.js} +4 -4
  39. package/dist/{registry-VSrEYeaD.js → registry-DLZlAhdP.js} +1 -1
  40. package/dist/{resolve-BkpWmZgN.js → resolve-9_cIPQsq.js} +2 -2
  41. package/dist/{runner-52ezCnZF.js → runner-C_eUbFyp.js} +9 -9
  42. package/dist/{sandbox-egress-signals-Cmhf3P6Y.js → sandbox-egress-signals-C1ycxTNA.js} +1 -1
  43. package/dist/{schema-CxWAN2zq.js → schema-C4XwHTY4.js} +1 -1
  44. package/dist/{skills-PHvy-ZgH.js → skills-Dqgjr_Tl.js} +2 -2
  45. package/dist/{spawn-CY34_HCm.js → spawn-BfEr3t7b.js} +2 -2
  46. package/dist/{store-BxxbxBlm.d.ts → store-DoewL5mG.d.ts} +0 -7
  47. package/dist/{task-queue-B9uJqkal.js → task-queue-CuFZDOXn.js} +3 -3
  48. package/dist/{task-runner-BZUoctJ1.js → task-runner-c7gwV8dj.js} +10 -10
  49. package/dist/{thread-state-SnFcB9Rk.js → thread-state-exTu-G1w.js} +6 -6
  50. package/dist/{turn-failure-response-CrSc1Vtn.js → turn-failure-response-DFp99ziF.js} +8 -8
  51. package/dist/{turn-lifecycle-D49hJbjm.js → turn-lifecycle-C4TjuOzG.js} +1 -1
  52. package/dist/{turn-session-routing-cMvumCLK.js → turn-session-routing-Vpg8jUD1.js} +1 -1
  53. package/dist/{validation-DsLyiOfn.js → validation-D2lULEG9.js} +1 -1
  54. package/dist/{version-Dayi_ng2.js → version-BjBMCc2o.js} +1 -1
  55. package/dist/version.js +1 -1
  56. package/dist/{viewer-DF3HTfW5.js → viewer-XE3nFqKM.js} +9 -11
  57. package/dist/{web-authorization-Dg_R1tMc.js → web-authorization-8E8IrWOj.js} +6 -6
  58. package/dist/{web-input-qVi8134S.js → web-input-DF4GGJrf.js} +28 -44
  59. package/dist/{work-BbcghZZp.js → work-Dt_JjfbX.js} +7 -7
  60. package/dist/{worker-B-uRQzKw.js → worker-BrbnLmD3.js} +5 -5
  61. package/package.json +5 -5
@@ -1,4 +1,4 @@
1
- import { a as setUserAdminFromSql, d as getDb, n as listAdminUsersFromSql } from "./viewer-DF3HTfW5.js";
1
+ import { a as setUserAdminFromSql, d as getDb, n as listAdminUsersFromSql } from "./viewer-XE3nFqKM.js";
2
2
  import { CLI_USAGE } from "./cli/run.js";
3
3
  //#region src/cli/admin.ts
4
4
  /**
@@ -1,18 +1,19 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { a as embedTexts, r as completeObject } from "./client-BZdqKg6S.js";
3
- import { I as isRecord$1, a as extractGenAiUsageSummary, d as logException, f as logInfo, p as logWarn, v as setSpanAttributes, w as withSpan, y as setSpanStatus } from "./logging-Bne7JUXI.js";
2
+ import { a as embedTexts, r as completeObject } from "./client-Cn73E7br.js";
3
+ import { I as isRecord$1, a as extractGenAiUsageSummary, d as logException, f as logInfo, p as logWarn, v as setSpanAttributes, w as withSpan, y as setSpanStatus } from "./logging-BSNF167N.js";
4
4
  import { a as getClient$1 } from "./sentry-CgWZM_kV.js";
5
- import { t as canExposeConversationPayload } from "./conversation-privacy-Ci3QLNOb.js";
6
- import { i as getChatConfig, n as botConfig, o as getSlackBotToken } from "./config-CGK_VplU.js";
5
+ import { t as canExposeConversationPayload } from "./conversation-privacy-BKlX7D_R.js";
6
+ import { i as getChatConfig, n as botConfig, o as getSlackBotToken } from "./config-B0S86yw9.js";
7
7
  import { r as defaultModelId } from "./model-profile-BwU8mqwD.js";
8
8
  import { d as parseSlackTeamId, g as parseSlackMessageTs, i as isActorUserId, o as parseActorUserId, u as parseSlackChannelReferenceId } from "./actor-BTtLaeWy.js";
9
- import { c as getConversationEventStore, d as getDb, f as getSqlExecutor, h as createSqlStore, i as resolveViewerUser, r as readActorIdentity, w as hasAgentTurnUsage } from "./viewer-DF3HTfW5.js";
9
+ import { O as readUserTimezone, T as hasAgentTurnUsage, c as getConversationEventStore, d as getDb, f as getSqlExecutor, h as createSqlStore, i as resolveViewerUser, k as saveUserTimezone, r as readActorIdentity } from "./viewer-XE3nFqKM.js";
10
10
  import { n as juniorDestinations } from "./destinations-BeBiJeEM.js";
11
- import { C as juniorCodeChanges, D as juniorConversations, O as juniorIdentities, S as juniorConversationAnnotations, T as juniorAttachments, _ as juniorConversationBriefs, b as juniorConversationEvents, h as juniorConversationParticipants, i as juniorWorkspaces, k as juniorUsers, n as juniorSnapshots, r as juniorWorkspaceRepos, w as juniorCodeRepositories } from "./executor-DmIad4GI.js";
11
+ import { C as juniorCodeChanges, D as juniorConversations, O as juniorIdentities, S as juniorConversationAnnotations, T as juniorAttachments, _ as juniorConversationBriefs, b as juniorConversationEvents, h as juniorConversationParticipants, i as juniorWorkspaces, k as juniorUsers, n as juniorSnapshots, r as juniorWorkspaceRepos, w as juniorCodeRepositories } from "./executor-BQ-A5nov.js";
12
12
  import { o as decodeStoredConversationEvent } from "./history-BLTUgFYO.js";
13
- import { p as credentialSubjectSchema } from "./registry-VSrEYeaD.js";
13
+ import { p as credentialSubjectSchema } from "./registry-DLZlAhdP.js";
14
14
  import { B as parseBriefInput, C as conversationReportEventSchema, N as readMessageAttachments, W as readMessageCardRefs, z as conversationBriefSchema } from "./conversation-DwD-vquD.js";
15
- import { C as getDefaultRedisStateAdapterFor, N as SANDBOX_WORKSPACE_ROOT, k as sleep$1, l as isSandboxMissingError, n as hash, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand } from "./profile-DIcHBAxe.js";
15
+ import { C as getDefaultRedisStateAdapterFor, N as SANDBOX_WORKSPACE_ROOT, k as sleep$1, l as isSandboxMissingError, n as hash, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand } from "./profile-3t9H_IwL.js";
16
+ import { i as isValidTimeZone } from "./cadence-D00SCzT1.js";
16
17
  import { n as briefEntriesFromReportEvents, s as generateBrief, t as BRIEF_PROMPT } from "./prompt-CMU-B4FA.js";
17
18
  import { AsyncLocalStorage } from "node:async_hooks";
18
19
  import { z } from "zod";
@@ -142,6 +143,96 @@ function renderJuniorNativeConversationEvent(args) {
142
143
  return presentation === void 0 ? void 0 : conversationEventPresentationSchema.parse(presentation);
143
144
  }
144
145
  //#endregion
146
+ //#region src/chat/slack/user.ts
147
+ const slackUserInfoSchema = z.object({
148
+ ok: z.literal(true),
149
+ user: z.object({
150
+ name: z.string().nullish(),
151
+ tz: z.string().nullish(),
152
+ profile: z.object({
153
+ email: z.string().nullish(),
154
+ real_name: z.string().nullish()
155
+ }).optional()
156
+ })
157
+ });
158
+ const USER_CACHE_TTL_MS = 3e5;
159
+ const userCache = /* @__PURE__ */ new Map();
160
+ function userCacheKey(teamId, userId) {
161
+ return `${teamId}:${userId}`;
162
+ }
163
+ function readFromCache(teamId, userId) {
164
+ const hit = userCache.get(userCacheKey(teamId, userId));
165
+ if (!hit) return null;
166
+ if (hit.expiresAt < Date.now()) {
167
+ userCache.delete(userCacheKey(teamId, userId));
168
+ return null;
169
+ }
170
+ return hit.value;
171
+ }
172
+ function writeToCache(teamId, userId, value) {
173
+ userCache.set(userCacheKey(teamId, userId), {
174
+ value,
175
+ expiresAt: Date.now() + USER_CACHE_TTL_MS
176
+ });
177
+ }
178
+ /** Fetch Slack user profile info with in-memory TTL cache to avoid repeated API calls. */
179
+ async function lookupSlackUser(teamId, userId) {
180
+ if (!teamId || !userId) return null;
181
+ const cached = readFromCache(teamId, userId);
182
+ if (cached) return cached;
183
+ const token = getSlackBotToken();
184
+ if (!token) return null;
185
+ try {
186
+ const response = await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(userId)}`, { headers: { authorization: `Bearer ${token}` } });
187
+ if (!response.ok) {
188
+ logWarn("slack.user.lookup.failed", {
189
+ "enduser.id": userId,
190
+ "app.slack.team_id": teamId,
191
+ "http.response.status_code": response.status
192
+ });
193
+ return null;
194
+ }
195
+ const parsed = slackUserInfoSchema.safeParse(await response.json());
196
+ if (!parsed.success) return null;
197
+ const payload = parsed.data;
198
+ const result = {
199
+ userName: payload.user.name?.trim() || void 0,
200
+ fullName: payload.user.profile?.real_name?.trim() || void 0,
201
+ email: payload.user.profile?.email?.trim() || void 0,
202
+ timezone: payload.user.tz?.trim() || void 0
203
+ };
204
+ writeToCache(teamId, userId, result);
205
+ return result;
206
+ } catch (error) {
207
+ logWarn("slack.user.lookup.failed", {
208
+ "enduser.id": userId,
209
+ "app.slack.team_id": teamId,
210
+ "exception.message": error instanceof Error ? error.message : String(error)
211
+ });
212
+ return null;
213
+ }
214
+ }
215
+ //#endregion
216
+ //#region src/chat/identities/timezone.ts
217
+ const DEFAULT_TIMEZONE = "America/Los_Angeles";
218
+ /** The install timezone, used when Junior does not know a person's timezone. */
219
+ function defaultTimezone() {
220
+ return process.env.JUNIOR_TIMEZONE?.trim() || DEFAULT_TIMEZONE;
221
+ }
222
+ /**
223
+ * Pick a person's timezone: their Slack profile, then the saved user
224
+ * timezone, then the install default. A valid Slack timezone is saved on the
225
+ * linked user, so later lookups without Slack still find it.
226
+ */
227
+ async function resolveUserTimezone(args) {
228
+ const timezone = (args.slack ? await lookupSlackUser(args.slack.teamId, args.slack.userId) : void 0)?.timezone;
229
+ if (timezone && isValidTimeZone(timezone)) {
230
+ if (args.userId) await saveUserTimezone(args.db, args.userId, timezone, args.nowMs);
231
+ return timezone;
232
+ }
233
+ return (args.userId ? await readUserTimezone(args.db, args.userId) : void 0) ?? defaultTimezone();
234
+ }
235
+ //#endregion
145
236
  //#region src/chat/plugins/annotations.ts
146
237
  function annotationFromRow(row) {
147
238
  const parsed = conversationAnnotationInputSchema.safeParse(row.annotation);
@@ -3639,7 +3730,22 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
3639
3730
  events,
3640
3731
  sandbox,
3641
3732
  state: createPluginState(pluginName),
3642
- users: { resolveActor },
3733
+ users: {
3734
+ resolveActor,
3735
+ async resolveTimezone() {
3736
+ const actor = context.actor;
3737
+ const resolved = await resolveActor();
3738
+ return await resolveUserTimezone({
3739
+ db: getDb(),
3740
+ nowMs: Date.now(),
3741
+ ...actor?.platform === "slack" ? { slack: {
3742
+ teamId: actor.teamId,
3743
+ userId: actor.userId
3744
+ } } : void 0,
3745
+ ...resolved?.user ? { userId: resolved.user.id } : void 0
3746
+ });
3747
+ }
3748
+ },
3643
3749
  workspaces: { async findByRepository(input) {
3644
3750
  return await listWorkspaceNamesByRepository(getDb(), input);
3645
3751
  } }
@@ -4204,4 +4310,4 @@ function createPluginHookRunner(input = {}) {
4204
4310
  };
4205
4311
  }
4206
4312
  //#endregion
4207
- export { verifySlackDirectCredentialSubject as $, getWorkspaceSnapshotBuilder as A, viewerConversationMembership as At, cancelWatch as B, saveObjectAnnotations as Bt, WorkspaceValidationError as C, conversationArchiveTimes as Ct, setWorkspaceSnapshotBuild as D, conversationHasParticipantUser as Dt, setWorkspaceSnapshot as E, conversationHasParticipantEmail as Et, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as F, getSlackFileId as Ft, findMatchingWatches as G, agentsInstructionsUpdatedEvent as Gt, createTimerWatch as H, listConversationAnnotations as Ht, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as I, matchSlackAttachments as It, bindEventAutomationCredentialSubject as J, listWatches as K, authenticationLinkedEvent as Kt, RESOURCE_WATCH_TOOL_SOURCE as L, readAttachmentVisionSummary as Lt, workspaceRepoCheckoutPath as M, readLatestConversationBrief as Mt, resolveChannelCapabilities as N, readConversationEventPage as Nt, SANDBOX_RUNTIME as O, conversationNotArchivedForEmail as Ot, getSlackToolContext as P, buildSentryConversationUrl as Pt, verifyScheduledAutomationCredentialSubject as Q, STOP_WATCHING_TOOL_NAME as R, recordSlackAttachment as Rt, updateWorkspace as S, readConversationAccessFromSql as St, loadSnapshotsForProfile as T, conversationArchivedForUser as Tt, createWatch as U, listConversationAnnotationsById as Ut, collectEventMatchKeys as V, createPluginAnnotations as Vt, deliverWatch as W, JUNIOR_NATIVE_EVENT_NAMESPACE as Wt, bindSlackDirectCredentialSubject as X, bindScheduledAutomationCredentialSubject as Y, verifyEventAutomationCredentialSubject as Z, deleteWorkspace as _, setDashboardConversationLinkOptions as _t, getPluginRoutes as a, getSlackClient as at, listWorkspaces as b, createPluginModel as bt, getPluginTools as c, normalizeSlackConversationId as ct, setPlugins as d, getWorkspaceTeamId as dt, verifyTimerWatchCredentialSubject as et, validatePlugins as f, runWithWorkspaceTeamId as ft, createWorkspace as g, getDashboardTaskLink as gt, setBriefsConfig as h, getDashboardObjectIconLink as ht, getPluginApiRoutes as i, getHeaderString as it, tryWorkspaceRepoCheckoutPath as j, createPluginConversationEvents as jt, deleteWorkspaceSnapshotBuilders as k, conversationNotArchivedForUser as kt, getPluginUserPromptContributions as l, runWithSlackInstallationToken as lt, registration_exports as m, getDashboardConversationLink as mt, applyPluginFormatMarkdown as n, downloadPrivateSlackFile as nt, getPluginSlackConversationLink as o, isConversationScopedChannel as ot, coreTaskRegistrations as p, JUNIOR_THREAD_STATE_TTL_MS as pt, takeDueTimerWatches as q, authenticationUnlinkedEvent as qt, createPluginHookRunner as r, getFilePermalink as rt, getPluginSystemPromptContributions as s, isDmChannel as st, agent_hooks_exports as t, SlackActionError as tt, getPlugins as u, withSlackRetries as ut, getWorkspace as v, createPluginState as vt, invalidateReadySnapshot as w, conversationArchivedForEmail as wt, listWorkspacesByRepository as x, createPluginLogger as xt, getWorkspaceByName as y, createPluginEmbedder as yt, cancelSubscriptions as z, resolveRootVisibility as zt };
4313
+ export { verifySlackDirectCredentialSubject as $, getWorkspaceSnapshotBuilder as A, viewerConversationMembership as At, cancelWatch as B, saveObjectAnnotations as Bt, WorkspaceValidationError as C, conversationArchiveTimes as Ct, setWorkspaceSnapshotBuild as D, conversationHasParticipantUser as Dt, setWorkspaceSnapshot as E, conversationHasParticipantEmail as Et, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as F, getSlackFileId as Ft, findMatchingWatches as G, resolveUserTimezone as Gt, createTimerWatch as H, listConversationAnnotations as Ht, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as I, matchSlackAttachments as It, bindEventAutomationCredentialSubject as J, agentsInstructionsUpdatedEvent as Jt, listWatches as K, lookupSlackUser as Kt, RESOURCE_WATCH_TOOL_SOURCE as L, readAttachmentVisionSummary as Lt, workspaceRepoCheckoutPath as M, readLatestConversationBrief as Mt, resolveChannelCapabilities as N, readConversationEventPage as Nt, SANDBOX_RUNTIME as O, conversationNotArchivedForEmail as Ot, getSlackToolContext as P, buildSentryConversationUrl as Pt, verifyScheduledAutomationCredentialSubject as Q, STOP_WATCHING_TOOL_NAME as R, recordSlackAttachment as Rt, updateWorkspace as S, readConversationAccessFromSql as St, loadSnapshotsForProfile as T, conversationArchivedForUser as Tt, createWatch as U, listConversationAnnotationsById as Ut, collectEventMatchKeys as V, createPluginAnnotations as Vt, deliverWatch as W, defaultTimezone as Wt, bindSlackDirectCredentialSubject as X, authenticationUnlinkedEvent as Xt, bindScheduledAutomationCredentialSubject as Y, authenticationLinkedEvent as Yt, verifyEventAutomationCredentialSubject as Z, deleteWorkspace as _, setDashboardConversationLinkOptions as _t, getPluginRoutes as a, getSlackClient as at, listWorkspaces as b, createPluginModel as bt, getPluginTools as c, normalizeSlackConversationId as ct, setPlugins as d, getWorkspaceTeamId as dt, verifyTimerWatchCredentialSubject as et, validatePlugins as f, runWithWorkspaceTeamId as ft, createWorkspace as g, getDashboardTaskLink as gt, setBriefsConfig as h, getDashboardObjectIconLink as ht, getPluginApiRoutes as i, getHeaderString as it, tryWorkspaceRepoCheckoutPath as j, createPluginConversationEvents as jt, deleteWorkspaceSnapshotBuilders as k, conversationNotArchivedForUser as kt, getPluginUserPromptContributions as l, runWithSlackInstallationToken as lt, registration_exports as m, getDashboardConversationLink as mt, applyPluginFormatMarkdown as n, downloadPrivateSlackFile as nt, getPluginSlackConversationLink as o, isConversationScopedChannel as ot, coreTaskRegistrations as p, JUNIOR_THREAD_STATE_TTL_MS as pt, takeDueTimerWatches as q, JUNIOR_NATIVE_EVENT_NAMESPACE as qt, createPluginHookRunner as r, getFilePermalink as rt, getPluginSystemPromptContributions as s, isDmChannel as st, agent_hooks_exports as t, SlackActionError as tt, getPlugins as u, withSlackRetries as ut, getWorkspace as v, createPluginState as vt, invalidateReadySnapshot as w, conversationArchivedForEmail as wt, listWorkspacesByRepository as x, createPluginLogger as xt, getWorkspaceByName as y, createPluginEmbedder as yt, cancelSubscriptions as z, resolveRootVisibility as zt };
@@ -1,28 +1,29 @@
1
- import { b as getGatewayApiKey, c as hasCompactedConversationContext, d as unwrapCurrentInstruction, f as escapeXml, g as getProviderErrorAttributes, h as findProviderError, i as completeText, l as isCompactionSummaryText, m as createProviderError, n as GEN_AI_SERVER_ADDRESS, o as resolveGatewayModel, p as ProviderError, r as completeObject, s as COMPACTION_SUMMARY_PREFIX, t as GEN_AI_PROVIDER_NAME, u as renderCurrentInstruction, v as isProviderRetryError, x as resolveGatewayCredential, y as MISSING_GATEWAY_CREDENTIALS_ERROR } from "./client-BZdqKg6S.js";
2
- import { C as withLogContext, F as normalizeIdentityEmail, I as isRecord$3, L as toOptionalNumber, R as toOptionalString, a as extractGenAiUsageSummary, b as setTags, c as getLogContextAttributesForSpan, d as logException, f as logInfo, g as serializeGenAiAttribute, i as extractGenAiUsageAttributes, l as getTracePropagationHeaders, m as normalizeGenAiFinishReason, p as logWarn, s as getLogContextAttributes, u as logError, v as setSpanAttributes, w as withSpan, x as summarizeMessageText, y as setSpanStatus } from "./logging-Bne7JUXI.js";
1
+ import { b as getGatewayApiKey, c as hasCompactedConversationContext, d as unwrapCurrentInstruction, f as escapeXml, g as getProviderErrorAttributes, h as findProviderError, i as completeText, l as isCompactionSummaryText, m as createProviderError, n as GEN_AI_SERVER_ADDRESS, o as resolveGatewayModel, p as ProviderError, r as completeObject, s as COMPACTION_SUMMARY_PREFIX, t as GEN_AI_PROVIDER_NAME, u as renderCurrentInstruction, v as isProviderRetryError, x as resolveGatewayCredential, y as MISSING_GATEWAY_CREDENTIALS_ERROR } from "./client-Cn73E7br.js";
2
+ import { C as withLogContext, F as normalizeIdentityEmail, I as isRecord$3, L as toOptionalNumber, R as toOptionalString, a as extractGenAiUsageSummary, b as setTags, c as getLogContextAttributesForSpan, d as logException, f as logInfo, g as serializeGenAiAttribute, i as extractGenAiUsageAttributes, l as getTracePropagationHeaders, m as normalizeGenAiFinishReason, p as logWarn, s as getLogContextAttributes, u as logError, v as setSpanAttributes, w as withSpan, x as summarizeMessageText, y as setSpanStatus } from "./logging-BSNF167N.js";
3
3
  import { m as startInactiveSpan, n as captureMessage, v as withActiveSpan } from "./sentry-CgWZM_kV.js";
4
- import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-Ci3QLNOb.js";
5
- import { i as getChatConfig, n as botConfig, o as getSlackBotToken, v as normalizeSlackEmojiName } from "./config-CGK_VplU.js";
4
+ import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-BKlX7D_R.js";
5
+ import { i as getChatConfig, n as botConfig, v as normalizeSlackEmojiName } from "./config-B0S86yw9.js";
6
6
  import { a as formatModelProfiles, c as profileConfig, i as formatModelProfile, l as TURN_REASONING_LEVELS, n as ModelProfileNotConfiguredError, o as modelIdForProfile, s as modelProfileSchema } from "./model-profile-BwU8mqwD.js";
7
7
  import { a as isUserActor, d as parseSlackTeamId, f as parseSlackUserId, g as parseSlackMessageTs, l as parseSlackChannelId, s as parseStoredSlackActor, u as parseSlackChannelReferenceId } from "./actor-BTtLaeWy.js";
8
- import { D as readUserTimezone, M as parseDestination, O as saveUserTimezone, P as sameDestination$1, b as addAgentTurnUsage, c as getConversationEventStore, d as getDb, f as getSqlExecutor, l as getConversationMessageSearchStore, r as readActorIdentity, u as getConversationStore, w as hasAgentTurnUsage } from "./viewer-DF3HTfW5.js";
8
+ import { F as sameDestination$1, N as parseDestination, T as hasAgentTurnUsage, c as getConversationEventStore, d as getDb, f as getSqlExecutor, l as getConversationMessageSearchStore, r as readActorIdentity, u as getConversationStore, x as addAgentTurnUsage } from "./viewer-XE3nFqKM.js";
9
9
  import { n as juniorDestinations } from "./destinations-BeBiJeEM.js";
10
- import { A as juniorArtifacts, D as juniorConversations, O as juniorIdentities, S as juniorConversationAnnotations, T as juniorAttachments, _ as juniorConversationBriefs, a as juniorSchedulerRuns, f as AGENT_INVOCATION_MAILBOX_STATUSES, l as juniorStats, o as juniorSchedulerTasks, s as juniorAutomationVersions, u as juniorEventAutomations } from "./executor-DmIad4GI.js";
10
+ import { A as juniorArtifacts, D as juniorConversations, O as juniorIdentities, S as juniorConversationAnnotations, T as juniorAttachments, _ as juniorConversationBriefs, a as juniorSchedulerRuns, f as AGENT_INVOCATION_MAILBOX_STATUSES, l as juniorStats, o as juniorSchedulerTasks, s as juniorAutomationVersions, u as juniorEventAutomations } from "./executor-BQ-A5nov.js";
11
11
  import { d as instructionActors, f as instructionProvenanceFor, p as sameActorIdentity, t as KNOWN_CONVERSATION_EVENT_TYPES, u as contextProvenance } from "./history-BLTUgFYO.js";
12
12
  import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-BVvSnQBB.js";
13
- import { a as resolveAuthTokenPlaceholder, c as fetchWithBoundedOAuthErrorBodies, d as credentialContextForActor, f as credentialContextSchema, h as CredentialUnavailableError, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, m as credentialUserSubjectId, o as resolvePluginCommandEnv, p as credentialSubjectSchema, s as OAuthProviderError } from "./registry-VSrEYeaD.js";
14
- import { n as pluginCatalogRuntime } from "./catalog-runtime-xq-njrMs.js";
15
- import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-PHvy-ZgH.js";
16
- import { C as isToolResultError, D as stripRuntimeTurnContext, E as retainRuntimeTurnContext, H as recordAuthorizationRequested, I as loadTurnRoute, K as recordToolExecutionStarted, L as openConversationProjection, M as loadConnectedMcpProviders, N as loadConversationProjection, O as trimTrailingAssistantMessages, R as recordAgentsInstructionsUpdated, S as isContinuablePiBoundary, T as normalizeToolNameFromResult, U as recordGuardianActionReviewed, W as recordMcpProviderConnected, _ as getTerminalAssistantMessages, _t as historyItemFromPiMessage, d as TurnSliceLimitExceededError, f as assertTurnToolCallLimit, g as getPiMessageRole, gt as getAgentContextInputLimitTokens, h as extractAssistantText, ht as getAgentContextCompactionTriggerTokens, k as TURN_CONTEXT_TAG, m as isTurnExecutionLimitExceededError, mt as estimateTextTokens, n as loadTurnCheckpoint, nt as resolveTaskTitle, q as recordTurnRoute, r as saveTurnCheckpoint, t as continuableMessages, tt as fallbackShortTitle, v as getUserMessageInstructionText, vt as piMessageFromHistoryItem, w as isToolResultMessage, x as isAssistantMessage, y as hasRuntimeTurnContext, z as recordAttachmentsDelivered } from "./checkpoint-C37Xgtj-.js";
17
- import { A as getWorkspaceSnapshotBuilder, B as cancelWatch, Bt as saveObjectAnnotations, C as WorkspaceValidationError, D as setWorkspaceSnapshotBuild, E as setWorkspaceSnapshot, F as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, G as findMatchingWatches, H as createTimerWatch, I as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, It as matchSlackAttachments, K as listWatches, L as RESOURCE_WATCH_TOOL_SOURCE, M as workspaceRepoCheckoutPath, N as resolveChannelCapabilities, O as SANDBOX_RUNTIME, P as getSlackToolContext, R as STOP_WATCHING_TOOL_NAME, S as updateWorkspace, T as loadSnapshotsForProfile, U as createWatch, Vt as createPluginAnnotations, W as deliverWatch, _ as deleteWorkspace, at as getSlackClient, b as listWorkspaces, c as getPluginTools, ct as normalizeSlackConversationId, et as verifyTimerWatchCredentialSubject, g as createWorkspace, gt as getDashboardTaskLink, j as tryWorkspaceRepoCheckoutPath, k as deleteWorkspaceSnapshotBuilders, l as getPluginUserPromptContributions, mt as getDashboardConversationLink, n as applyPluginFormatMarkdown, nt as downloadPrivateSlackFile, ot as isConversationScopedChannel, pt as JUNIOR_THREAD_STATE_TTL_MS, r as createPluginHookRunner, rt as getFilePermalink, s as getPluginSystemPromptContributions, st as isDmChannel$1, tt as SlackActionError, u as getPlugins, ut as withSlackRetries, v as getWorkspace, w as invalidateReadySnapshot, xt as createPluginLogger, y as getWorkspaceByName, z as cancelSubscriptions } from "./agent-hooks-p3UA9FI1.js";
13
+ import { a as resolveAuthTokenPlaceholder, c as fetchWithBoundedOAuthErrorBodies, d as credentialContextForActor, f as credentialContextSchema, h as CredentialUnavailableError, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, m as credentialUserSubjectId, o as resolvePluginCommandEnv, p as credentialSubjectSchema, s as OAuthProviderError } from "./registry-DLZlAhdP.js";
14
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DdigNl7s.js";
15
+ import { a as parseSkillInvocation, i as parseSkillFile, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-Dqgjr_Tl.js";
16
+ import { C as isToolResultError, D as stripRuntimeTurnContext, E as retainRuntimeTurnContext, H as recordAuthorizationRequested, I as loadTurnRoute, K as recordToolExecutionStarted, L as openConversationProjection, M as loadConnectedMcpProviders, N as loadConversationProjection, O as trimTrailingAssistantMessages, R as recordAgentsInstructionsUpdated, S as isContinuablePiBoundary, T as normalizeToolNameFromResult, U as recordGuardianActionReviewed, W as recordMcpProviderConnected, _ as getTerminalAssistantMessages, _t as historyItemFromPiMessage, d as TurnSliceLimitExceededError, f as assertTurnToolCallLimit, g as getPiMessageRole, gt as getAgentContextInputLimitTokens, h as extractAssistantText, ht as getAgentContextCompactionTriggerTokens, k as TURN_CONTEXT_TAG, m as isTurnExecutionLimitExceededError, mt as estimateTextTokens, n as loadTurnCheckpoint, nt as resolveTaskTitle, q as recordTurnRoute, r as saveTurnCheckpoint, t as continuableMessages, tt as fallbackShortTitle, v as getUserMessageInstructionText, vt as piMessageFromHistoryItem, w as isToolResultMessage, x as isAssistantMessage, y as hasRuntimeTurnContext, z as recordAttachmentsDelivered } from "./checkpoint-C1ZnSz7r.js";
17
+ import { A as getWorkspaceSnapshotBuilder, B as cancelWatch, Bt as saveObjectAnnotations, C as WorkspaceValidationError, D as setWorkspaceSnapshotBuild, E as setWorkspaceSnapshot, F as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, G as findMatchingWatches, Gt as resolveUserTimezone, H as createTimerWatch, I as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, It as matchSlackAttachments, K as listWatches, L as RESOURCE_WATCH_TOOL_SOURCE, M as workspaceRepoCheckoutPath, N as resolveChannelCapabilities, O as SANDBOX_RUNTIME, P as getSlackToolContext, R as STOP_WATCHING_TOOL_NAME, S as updateWorkspace, T as loadSnapshotsForProfile, U as createWatch, Vt as createPluginAnnotations, W as deliverWatch, Wt as defaultTimezone, _ as deleteWorkspace, at as getSlackClient, b as listWorkspaces, c as getPluginTools, ct as normalizeSlackConversationId, et as verifyTimerWatchCredentialSubject, g as createWorkspace, gt as getDashboardTaskLink, j as tryWorkspaceRepoCheckoutPath, k as deleteWorkspaceSnapshotBuilders, l as getPluginUserPromptContributions, mt as getDashboardConversationLink, n as applyPluginFormatMarkdown, nt as downloadPrivateSlackFile, ot as isConversationScopedChannel, pt as JUNIOR_THREAD_STATE_TTL_MS, r as createPluginHookRunner, rt as getFilePermalink, s as getPluginSystemPromptContributions, st as isDmChannel$1, tt as SlackActionError, u as getPlugins, ut as withSlackRetries, v as getWorkspace, w as invalidateReadySnapshot, xt as createPluginLogger, y as getWorkspaceByName, z as cancelSubscriptions } from "./agent-hooks-JFbgedMZ.js";
18
18
  import { F as isVisionImageMediaType, G as removedCardSchema, L as briefLinkSchema, R as briefOutcomeStatusSchema, z as conversationBriefSchema } from "./conversation-DwD-vquD.js";
19
- import { A as SANDBOX_DATA_ROOT, C as getDefaultRedisStateAdapterFor, D as fenceLock, E as acquireActiveLock, F as sandboxSkillFile, I as sandboxSkillPathResolution, M as SANDBOX_SKILLS_ROOT, N as SANDBOX_WORKSPACE_ROOT, O as withLock, P as sandboxSkillDir, _ as workspaceSnapshotNotReadyUserMessage, a as isAbortError, b as buildNonInteractiveShellScript, c as isSandboxCommandStreamInterruptedError, d as isSnapshottingError, f as throwSandboxOperationError, g as isWorkspaceSnapshotNotReadyError, h as getWorkspaceSnapshotNotReadyError, i as ensureDockerDaemon, j as SANDBOX_REPOS_ROOT, k as sleep$2, l as isSandboxMissingError, m as WorkspaceSnapshotNotReadyError, n as hash, o as isAlreadyExistsError, p as wrapSandboxSetupError, r as isStale, s as isSandboxApiTransientError, t as create, u as isSandboxUnavailableError, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand, y as buildCommandScript } from "./profile-DIcHBAxe.js";
20
- import { n as canReusePendingAuthLink, t as abandonReplacedPendingAuth } from "./pending-auth-C6w4Gwve.js";
21
- import { a as NO_REPLY_MARKER, c as CooperativeTurnYieldError, i as sanitizeAssistantText, l as TurnInputCommitLostError, n as decideReply, o as isNoReplyMarker, p as isTurnInputCommitLostError, r as getAssistantReplyText, t as authorizationId } from "./oauth-authorization-O8N3knp9.js";
19
+ import { A as SANDBOX_DATA_ROOT, C as getDefaultRedisStateAdapterFor, D as fenceLock, E as acquireActiveLock, F as sandboxSkillFile, I as sandboxSkillPathResolution, M as SANDBOX_SKILLS_ROOT, N as SANDBOX_WORKSPACE_ROOT, O as withLock, P as sandboxSkillDir, _ as workspaceSnapshotNotReadyUserMessage, a as isAbortError, b as buildNonInteractiveShellScript, c as isSandboxCommandStreamInterruptedError, d as isSnapshottingError, f as throwSandboxOperationError, g as isWorkspaceSnapshotNotReadyError, h as getWorkspaceSnapshotNotReadyError, i as ensureDockerDaemon, j as SANDBOX_REPOS_ROOT, k as sleep$2, l as isSandboxMissingError, m as WorkspaceSnapshotNotReadyError, n as hash, o as isAlreadyExistsError, p as wrapSandboxSetupError, r as isStale, s as isSandboxApiTransientError, t as create, u as isSandboxUnavailableError, v as getVercelSandboxCredentials, w as getStateAdapter, x as runNonInteractiveCommand, y as buildCommandScript } from "./profile-3t9H_IwL.js";
20
+ import { n as canReusePendingAuthLink, t as abandonReplacedPendingAuth } from "./pending-auth-Chn_EA1_.js";
21
+ import { a as NO_REPLY_MARKER, c as CooperativeTurnYieldError, i as sanitizeAssistantText, l as TurnInputCommitLostError, n as decideReply, o as isNoReplyMarker, p as isTurnInputCommitLostError, r as getAssistantReplyText, t as authorizationId } from "./oauth-authorization-BM7g61od.js";
22
+ import { i as isValidTimeZone, r as getZonedDateTimeParts } from "./cadence-D00SCzT1.js";
22
23
  import { r as EVENT_AUTHOR_ID } from "./prompt-CMU-B4FA.js";
23
- import { a as createSandboxSession, c as postinstall, d as getSandboxResources, i as bindSandboxFileSystem, l as setSnapshotSpanAttributes, n as isMissingError, o as stopSession, r as resolve$1, s as dependencies } from "./resolve-BkpWmZgN.js";
24
- import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-CXpx6KfD.js";
25
- import { A as eventAutomationSchema, D as scheduledRunSchema, E as scheduledAutomationSchema, M as compileScheduleIntent, N as isValidTimeZone$1, O as automationInstructionToolSchema, P as scheduleIntentSchema, R as getZonedDateTimeParts, S as automationVersionSchema, T as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, j as ScheduleIntentError, k as automationTitleSchema, z as taskOutcomeInputSchema } from "./automation-CrQGQ2MT.js";
24
+ import { a as createSandboxSession, c as postinstall, d as getSandboxResources, i as bindSandboxFileSystem, l as setSnapshotSpanAttributes, n as isMissingError, o as stopSession, r as resolve$1, s as dependencies } from "./resolve-9_cIPQsq.js";
25
+ import { a as getVercelConversationWorkQueue, f as getTurnRequestDeadline, n as sendNextWorkspaceSnapshotJob, r as sendWorkspaceSnapshotJob } from "./job-queue-DgXLqoeB.js";
26
+ import { A as eventAutomationSchema, D as scheduledRunSchema, E as scheduledAutomationSchema, F as taskOutcomeInputSchema, M as compileScheduleIntent, N as scheduleIntentSchema, O as automationInstructionToolSchema, S as automationVersionSchema, T as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, j as ScheduleIntentError, k as automationTitleSchema } from "./automation-B5_c8hEb.js";
26
27
  import { r as isExperimentalFeatureEnabled } from "./experimental-Qn9rKLgx.js";
27
28
  import { n as privateTraceResultAttributes } from "./private-trace-result-BLvBjy_e.js";
28
29
  import { streamSimple } from "@earendil-works/pi-ai/compat";
@@ -11451,76 +11452,6 @@ function logScheduledAutomationRunSkipped(task, run, extras = {}) {
11451
11452
  logInfo("scheduled_automation.run.skipped", scheduledAutomationRunAttributes(task, run, extras));
11452
11453
  }
11453
11454
  //#endregion
11454
- //#region src/chat/slack/user.ts
11455
- const slackUserInfoSchema = z.object({
11456
- ok: z.literal(true),
11457
- user: z.object({
11458
- name: z.string().nullish(),
11459
- tz: z.string().nullish(),
11460
- profile: z.object({
11461
- email: z.string().nullish(),
11462
- real_name: z.string().nullish()
11463
- }).optional()
11464
- })
11465
- });
11466
- const USER_CACHE_TTL_MS = 3e5;
11467
- const userCache = /* @__PURE__ */ new Map();
11468
- function userCacheKey(teamId, userId) {
11469
- return `${teamId}:${userId}`;
11470
- }
11471
- function readFromCache(teamId, userId) {
11472
- const hit = userCache.get(userCacheKey(teamId, userId));
11473
- if (!hit) return null;
11474
- if (hit.expiresAt < Date.now()) {
11475
- userCache.delete(userCacheKey(teamId, userId));
11476
- return null;
11477
- }
11478
- return hit.value;
11479
- }
11480
- function writeToCache(teamId, userId, value) {
11481
- userCache.set(userCacheKey(teamId, userId), {
11482
- value,
11483
- expiresAt: Date.now() + USER_CACHE_TTL_MS
11484
- });
11485
- }
11486
- /** Fetch Slack user profile info with in-memory TTL cache to avoid repeated API calls. */
11487
- async function lookupSlackUser(teamId, userId) {
11488
- if (!teamId || !userId) return null;
11489
- const cached = readFromCache(teamId, userId);
11490
- if (cached) return cached;
11491
- const token = getSlackBotToken();
11492
- if (!token) return null;
11493
- try {
11494
- const response = await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(userId)}`, { headers: { authorization: `Bearer ${token}` } });
11495
- if (!response.ok) {
11496
- logWarn("slack.user.lookup.failed", {
11497
- "enduser.id": userId,
11498
- "app.slack.team_id": teamId,
11499
- "http.response.status_code": response.status
11500
- });
11501
- return null;
11502
- }
11503
- const parsed = slackUserInfoSchema.safeParse(await response.json());
11504
- if (!parsed.success) return null;
11505
- const payload = parsed.data;
11506
- const result = {
11507
- userName: payload.user.name?.trim() || void 0,
11508
- fullName: payload.user.profile?.real_name?.trim() || void 0,
11509
- email: payload.user.profile?.email?.trim() || void 0,
11510
- timezone: payload.user.tz?.trim() || void 0
11511
- };
11512
- writeToCache(teamId, userId, result);
11513
- return result;
11514
- } catch (error) {
11515
- logWarn("slack.user.lookup.failed", {
11516
- "enduser.id": userId,
11517
- "app.slack.team_id": teamId,
11518
- "exception.message": error instanceof Error ? error.message : String(error)
11519
- });
11520
- return null;
11521
- }
11522
- }
11523
- //#endregion
11524
11455
  //#region src/chat/scheduled-automations/identity.ts
11525
11456
  const SLACK_USER_ID_PATTERN = /^[UW][A-Z0-9]{5,}$/;
11526
11457
  function clean(value) {
@@ -11551,7 +11482,6 @@ function sanitizeScheduledAutomationPrincipal(principal) {
11551
11482
  //#endregion
11552
11483
  //#region src/chat/scheduled-automations/tool-support.ts
11553
11484
  const TASK_ID_PREFIX = "sched";
11554
- const DEFAULT_SCHEDULE_TIMEZONE = "America/Los_Angeles";
11555
11485
  const compactTaskResultSchema = z.object({
11556
11486
  id: z.string(),
11557
11487
  title: z.string().nullable(),
@@ -11768,23 +11698,6 @@ function buildTaskId(args) {
11768
11698
  function normalizeStatus(value) {
11769
11699
  if (value === "active" || value === "blocked") return value;
11770
11700
  }
11771
- /** Centralize scheduler timezone defaulting for all concrete tool entry points. */
11772
- function getDefaultScheduleTimezone() {
11773
- return process.env.JUNIOR_TIMEZONE?.trim() || DEFAULT_SCHEDULE_TIMEZONE;
11774
- }
11775
- /**
11776
- * Pick the timezone for a new schedule when the user names none: the
11777
- * creator's Slack profile, then the saved user timezone, then the install
11778
- * default. A valid Slack timezone is saved on the linked user.
11779
- */
11780
- async function resolveCreatorScheduleTimezone(args) {
11781
- const timezone = (await lookupSlackUser(args.teamId, args.slackUserId))?.timezone;
11782
- if (timezone && isValidTimeZone$1(timezone)) {
11783
- if (args.userId) await saveUserTimezone(args.db, args.userId, timezone, args.nowMs);
11784
- return timezone;
11785
- }
11786
- return (args.userId ? await readUserTimezone(args.db, args.userId) : void 0) ?? getDefaultScheduleTimezone();
11787
- }
11788
11701
  //#endregion
11789
11702
  //#region src/chat/scheduled-automations/tools/create.ts
11790
11703
  /** Create a tool that stores a scheduled automation for the active Slack context. */
@@ -11832,11 +11745,13 @@ function createSlackScheduleCreateAutomationTool(context) {
11832
11745
  const identity = creator?.identity;
11833
11746
  if (!identity || identity.provider !== "slack" || identity.providerTenantId !== destination.teamId || identity.providerSubjectId !== actor.slackUserId) throwToolInputError("Scheduled automation creator identity is unavailable.");
11834
11747
  const nowMs = context.now?.() ?? Date.now();
11835
- const defaultTimezone = input.schedule.timezone ?? await resolveCreatorScheduleTimezone({
11748
+ const defaultTimezone = input.schedule.timezone ?? await resolveUserTimezone({
11836
11749
  db,
11837
11750
  nowMs,
11838
- slackUserId: actor.slackUserId,
11839
- teamId: destination.teamId,
11751
+ slack: {
11752
+ teamId: destination.teamId,
11753
+ userId: actor.slackUserId
11754
+ },
11840
11755
  ...creator.user ? { userId: creator.user.id } : void 0
11841
11756
  });
11842
11757
  let compiled;
@@ -12056,7 +11971,7 @@ async function editScheduledAutomation(current, input, isCreator, nowMs) {
12056
11971
  let compiled;
12057
11972
  if (input.schedule !== void 0) try {
12058
11973
  compiled = compileScheduleIntent({
12059
- defaultTimezone: current.schedule.timezone || getDefaultScheduleTimezone(),
11974
+ defaultTimezone: current.schedule.timezone || defaultTimezone(),
12060
11975
  intent: input.schedule,
12061
11976
  nowMs
12062
11977
  });
@@ -15213,14 +15128,6 @@ function createSystemTimeTool() {
15213
15128
  }
15214
15129
  });
15215
15130
  }
15216
- function isValidTimeZone(timezone) {
15217
- try {
15218
- new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
15219
- return true;
15220
- } catch {
15221
- return false;
15222
- }
15223
- }
15224
15131
  function getTimeZoneOffsetMinutes(timestampMs, timezone) {
15225
15132
  const parts = getZonedDateTimeParts(timestampMs, timezone);
15226
15133
  const asUtcMs = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
@@ -19074,6 +18981,22 @@ async function requestBodyBytes(request) {
19074
18981
  if (request.method === "GET" || request.method === "HEAD" || request.body === null) return;
19075
18982
  return await request.arrayBuffer();
19076
18983
  }
18984
+ /**
18985
+ * Explain a request body that the runtime delivered already used.
18986
+ *
18987
+ * The forwarded headers cannot show whether the body was empty, so the proxy
18988
+ * does not send a credentialed write upstream without its payload.
18989
+ */
18990
+ function unreadableBodyResponse(eventId) {
18991
+ return Response.json({
18992
+ source: "junior-egress",
18993
+ error: "Junior's sandbox egress proxy could not read the request body, so it did not send the request upstream.",
18994
+ ...eventId ? { sentryEventId: eventId } : void 0
18995
+ }, {
18996
+ status: 500,
18997
+ headers: { "cache-control": "no-store" }
18998
+ });
18999
+ }
19077
19000
  /** Identify GitHub writes whose body determines whether a grant is safe. */
19078
19001
  function githubBodyInspection(input) {
19079
19002
  if (input.provider !== "github" || input.requestMethod.toUpperCase() !== "POST" || input.upstreamUrl.hostname.toLowerCase() !== "api.github.com") return;
@@ -19229,11 +19152,28 @@ async function recordSandboxPermissionDenied(input) {
19229
19152
  */
19230
19153
  async function executeCredentialedEgressRequest(input) {
19231
19154
  const { activeEgressId, credentialContext, deps, operation, provider, request, upstreamUrl } = input;
19155
+ let body;
19156
+ try {
19157
+ body = await requestBodyBytes(request);
19158
+ } catch (error) {
19159
+ if (!(error instanceof TypeError)) throw error;
19160
+ return unreadableBodyResponse(logException(error, "sandbox.egress.request_body.unreadable", {
19161
+ ...egressAttributes({
19162
+ egressId: activeEgressId,
19163
+ host: upstreamUrl.hostname,
19164
+ method: request.method,
19165
+ path: upstreamUrl.pathname,
19166
+ provider,
19167
+ status: 500
19168
+ }),
19169
+ ...routingAttributes(request, upstreamUrl)
19170
+ }));
19171
+ }
19232
19172
  const bodyForGrantSelection = githubBodyInspection({
19233
19173
  provider,
19234
19174
  requestMethod: request.method,
19235
19175
  upstreamUrl
19236
- }) ? await requestBodyBytes(request) : void 0;
19176
+ }) ? body : void 0;
19237
19177
  let grantSelection;
19238
19178
  try {
19239
19179
  grantSelection = await selectSandboxEgressGrant({
@@ -19325,7 +19265,6 @@ async function executeCredentialedEgressRequest(input) {
19325
19265
  return Response.json({ error: "Credential lease does not cover forwarded host" }, { status: 403 });
19326
19266
  }
19327
19267
  const fetchImpl = deps.fetch ?? fetch;
19328
- const body = bodyForGrantSelection ?? await requestBodyBytes(request);
19329
19268
  let retriedAfter403 = false;
19330
19269
  while (true) {
19331
19270
  const headers = requestHeaders(request, lease, upstreamUrl.hostname, deps.tracePropagation ?? {});
@@ -21879,7 +21818,7 @@ function createAgentRunner(execute, options) {
21879
21818
  } } : void 0
21880
21819
  };
21881
21820
  if (run.instruction.storedAttachments?.length) {
21882
- const { loadInputImages } = await import("./images-1xUjTHGf.js").then((n) => n.n);
21821
+ const { loadInputImages } = await import("./images-C7OKd6uy.js").then((n) => n.n);
21883
21822
  const storage = nextRun.environment?.attachmentStorage;
21884
21823
  if (!storage) throw new Error("Attachment storage is unavailable.");
21885
21824
  nextRun.instruction = {
@@ -21895,4 +21834,4 @@ function createAgentRunner(execute, options) {
21895
21834
  } };
21896
21835
  }
21897
21836
  //#endregion
21898
- export { eventAutomationBelongsToUser as $, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as $t, resolveSlackChannelIdFromMessage as A, slackEntitySchema as An, beginConversationResume as At, parseScheduledAutomationRow as B, setConfigDefaults as Bn, ensureConversationWake as Bt, renderBlockText as C, normalizeSlackReplyMarkdown as Cn, timerWatchCredentialSubject as Ct, storeAttachment as D, addReactionToMessage as Dn, ackMessages as Dt, requestAttachmentDeletion as E, truncateStatusText as En, pluginEventCatalog as Et, lookupSlackUser as F, actorFromRun as Fn, completeConversationStop as Ft, withScheduledAutomationLock as G, recordAttemptFailure as Gt, saveScheduledAutomation as H, getConversationWorkState as Ht, logScheduledAutomationRunSkipped as I, toolInvocationDestination as In, completeConversationWork as It, eventAutomationTriggerAvailable as J, removeActiveConversation as Jt, editEventAutomation as K, recordConversationRetry as Kt, scheduledAutomationRunAttributes as L, AuthorizationFlowDisabledError as Ln, countPendingConversationMessages as Lt, getConversationInfo as M, createUserTokenStore as Mn, checkInConversationWork as Mt, listThreadReplies as N, buildSteeringPiMessage as Nn, clearConsumedConversationWake as Nt, parseSlackThreadId as O, postSlackMessage as On, appendAndEnqueueExclusiveInboundMessage as Ot, editScheduledAutomation as P, RetryableDeliveryError as Pn, clearExpiredConversationLease as Pt, deleteEventAutomation as Q, stopConversationWork as Qt, listScheduledAutomations as R, shouldEmitDevAgentTrace as Rn, deadLetterAttempt as Rt, renderAttachmentText as S, formatSlackLink as Sn, isEventMailboxMetadata as St, readLiveAttachment as T, slackMention as Tn, eventGuidance as Tt, saveScheduledAutomationInLock as U, hasRunnableConversationWork as Ut, readScheduledAutomation as V, getConversation as Vt, scheduledRunId as W, listActiveConversationIds as Wt, resolveTaskOutcomes as X, requestConversationWork as Xt, effectiveTaskOutcomes as Y, requestAnotherSlice as Yt, collectEventAutomationMatchKeys as Z, startConversationWork as Zt, resolvePluginOAuthAccount as _, formatProviderLabel as _n, AgentInvocationLimitError as _t, buildAuthPauseResponse as a, renderTaskInput as an, setEventAutomationStatus as at, unpublishedArtifactHeaders as b, startOAuthFlow as bn, ingestEvent as bt, deleteMcpAuthSessionsForUserProvider as c, resolveSandboxEgressProviderForHost as cn, readAutomationVersion as ct, getMcpAuthSession as d, SANDBOX_EGRESS_PROXY_PATH as dn, automationRevision as dt, CONVERSATION_WORK_STALE_ENQUEUE_MS as en, findMatchingEventAutomations as et, getMcpStoredOAuthCredentials as f, clearSandboxEgressSignals as fn, requireAutomationRevision as ft, readStats as g, sandboxEgressSignalsResponseSchema as gn, AgentInvocationBusyError as gt, latestProgressStatus as h, parseSandboxEgressCredentialToken as hn, createAgentInvocationSchema as ht, executeCredentialedEgressRequest as i, isInvalidConversationRecordError as in, saveEventAutomation as it, resolveSlackChannelIdFromThreadId as j, slackExternalRefIdSchema as jn, cancelHumanFacingPendingMessages as jt, readSlackRawMessageContext as k, removeReactionFromMessage as kn, appendAndEnqueueInboundMessage as kt, deleteMcpServerSessionId as l, normalizeSandboxEgressTracePropagationDomains as ln, sameDefinitionValue as lt, PluginCredentialFailureError as m, consumeSandboxEgressPermissionDeniedSignal as mn, agentInvocationSchema as mt, executeAgentRun as n, hasRunnableConversationWork$1 as nn, listDeletedEventAutomationsCreatedBy as nt, finalizeMcpAuthorization as o, maybePostAutomatedTurnLimitNotice as on, automationDefinition as ot, putMcpStoredOAuthCredentials as p, consumeSandboxEgressAuthRequiredSignal as pn, agentBindingSchema as pt, AutomationEditError as q, releaseConversationWork as qt, createContextCompactor as r, isFinalAttempt as rn, parseEventAutomationRow as rt, deleteMcpAuthSession as s, recordFinishedTurnForAutomatedLimit as sn, listAutomationVersions as st, createAgentRunner as t, hasConversationStop as tn, getEventAutomation as tt, deleteMcpStoredOAuthCredentials as u, shouldPropagateSandboxEgressTrace as un, AutomationConflictError as ut, publicArtifactHeaders as v, parseOAuthStatePayload as vn, getMcpProviderErrorAttributes as vt, collectAttachmentGarbage as w, normalizeSlackStatusText as wn, getEventCatalog as wt, lookupSlackUserProfile as x, escapeSlackMrkdwnText as xn, EVENT_WAIT_MS as xt, readPublicArtifact as y, resolveBaseUrl as yn, processWorkspaceSnapshotJob as yt, listScheduledAutomationsForTeam as z, getConfigDefaults as zn, drainConversationMailbox as zt };
21837
+ export { findMatchingEventAutomations as $, CONVERSATION_WORK_STALE_ENQUEUE_MS as $t, resolveSlackChannelIdFromMessage as A, slackExternalRefIdSchema as An, cancelHumanFacingPendingMessages as At, readScheduledAutomation as B, getConversation as Bt, renderBlockText as C, normalizeSlackStatusText as Cn, getEventCatalog as Ct, storeAttachment as D, postSlackMessage as Dn, appendAndEnqueueExclusiveInboundMessage as Dt, requestAttachmentDeletion as E, addReactionToMessage as En, ackMessages as Et, logScheduledAutomationRunSkipped as F, toolInvocationDestination as Fn, completeConversationWork as Ft, editEventAutomation as G, recordConversationRetry as Gt, saveScheduledAutomationInLock as H, hasRunnableConversationWork as Ht, scheduledAutomationRunAttributes as I, AuthorizationFlowDisabledError as In, countPendingConversationMessages as It, effectiveTaskOutcomes as J, requestAnotherSlice as Jt, AutomationEditError as K, releaseConversationWork as Kt, listScheduledAutomations as L, shouldEmitDevAgentTrace as Ln, deadLetterAttempt as Lt, getConversationInfo as M, buildSteeringPiMessage as Mn, clearConsumedConversationWake as Mt, listThreadReplies as N, RetryableDeliveryError as Nn, clearExpiredConversationLease as Nt, parseSlackThreadId as O, removeReactionFromMessage as On, appendAndEnqueueInboundMessage as Ot, editScheduledAutomation as P, actorFromRun as Pn, completeConversationStop as Pt, eventAutomationBelongsToUser as Q, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as Qt, listScheduledAutomationsForTeam as R, getConfigDefaults as Rn, drainConversationMailbox as Rt, renderAttachmentText as S, normalizeSlackReplyMarkdown as Sn, timerWatchCredentialSubject as St, readLiveAttachment as T, truncateStatusText as Tn, pluginEventCatalog as Tt, scheduledRunId as U, listActiveConversationIds as Ut, saveScheduledAutomation as V, getConversationWorkState as Vt, withScheduledAutomationLock as W, recordAttemptFailure as Wt, collectEventAutomationMatchKeys as X, startConversationWork as Xt, resolveTaskOutcomes as Y, requestConversationWork as Yt, deleteEventAutomation as Z, stopConversationWork as Zt, resolvePluginOAuthAccount as _, parseOAuthStatePayload as _n, getMcpProviderErrorAttributes as _t, buildAuthPauseResponse as a, maybePostAutomatedTurnLimitNotice as an, automationDefinition as at, unpublishedArtifactHeaders as b, escapeSlackMrkdwnText as bn, EVENT_WAIT_MS as bt, deleteMcpAuthSessionsForUserProvider as c, normalizeSandboxEgressTracePropagationDomains as cn, sameDefinitionValue as ct, getMcpAuthSession as d, clearSandboxEgressSignals as dn, requireAutomationRevision as dt, hasConversationStop as en, getEventAutomation as et, getMcpStoredOAuthCredentials as f, consumeSandboxEgressAuthRequiredSignal as fn, agentBindingSchema as ft, readStats as g, formatProviderLabel as gn, AgentInvocationLimitError as gt, latestProgressStatus as h, sandboxEgressSignalsResponseSchema as hn, AgentInvocationBusyError as ht, executeCredentialedEgressRequest as i, renderTaskInput as in, setEventAutomationStatus as it, resolveSlackChannelIdFromThreadId as j, createUserTokenStore as jn, checkInConversationWork as jt, readSlackRawMessageContext as k, slackEntitySchema as kn, beginConversationResume as kt, deleteMcpServerSessionId as l, shouldPropagateSandboxEgressTrace as ln, AutomationConflictError as lt, PluginCredentialFailureError as m, parseSandboxEgressCredentialToken as mn, createAgentInvocationSchema as mt, executeAgentRun as n, isFinalAttempt as nn, parseEventAutomationRow as nt, finalizeMcpAuthorization as o, recordFinishedTurnForAutomatedLimit as on, listAutomationVersions as ot, putMcpStoredOAuthCredentials as p, consumeSandboxEgressPermissionDeniedSignal as pn, agentInvocationSchema as pt, eventAutomationTriggerAvailable as q, removeActiveConversation as qt, createContextCompactor as r, isInvalidConversationRecordError as rn, saveEventAutomation as rt, deleteMcpAuthSession as s, resolveSandboxEgressProviderForHost as sn, readAutomationVersion as st, createAgentRunner as t, hasRunnableConversationWork$1 as tn, listDeletedEventAutomationsCreatedBy as tt, deleteMcpStoredOAuthCredentials as u, SANDBOX_EGRESS_PROXY_PATH as un, automationRevision as ut, publicArtifactHeaders as v, resolveBaseUrl as vn, processWorkspaceSnapshotJob as vt, collectAttachmentGarbage as w, slackMention as wn, eventGuidance as wt, lookupSlackUserProfile as x, formatSlackLink as xn, isEventMailboxMetadata as xt, readPublicArtifact as y, startOAuthFlow as yn, ingestEvent as yt, parseScheduledAutomationRow as z, setConfigDefaults as zn, ensureConversationWake as zt };