@sentry/junior 0.221.1 → 0.222.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 (64) hide show
  1. package/dist/{agent-CY49A4pN.js → agent-7kKtDe-6.js} +47 -27
  2. package/dist/{agent-hooks-BnZBgDPe.js → agent-hooks-DkriF84n.js} +9 -8
  3. package/dist/{agent-runner-BC8iSAfE.js → agent-runner-D0ImXS7U.js} +6 -5
  4. package/dist/api/schema.d.ts +51 -2
  5. package/dist/api/schema.js +4 -4
  6. package/dist/api.js +18 -515
  7. package/dist/{app-BYD2Nyji.d.ts → app-C0zbsnr7.d.ts} +1 -1
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +153 -32
  10. package/dist/{auth-pause-state-CJwPs1cT.js → auth-pause-state-3OT67TA8.js} +52 -7
  11. package/dist/{briefs-BSOhy23c.js → briefs-CNH1ztn5.js} +4 -4
  12. package/dist/{catalog-runtime-0oMD2jas.js → catalog-runtime-XH_LFA_7.js} +1 -1
  13. package/dist/{checkpoint-Bl47qAIY.js → checkpoint-CRod8es5.js} +8 -7
  14. package/dist/cli/chat.js +13 -13
  15. package/dist/cli/check.js +3 -3
  16. package/dist/cli/main.js +1 -1
  17. package/dist/cli/plugins.js +3 -3
  18. package/dist/cli/snapshot-create.js +3 -3
  19. package/dist/cli/upgrade.js +3 -3
  20. package/dist/{client-BrThxuRI.js → client-CcSboWx_.js} +2 -2
  21. package/dist/{config-CEuC6CFj.js → config-CGYv-YPE.js} +2 -2
  22. package/dist/{conversation-BSRGzJmY.js → conversation-BBDt88di.js} +46 -3
  23. package/dist/{conversation-privacy-aHn1OwXL.js → conversation-privacy-BGjdDVWD.js} +1 -1
  24. package/dist/{credential-sync-Dht95TJQ.js → credential-sync-BfzGNruT.js} +125 -30
  25. package/dist/{execution-stats-D9m2kmmg.js → execution-stats-D97ePWuM.js} +3 -3
  26. package/dist/{executor-3IasVOqK.js → executor-BLBZ-UB8.js} +1 -1
  27. package/dist/{history-ClE4toxe.d.ts → history-CaV8Ww7M.d.ts} +16 -1
  28. package/dist/instrumentation.js +2 -2
  29. package/dist/{job-queue-36liupTq.js → job-queue-_8gxwDzt.js} +1 -1
  30. package/dist/{logging-gR24QCo_.js → logging-qmsMdU0y.js} +1 -1
  31. package/dist/nitro.d.ts +1 -1
  32. package/dist/nitro.js +3 -3
  33. package/dist/{oauth-callback-server-BvNIWVA3.js → oauth-callback-server-Mjfm46A5.js} +2 -2
  34. package/dist/{pending-auth-Cl4BsopG.js → pending-auth-_1Ry-_Bw.js} +2 -2
  35. package/dist/{profile-VmUpQuOm.js → profile-DbG8AlNd.js} +4 -4
  36. package/dist/{prompt-BkaHwBW0.js → prompt-B8rCQI7K.js} +1 -1
  37. package/dist/{registry-BATk1X_v.js → registry-DGyQCsiy.js} +1 -1
  38. package/dist/reporting-window-DbUqng0P.js +229 -0
  39. package/dist/{resolve-Cf79l1H8.js → resolve-D5SqDbCA.js} +2 -2
  40. package/dist/{runner-DNN4EPj_.js → runner-BRAFjJhe.js} +21 -10
  41. package/dist/{sandbox-egress-signals-C-HUJW1G.js → sandbox-egress-signals-CdI1aVHT.js} +1 -1
  42. package/dist/{schema-YPJXVcOW.js → schema-CTOODa3L.js} +5 -128
  43. package/dist/{short-title-Cy3D8vg1.js → short-title-CB2fxEyx.js} +2 -2
  44. package/dist/{skills-DMQkR1Yu.js → skills-BoS3b8cg.js} +2 -2
  45. package/dist/{spawn-BHk7RpYw.js → spawn-BXCU1udr.js} +2 -2
  46. package/dist/{stats-8Bzht8zO.js → stats-qUXQZq-w.js} +52 -13
  47. package/dist/{task-queue-Cm4FhC0n.js → task-queue-Di_q8922.js} +3 -3
  48. package/dist/{task-runner-dQwOhCYs.js → task-runner-4rCppQMo.js} +8 -8
  49. package/dist/{thread-state-D0Ktlch_.js → thread-state-2Paza8DV.js} +5 -5
  50. package/dist/{turn-execution-BfLZfabf.js → turn-execution--F7a9kEU.js} +3 -3
  51. package/dist/{turn-lifecycle-D75pWL8e.js → turn-lifecycle-f-y0Irpi.js} +1 -1
  52. package/dist/{validation-D5fdtuzG.js → validation-Be9lSORU.js} +1 -1
  53. package/dist/{version-DErORHQC.js → version-BydrOZMQ.js} +1 -1
  54. package/dist/version.js +1 -1
  55. package/dist/{web-authorization-IHMPbDay.js → web-authorization-BdfOkTuG.js} +1 -1
  56. package/dist/web-input-DegYUyKU.js +899 -0
  57. package/dist/{work-CaaSjlNk.js → work-Citqpnfc.js} +9 -9
  58. package/dist/{worker-Eom9CfBl.js → worker-Bn_HFyvM.js} +5 -5
  59. package/migrations/0044_event_automation_channel_destinations.sql +36 -0
  60. package/migrations/meta/0044_snapshot.json +3473 -0
  61. package/migrations/meta/_journal.json +7 -0
  62. package/package.json +4 -4
  63. package/dist/reporting-schema-DosTN__Q.js +0 -105
  64. package/dist/web-input-DskRJhrK.js +0 -392
package/dist/api.js CHANGED
@@ -1,24 +1,23 @@
1
- import { f as logWarn, u as logException } from "./logging-gR24QCo_.js";
1
+ import { f as logWarn, u as logException } from "./logging-qmsMdU0y.js";
2
2
  import { _ as parseSlackMessageTs, h as parseSlackTeamId, p as parseSlackChannelId } from "./context-Bplcgypl.js";
3
- import { $ as resolveViewerUser, $t as parseSessionSource, Ct as conversationArchivedForEmail, D as SANDBOX_RUNTIME, Dt as conversationNotArchivedForEmail, Et as conversationHasParticipantUser, Ft as listConversationAnnotations, Gt as getDb, It as listConversationAnnotationsById, J as withSlackRetries, Kt as getSqlExecutor, Mt as readConversationEventPage, Nt as buildSentryConversationUrl, Ot as conversationNotArchivedForUser, S as WorkspaceValidationError, St as conversationArchiveTimes, Tt as conversationHasParticipantEmail, U as getSlackClient, Wt as getConversationStore, Z as findUserByEmail, Zt as locationFromRow, _ as deleteWorkspace, an as resolveRootConversationId, b as listWorkspaces, bt as createPluginLogger, et as updateViewerDisplayName, g as createWorkspace, in as hasAgentTurnUsage, j as workspaceRepoCheckoutPath, jt as readLatestConversationBrief, kt as viewerConversationMembership, rn as agentTurnUsageSchema, u as getPlugins, v as getWorkspace, wt as conversationArchivedForUser, x as updateWorkspace, xt as readConversationAccessFromSql } from "./agent-hooks-BnZBgDPe.js";
3
+ import { $ as resolveViewerUser, $t as parseSessionSource, Ct as conversationArchivedForEmail, D as SANDBOX_RUNTIME, Dt as conversationNotArchivedForEmail, Et as conversationHasParticipantUser, Ft as listConversationAnnotations, Gt as getDb, It as listConversationAnnotationsById, J as withSlackRetries, Kt as getSqlExecutor, Mt as readConversationEventPage, Nt as buildSentryConversationUrl, Ot as conversationNotArchivedForUser, S as WorkspaceValidationError, St as conversationArchiveTimes, Tt as conversationHasParticipantEmail, U as getSlackClient, Wt as getConversationStore, Z as findUserByEmail, Zt as locationFromRow, _ as deleteWorkspace, an as resolveRootConversationId, b as listWorkspaces, bt as createPluginLogger, et as updateViewerDisplayName, g as createWorkspace, in as hasAgentTurnUsage, j as workspaceRepoCheckoutPath, jt as readLatestConversationBrief, kt as viewerConversationMembership, rn as agentTurnUsageSchema, u as getPlugins, v as getWorkspace, wt as conversationArchivedForUser, x as updateWorkspace, xt as readConversationAccessFromSql } from "./agent-hooks-DkriF84n.js";
4
4
  import { n as juniorDestinations } from "./destinations-BeBiJeEM.js";
5
- import { C as juniorCodeRepositories, D as juniorIdentities, E as juniorConversations, O as juniorUsers, S as juniorCodeChanges, T as conversationReadColumns, b as juniorApiTokens, g as juniorConversationBriefs, m as juniorConversationParticipants, o as juniorSchedulerTasks, v as juniorConversationMetrics, y as juniorConversationEvents } from "./executor-3IasVOqK.js";
6
- import { D as createConversationBodySchema, O as createConversationMessageBodySchema, T as conversationStatsReportSchema, _ as conversationParamsSchema, a as cancelConversationPendingMessagesBodySchema, c as conversationAttachmentParamsSchema, d as conversationDetailReportSchema, g as conversationFeedSchema, h as conversationFeedQuerySchema, i as archiveConversationResponseSchema, m as conversationEventsQuerySchema, o as cancelConversationPendingMessagesResponseSchema, p as conversationEventPageSchema, r as archiveConversationBodySchema, t as acceptedConversationMessageSchema, u as conversationDetailQuerySchema, x as conversationPendingMessagesReportSchema } from "./conversation-BSRGzJmY.js";
7
- import { t as fallbackShortTitle } from "./short-title-Cy3D8vg1.js";
8
- import { n as hash, t as create } from "./profile-VmUpQuOm.js";
9
- import { A as eventAutomationTriggerAvailable, F as effectiveTaskOutcomes, G as listDeletedEventAutomationsCreatedBy, H as eventAutomationBelongsToUser, J as listPublicEventAutomationsForTeams, K as listEventAutomationsCreatedBy, Tt as getConversation, V as deleteEventAutomation, W as getEventAutomation, X as getEventCatalog, _ as parseScheduledAutomationRow, c as parseSlackThreadId, ht as cancelHumanFacingPendingMessages, i as readLiveAttachment, m as listPublicScheduledAutomationsForTeams, n as readStats, p as isListedScheduledAutomation, v as readScheduledAutomation, y as saveScheduledAutomation } from "./stats-8Bzht8zO.js";
10
- import { t as getCachedSnapshot } from "./resolve-Cf79l1H8.js";
5
+ import { C as juniorCodeRepositories, D as juniorIdentities, E as juniorConversations, O as juniorUsers, S as juniorCodeChanges, T as conversationReadColumns, b as juniorApiTokens, g as juniorConversationBriefs, m as juniorConversationParticipants, v as juniorConversationMetrics, y as juniorConversationEvents } from "./executor-BLBZ-UB8.js";
6
+ import { D as createConversationBodySchema, O as createConversationMessageBodySchema, T as conversationStatsReportSchema, _ as conversationParamsSchema, a as cancelConversationPendingMessagesBodySchema, c as conversationAttachmentParamsSchema, d as conversationDetailReportSchema, g as conversationFeedSchema, h as conversationFeedQuerySchema, i as archiveConversationResponseSchema, m as conversationEventsQuerySchema, o as cancelConversationPendingMessagesResponseSchema, p as conversationEventPageSchema, r as archiveConversationBodySchema, t as acceptedConversationMessageSchema, u as conversationDetailQuerySchema, x as conversationPendingMessagesReportSchema } from "./conversation-BBDt88di.js";
7
+ import { n as hash, t as create } from "./profile-DbG8AlNd.js";
8
+ import { Tt as getConversation, c as parseSlackThreadId, ht as cancelHumanFacingPendingMessages, i as readLiveAttachment, n as readStats } from "./stats-qUXQZq-w.js";
9
+ import { t as getCachedSnapshot } from "./resolve-D5SqDbCA.js";
11
10
  import { t as getVercelConversationWorkQueue } from "./vercel-queue-DIkVcfK4.js";
12
- import { c as runtimeInfoReportSchema, n as pluginOperationalReportFeedSchema, s as pluginsSchema, t as healthReportSchema, u as skillReportsSchema } from "./reporting-schema-DosTN__Q.js";
13
- import { a as webActorFromEmail, c as formatSlackConversationRedactedLabel, d as resolveSlackConversationContextFromThreadId, f as lookupSlackUser, g as readHealthReport, m as createVercelAttachmentStorage, p as legacyWebMailboxMetadataSchema, r as createAndEnqueueConversation, t as appendAndEnqueueWebMessage } from "./web-input-DskRJhrK.js";
14
- import { a as readAutomationExecutionStatusDays, c as readAutomationExecutions, d as conversationActiveDaysColumn, f as conversationAggregateColumns, i as readAutomationExecutionHours, l as readAutomationRuns, n as readAutomationExecutionByConversationId, o as readAutomationExecutionStatusHours, p as conversationRangeColumns, r as readAutomationExecutionDays, s as readAutomationExecutionSummaries, t as emptyAutomationRunWindows } from "./execution-stats-D9m2kmmg.js";
15
- import { r as getWebAuthorization } from "./web-authorization-IHMPbDay.js";
16
- import { $ as sumUtcHoursIntoSixHours, A as actorProfileReportSchema, C as createPersonalTokenBodySchema, D as personalTokenParamsSchema, F as locationDirectoryReportSchema, G as codePersonReportSchema, I as locationParamsSchema, J as HOUR_MS$1, L as activityDays$1, M as personalSpendReportSchema, O as revokePersonalTokenResponseSchema, P as locationDetailReportSchema, Q as startOfUtcHour, R as activityHours$1, T as personalTokenListSchema, W as codeOverviewReportSchema, X as fillUtcHours, Y as fillUtcDays, Z as fillUtcSixHours, _ as automationRunListSchema, a as workspaceBodySchema, at as apiErrorSchema, et as trailingUtcDayWindow, g as automationParamsSchema, h as automationListSchema, i as deleteWorkspaceResponseSchema, it as utcHourKey, j as personParamsSchema, k as actorDirectoryReportSchema, l as workspaceSchema, m as automationListQuerySchema, n as statsReportSchema, nt as trailingUtcSixHourWindow, o as workspaceListSchema, q as DAY_MS$1, rt as utcDayKey, s as workspaceParamsSchema, tt as trailingUtcHourWindow, u as automationExecutionListSchema, w as createdPersonalTokenSchema, z as activitySixHours$1 } from "./schema-YPJXVcOW.js";
11
+ import { S as skillReportsSchema, a as fillUtcSixHours, b as runtimeInfoReportSchema, c as trailingUtcDayWindow, d as utcDayKey, f as utcHourKey, i as fillUtcHours, l as trailingUtcHourWindow, m as pluginOperationalReportFeedSchema, n as HOUR_MS$1, o as startOfUtcHour, p as healthReportSchema, r as fillUtcDays, s as sumUtcHoursIntoSixHours, t as DAY_MS$1, u as trailingUtcSixHourWindow, y as pluginsSchema } from "./reporting-window-DbUqng0P.js";
12
+ import { C as readHealthReport, a as webActorFromEmail, b as legacyWebMailboxMetadataSchema, c as formatSlackConversationRedactedLabel, d as resolveSlackConversationContextFromThreadId, f as ViewerTaskNotFoundError, g as readViewerAutomationRuns, h as readViewerAutomationExecutions, m as readConversationSourceTask, p as deleteViewerTask, r as createAndEnqueueConversation, t as appendAndEnqueueWebMessage, v as readViewerAutomations, x as createVercelAttachmentStorage, y as lookupSlackUser } from "./web-input-DegYUyKU.js";
13
+ import { d as conversationActiveDaysColumn, f as conversationAggregateColumns, p as conversationRangeColumns } from "./execution-stats-D97ePWuM.js";
14
+ import { r as getWebAuthorization } from "./web-authorization-BdfOkTuG.js";
15
+ import { A as actorProfileReportSchema, C as createPersonalTokenBodySchema, D as personalTokenParamsSchema, F as locationDirectoryReportSchema, G as codePersonReportSchema, I as locationParamsSchema, L as activityDays$1, M as personalSpendReportSchema, O as revokePersonalTokenResponseSchema, P as locationDetailReportSchema, R as activityHours$1, T as personalTokenListSchema, W as codeOverviewReportSchema, _ as automationRunListSchema, a as workspaceBodySchema, g as automationParamsSchema, h as automationListSchema, i as deleteWorkspaceResponseSchema, j as personParamsSchema, k as actorDirectoryReportSchema, l as workspaceSchema, m as automationListQuerySchema, n as statsReportSchema, o as workspaceListSchema, q as apiErrorSchema, s as workspaceParamsSchema, u as automationExecutionListSchema, w as createdPersonalTokenSchema, z as activitySixHours$1 } from "./schema-CTOODa3L.js";
17
16
  import { Hono } from "hono";
18
17
  import path from "node:path";
19
18
  import { z } from "zod";
20
19
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
21
- import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, notExists, notInArray, or, sql } from "drizzle-orm";
20
+ import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lte, notExists, or, sql } from "drizzle-orm";
22
21
  import { conversationSidebarAnnotationSchema, pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
23
22
  import { alias } from "drizzle-orm/pg-core";
24
23
  import { readFileSync } from "node:fs";
@@ -1139,502 +1138,6 @@ async function readConversationFeed(options = {}) {
1139
1138
  return conversationFeedSchema.parse(await readConversationFeedFromSql(options));
1140
1139
  }
1141
1140
  //#endregion
1142
- //#region src/chat/scheduled-automations/personal.ts
1143
- const cursorSchema = z.object({
1144
- createdAtMs: z.number().finite(),
1145
- id: z.string().min(1),
1146
- query: z.string().max(200).optional(),
1147
- version: z.literal(1)
1148
- }).strict();
1149
- var InvalidScheduledAutomationCursorError = class extends Error {
1150
- constructor() {
1151
- super("Scheduled automation cursor is invalid.");
1152
- this.name = "InvalidScheduledAutomationCursorError";
1153
- }
1154
- };
1155
- var PersonalScheduledAutomationNotFoundError = class extends Error {
1156
- constructor() {
1157
- super("Scheduled automation was not found.");
1158
- this.name = "PersonalScheduledAutomationNotFoundError";
1159
- }
1160
- };
1161
- function normalizeQuery(query) {
1162
- return query?.trim().toLowerCase() || void 0;
1163
- }
1164
- function decodeCursor(value, query) {
1165
- if (!value) return void 0;
1166
- try {
1167
- const parsed = cursorSchema.parse(JSON.parse(Buffer.from(value, "base64url").toString("utf8")));
1168
- if (parsed.query !== query) throw new InvalidScheduledAutomationCursorError();
1169
- return {
1170
- createdAtMs: parsed.createdAtMs,
1171
- id: parsed.id
1172
- };
1173
- } catch {
1174
- throw new InvalidScheduledAutomationCursorError();
1175
- }
1176
- }
1177
- function encodeCursor(task, query) {
1178
- return Buffer.from(JSON.stringify({
1179
- createdAtMs: task.createdAtMs,
1180
- id: task.id,
1181
- ...query ? { query } : void 0,
1182
- version: 1
1183
- }), "utf8").toString("base64url");
1184
- }
1185
- /** Delete one scheduled automation created by the viewer. */
1186
- async function deleteViewerScheduledAutomation(db, user, id, nowMs = Date.now()) {
1187
- const identityIds = new Set(user.identities.map((identity) => identity.id));
1188
- const task = await readScheduledAutomation(db, id);
1189
- if (!task || task.status === "deleted" || !identityIds.has(task.creatorIdentityId)) throw new PersonalScheduledAutomationNotFoundError();
1190
- await saveScheduledAutomation(db, {
1191
- ...task,
1192
- nextRunAtMs: void 0,
1193
- runNowAtMs: void 0,
1194
- status: "deleted",
1195
- updatedAtMs: nowMs
1196
- });
1197
- }
1198
- /** List scheduled automations created by the viewer with a stable SQL cursor. */
1199
- async function listViewerScheduledAutomations(db, user, input) {
1200
- const identityIds = user.identities.map((identity) => identity.id);
1201
- if (identityIds.length === 0) return { automations: [] };
1202
- const query = normalizeQuery(input.query);
1203
- const cursor = decodeCursor(input.cursor, query);
1204
- const automations = [];
1205
- let before = cursor;
1206
- const fetchLimit = input.limit + 1;
1207
- while (automations.length < fetchLimit) {
1208
- const cursorFilter = before ? or(lt(juniorSchedulerTasks.createdAtMs, before.createdAtMs), and(eq(juniorSchedulerTasks.createdAtMs, before.createdAtMs), lt(juniorSchedulerTasks.id, before.id))) : void 0;
1209
- const search = query ? sql`strpos(lower(coalesce(${juniorSchedulerTasks.title}, ${juniorSchedulerTasks.record}->'task'->>'text')), ${query}) > 0` : void 0;
1210
- const rows = await db.select({
1211
- createdAtMs: juniorSchedulerTasks.createdAtMs,
1212
- creatorIdentityId: juniorSchedulerTasks.creatorIdentityId,
1213
- id: juniorSchedulerTasks.id,
1214
- record: juniorSchedulerTasks.record,
1215
- title: juniorSchedulerTasks.title
1216
- }).from(juniorSchedulerTasks).where(and(notInArray(juniorSchedulerTasks.status, ["deleted", "paused"]), inArray(juniorSchedulerTasks.creatorIdentityId, identityIds), cursorFilter, search)).orderBy(desc(juniorSchedulerTasks.createdAtMs), desc(juniorSchedulerTasks.id)).limit(fetchLimit);
1217
- automations.push(...rows.map(parseScheduledAutomationRow).filter(isListedScheduledAutomation));
1218
- if (rows.length < fetchLimit) break;
1219
- const last = rows.at(-1);
1220
- before = {
1221
- createdAtMs: last.createdAtMs,
1222
- id: last.id
1223
- };
1224
- }
1225
- const page = automations.slice(0, input.limit);
1226
- return {
1227
- automations: page,
1228
- ...automations.length > input.limit && page.length > 0 ? { nextCursor: encodeCursor(page.at(-1), query) } : void 0
1229
- };
1230
- }
1231
- //#endregion
1232
- //#region src/chat/automations/read.ts
1233
- const TASK_LIST_LIMIT = 100;
1234
- const TASK_FETCH_LIMIT = 101;
1235
- const TASK_EXECUTION_LIST_LIMIT = 100;
1236
- function creatorLabel(creator) {
1237
- return creator.fullName?.trim() || (creator.userName?.trim() ? `@${creator.userName.trim()}` : "") || creator.slackUserId;
1238
- }
1239
- function creatorKey(teamId, slackUserId) {
1240
- return `${teamId}:${slackUserId}`;
1241
- }
1242
- async function creatorProfileEmails(candidates) {
1243
- const selectors = new Map(candidates.map(({ task }) => {
1244
- const teamId = task.destination.teamId;
1245
- const slackUserId = task.createdBy.slackUserId;
1246
- return [creatorKey(teamId, slackUserId), {
1247
- slackUserId,
1248
- teamId
1249
- }];
1250
- }));
1251
- if (selectors.size === 0) return /* @__PURE__ */ new Map();
1252
- const rows = await getDb().select({
1253
- email: juniorUsers.primaryEmailNormalized,
1254
- slackUserId: juniorIdentities.providerSubjectId,
1255
- teamId: juniorIdentities.providerTenantId
1256
- }).from(juniorIdentities).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"), eq(juniorIdentities.emailVerified, true), or(...[...selectors.values()].map((selector) => and(eq(juniorIdentities.providerTenantId, selector.teamId), eq(juniorIdentities.providerSubjectId, selector.slackUserId))))));
1257
- return new Map(rows.map((row) => [creatorKey(row.teamId, row.slackUserId), row.email]));
1258
- }
1259
- function destinationKey(destination) {
1260
- return `${destination.teamId}:${destination.channelId}`;
1261
- }
1262
- function displayText(value, fallback) {
1263
- return value.trim() || fallback;
1264
- }
1265
- function taskDisplayTitle(title, instruction, fallback) {
1266
- const stored = title?.trim();
1267
- if (stored) return stored;
1268
- return fallbackShortTitle(instruction, fallback);
1269
- }
1270
- async function destinationDetails(destinations) {
1271
- const selectors = new Map(destinations.map((destination) => [destinationKey(destination), destination]));
1272
- if (selectors.size === 0) return /* @__PURE__ */ new Map();
1273
- const rows = await getDb().select({
1274
- displayName: juniorDestinations.displayName,
1275
- kind: juniorDestinations.kind,
1276
- providerDestinationId: juniorDestinations.providerDestinationId,
1277
- providerTenantId: juniorDestinations.providerTenantId,
1278
- visibility: juniorDestinations.visibility
1279
- }).from(juniorDestinations).where(or(...[...selectors.values()].map((destination) => and(eq(juniorDestinations.provider, "slack"), eq(juniorDestinations.providerTenantId, destination.teamId), eq(juniorDestinations.providerDestinationId, destination.channelId)))));
1280
- return new Map(rows.map((row) => {
1281
- const name = row.displayName?.trim();
1282
- const label = name ? row.kind === "channel" ? `#${name.replace(/^#/, "")}` : name : row.kind === "dm" ? "Direct message" : row.kind === "group" ? "Group message" : `Channel ${row.providerDestinationId}`;
1283
- return [`${row.providerTenantId}:${row.providerDestinationId}`, {
1284
- label,
1285
- visibility: row.visibility === "public" ? "public" : "private"
1286
- }];
1287
- }));
1288
- }
1289
- function executionSummaryFields(stats) {
1290
- return {
1291
- ...stats?.lastConversationId ? { lastConversationId: stats.lastConversationId } : void 0,
1292
- ...stats?.lastExecutedAtMs ? { lastRunAt: new Date(stats.lastExecutedAtMs).toISOString() } : void 0,
1293
- runs: stats?.runs ?? emptyAutomationRunWindows(),
1294
- totalRuns: stats?.totalRuns ?? 0
1295
- };
1296
- }
1297
- function scheduledAutomationSummary(task, ownedByViewer, destination, stats, createdByEmail) {
1298
- if (task.status === "deleted") throw new Error("Deleted scheduled automations cannot enter the Automations view");
1299
- const nextRunAtMs = task.runNowAtMs ?? task.nextRunAtMs;
1300
- const instruction = displayText(task.task.text, "Untitled scheduled automation");
1301
- return {
1302
- createdAt: new Date(task.createdAtMs).toISOString(),
1303
- createdBy: creatorLabel(task.createdBy),
1304
- ...createdByEmail ? { createdByEmail } : void 0,
1305
- destination: {
1306
- channelId: task.destination.channelId,
1307
- label: destination.label,
1308
- teamId: task.destination.teamId,
1309
- visibility: destination.visibility
1310
- },
1311
- id: task.id,
1312
- instruction,
1313
- kind: "scheduled",
1314
- ...executionSummaryFields(stats),
1315
- ...nextRunAtMs !== void 0 ? { nextRunAt: new Date(nextRunAtMs).toISOString() } : void 0,
1316
- ownedByViewer,
1317
- schedule: displayText(task.schedule.description, "Schedule unavailable"),
1318
- status: task.status,
1319
- outcomes: effectiveTaskOutcomes(task.outcomes, task.destination),
1320
- title: taskDisplayTitle(task.title, instruction, "Untitled scheduled automation")
1321
- };
1322
- }
1323
- function eventAutomationSummary(task, ownedByViewer, destination, stats, createdByEmail) {
1324
- const instruction = task.task.text;
1325
- return {
1326
- createdAt: new Date(task.createdAtMs).toISOString(),
1327
- createdBy: creatorLabel(task.createdBy),
1328
- ...createdByEmail ? { createdByEmail } : void 0,
1329
- destination: {
1330
- channelId: task.destination.channelId,
1331
- label: destination.label,
1332
- teamId: task.destination.teamId,
1333
- visibility: destination.visibility
1334
- },
1335
- events: task.trigger.events,
1336
- id: task.id,
1337
- instruction,
1338
- kind: "event",
1339
- ...executionSummaryFields(stats),
1340
- ownedByViewer,
1341
- resource: `${task.trigger.label} · ${task.trigger.identifier}`,
1342
- source: task.trigger.namespace,
1343
- outcomes: effectiveTaskOutcomes(task.outcomes, task.destination),
1344
- title: taskDisplayTitle(task.title, instruction, "Untitled event automation"),
1345
- triggerAvailable: eventAutomationTriggerAvailable(task, getEventCatalog())
1346
- };
1347
- }
1348
- function viewerTeamIds(user) {
1349
- return [...new Set(user.identities.filter((identity) => identity.provider === "slack").map((identity) => identity.providerTenantId).filter((teamId) => Boolean(teamId)))];
1350
- }
1351
- async function resolveViewerTaskCandidate(user, kind, id) {
1352
- const db = getDb();
1353
- const identityIds = new Set(user.identities.map((identity) => identity.id));
1354
- const teamIds = viewerTeamIds(user);
1355
- if (kind === "scheduled") {
1356
- const task = await readScheduledAutomation(db, id);
1357
- if (!task || task.status === "deleted") return void 0;
1358
- const ownedByViewer = identityIds.has(task.creatorIdentityId);
1359
- const destination = (await destinationDetails([task.destination])).get(destinationKey(task.destination));
1360
- const publicToViewer = teamIds.includes(task.destination.teamId) && destination?.visibility === "public";
1361
- if (!ownedByViewer && !publicToViewer) return void 0;
1362
- return {
1363
- kind: "scheduled",
1364
- ownedByViewer,
1365
- publicToViewer,
1366
- task
1367
- };
1368
- }
1369
- const task = await getEventAutomation(db, id);
1370
- if (!task || task.status === "deleted") return void 0;
1371
- const ownedByViewer = eventAutomationBelongsToUser(task, user);
1372
- const destination = (await destinationDetails([task.destination])).get(destinationKey(task.destination));
1373
- const publicToViewer = teamIds.includes(task.destination.teamId) && destination?.visibility === "public";
1374
- if (!ownedByViewer && !publicToViewer) return void 0;
1375
- return {
1376
- kind: "event",
1377
- ownedByViewer,
1378
- publicToViewer,
1379
- task
1380
- };
1381
- }
1382
- async function automationSummaryForCandidate(candidate) {
1383
- const [destinations, creatorEmails, stats] = await Promise.all([
1384
- destinationDetails([candidate.task.destination]),
1385
- creatorProfileEmails([candidate]),
1386
- readAutomationExecutionSummaries(candidate.kind, "junior")
1387
- ]);
1388
- const destination = destinations.get(destinationKey(candidate.task.destination)) ?? {
1389
- label: `Channel ${candidate.task.destination.channelId}`,
1390
- visibility: "private"
1391
- };
1392
- const createdByEmail = creatorEmails.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
1393
- if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), createdByEmail);
1394
- return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), createdByEmail);
1395
- }
1396
- /** Read viewer-owned and public-workspace automations as one bounded newest-first projection. */
1397
- function emptyAutomationExecutionDay(date) {
1398
- return {
1399
- costUsd: 0,
1400
- date,
1401
- event: 0,
1402
- scheduled: 0
1403
- };
1404
- }
1405
- function emptyAutomationExecutionStatusDay(date) {
1406
- return {
1407
- blocked: 0,
1408
- completed: 0,
1409
- date,
1410
- failed: 0
1411
- };
1412
- }
1413
- function automationExecutionSixHours(hours, nowMs = Date.now()) {
1414
- return sumUtcHoursIntoSixHours({
1415
- empty: emptyAutomationExecutionDay,
1416
- hours,
1417
- nowMs
1418
- });
1419
- }
1420
- function automationExecutionStatusSixHours(hours, nowMs = Date.now()) {
1421
- return sumUtcHoursIntoSixHours({
1422
- empty: emptyAutomationExecutionStatusDay,
1423
- hours,
1424
- nowMs
1425
- });
1426
- }
1427
- /** List one viewer's scheduled and event automations, optionally filtered by title or instruction search. */
1428
- async function readViewerAutomations(user, input = {}) {
1429
- const db = getDb();
1430
- const query = input.q?.trim().toLowerCase() || void 0;
1431
- const identityIds = new Set(user.identities.map((identity) => identity.id));
1432
- const teamIds = viewerTeamIds(user);
1433
- const [scheduledPage, publicScheduled, eventAutomations, publicEventAutomations] = await Promise.all([
1434
- listViewerScheduledAutomations(db, user, {
1435
- limit: TASK_FETCH_LIMIT,
1436
- query
1437
- }),
1438
- listPublicScheduledAutomationsForTeams(db, teamIds, {
1439
- limit: TASK_FETCH_LIMIT,
1440
- query
1441
- }),
1442
- listEventAutomationsCreatedBy(db, user, TASK_FETCH_LIMIT, query),
1443
- listPublicEventAutomationsForTeams(db, teamIds, TASK_FETCH_LIMIT, query)
1444
- ]);
1445
- const candidatesById = /* @__PURE__ */ new Map();
1446
- const publicScheduledIds = new Set(publicScheduled.map((task) => task.id));
1447
- const publicEventAutomationIds = new Set(publicEventAutomations.map((task) => task.id));
1448
- for (const task of [...scheduledPage.automations, ...publicScheduled]) candidatesById.set(`scheduled:${task.id}`, {
1449
- kind: "scheduled",
1450
- ownedByViewer: identityIds.has(task.creatorIdentityId),
1451
- publicToViewer: publicScheduledIds.has(task.id),
1452
- task
1453
- });
1454
- for (const task of [...eventAutomations, ...publicEventAutomations]) candidatesById.set(`event:${task.id}`, {
1455
- kind: "event",
1456
- ownedByViewer: eventAutomationBelongsToUser(task, user),
1457
- publicToViewer: publicEventAutomationIds.has(task.id),
1458
- task
1459
- });
1460
- const candidates = [...candidatesById.values()].sort((left, right) => right.task.createdAtMs - left.task.createdAtMs || right.task.id.localeCompare(left.task.id));
1461
- const ownedCandidates = candidates.filter((candidate) => candidate.ownedByViewer);
1462
- const publicCandidates = candidates.filter((candidate) => candidate.publicToViewer);
1463
- const selectedCandidates = /* @__PURE__ */ new Set([...ownedCandidates.slice(0, TASK_LIST_LIMIT), ...publicCandidates.slice(0, TASK_LIST_LIMIT)]);
1464
- const selected = candidates.filter((candidate) => selectedCandidates.has(candidate));
1465
- const [destinations, creatorEmails] = await Promise.all([destinationDetails(selected.map(({ task }) => task.destination)), creatorProfileEmails(selected)]);
1466
- const visible = selected.filter((candidate) => candidate.ownedByViewer || destinations.get(destinationKey(candidate.task.destination))?.visibility === "public");
1467
- const [executionDays, executionHours, scheduledStats, eventStats] = await Promise.all([
1468
- readAutomationExecutionDays(),
1469
- readAutomationExecutionHours(),
1470
- readAutomationExecutionSummaries("scheduled", "junior"),
1471
- readAutomationExecutionSummaries("event", "junior")
1472
- ]);
1473
- const automations = visible.map((candidate) => {
1474
- const destination = destinations.get(destinationKey(candidate.task.destination)) ?? {
1475
- label: `Channel ${candidate.task.destination.channelId}`,
1476
- visibility: "private"
1477
- };
1478
- const createdByEmail = creatorEmails.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
1479
- if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, scheduledStats.get(candidate.task.id), createdByEmail);
1480
- return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, eventStats.get(candidate.task.id), createdByEmail);
1481
- });
1482
- return {
1483
- executionDays,
1484
- executionHours,
1485
- executionSixHours: automationExecutionSixHours(executionHours),
1486
- automations,
1487
- truncated: ownedCandidates.length > TASK_LIST_LIMIT || publicCandidates.length > TASK_LIST_LIMIT
1488
- };
1489
- }
1490
- /** Load deleted scheduled automations the viewer still owns, newest first. */
1491
- async function readDeletedOwnedScheduledAutomations(user) {
1492
- const identityIds = user.identities.map((identity) => identity.id);
1493
- if (identityIds.length === 0) return [];
1494
- return (await getDb().select({
1495
- creatorIdentityId: juniorSchedulerTasks.creatorIdentityId,
1496
- id: juniorSchedulerTasks.id,
1497
- record: juniorSchedulerTasks.record,
1498
- title: juniorSchedulerTasks.title
1499
- }).from(juniorSchedulerTasks).where(and(eq(juniorSchedulerTasks.status, "deleted"), inArray(juniorSchedulerTasks.creatorIdentityId, identityIds))).orderBy(desc(juniorSchedulerTasks.createdAtMs), desc(juniorSchedulerTasks.id)).limit(TASK_EXECUTION_LIST_LIMIT)).map(parseScheduledAutomationRow).filter((task) => task?.status === "deleted");
1500
- }
1501
- /** Load deleted event automations the viewer still owns, newest first. */
1502
- async function readDeletedOwnedEventAutomations(user) {
1503
- return await listDeletedEventAutomationsCreatedBy(getDb(), user, TASK_EXECUTION_LIST_LIMIT);
1504
- }
1505
- function automationTitleForRun(run, automationTitles) {
1506
- return automationTitles.get(`${run.kind}:${run.automationId}`) ?? run.title?.trim() ?? "Untitled task";
1507
- }
1508
- function addDeletedAutomationRun(args, automationTitles, automations) {
1509
- const key = `${args.kind}:${args.automationId}`;
1510
- if (automationTitles.has(key)) return;
1511
- automationTitles.set(key, args.title);
1512
- automations.push({
1513
- kind: args.kind,
1514
- automationId: args.automationId
1515
- });
1516
- }
1517
- /**
1518
- * Read newest runs across live viewer-visible automations and deleted automations the
1519
- * viewer owns. Deleted task rows stay available so history does not depend on
1520
- * conversation actor membership.
1521
- */
1522
- async function readViewerAutomationRuns(user) {
1523
- const [taskList, deletedScheduled, deletedEvent] = await Promise.all([
1524
- readViewerAutomations(user),
1525
- readDeletedOwnedScheduledAutomations(user),
1526
- readDeletedOwnedEventAutomations(user)
1527
- ]);
1528
- const automationTitles = /* @__PURE__ */ new Map();
1529
- const automations = [];
1530
- for (const task of taskList.automations) {
1531
- automationTitles.set(`${task.kind}:${task.id}`, task.title);
1532
- automations.push({
1533
- kind: task.kind,
1534
- automationId: task.id
1535
- });
1536
- }
1537
- for (const task of deletedScheduled) {
1538
- const instruction = displayText(task.task.text, "Untitled scheduled automation");
1539
- addDeletedAutomationRun({
1540
- kind: "scheduled",
1541
- automationId: task.id,
1542
- title: taskDisplayTitle(task.title, instruction, "Untitled scheduled automation")
1543
- }, automationTitles, automations);
1544
- }
1545
- for (const task of deletedEvent) {
1546
- const instruction = displayText(task.task.text, "Untitled event automation");
1547
- addDeletedAutomationRun({
1548
- kind: "event",
1549
- automationId: task.id,
1550
- title: taskDisplayTitle(task.title, instruction, "Untitled event automation")
1551
- }, automationTitles, automations);
1552
- }
1553
- const runs = await readAutomationRuns({
1554
- limit: 101,
1555
- automations
1556
- });
1557
- return {
1558
- runs: runs.slice(0, TASK_EXECUTION_LIST_LIMIT).map((run) => ({
1559
- ...run,
1560
- automationTitle: automationTitleForRun(run, automationTitles)
1561
- })),
1562
- truncated: runs.length > TASK_EXECUTION_LIST_LIMIT
1563
- };
1564
- }
1565
- var ViewerTaskNotFoundError = class extends Error {
1566
- constructor() {
1567
- super("Task was not found.");
1568
- this.name = "ViewerTaskNotFoundError";
1569
- }
1570
- };
1571
- /** Read one viewer-visible task and its newest terminal executions. */
1572
- async function readViewerAutomationExecutions(user, kind, id) {
1573
- const candidate = await resolveViewerTaskCandidate(user, kind, id);
1574
- if (!candidate) throw new ViewerTaskNotFoundError();
1575
- const [automation, executions, executionDays, executionHours] = await Promise.all([
1576
- automationSummaryForCandidate(candidate),
1577
- readAutomationExecutions({
1578
- kind,
1579
- limit: 101,
1580
- automationId: id
1581
- }),
1582
- readAutomationExecutionStatusDays({
1583
- kind,
1584
- automationId: id
1585
- }),
1586
- readAutomationExecutionStatusHours({
1587
- kind,
1588
- automationId: id
1589
- })
1590
- ]);
1591
- return {
1592
- executionDays,
1593
- executionHours,
1594
- executionSixHours: automationExecutionStatusSixHours(executionHours),
1595
- executions: executions.slice(0, TASK_EXECUTION_LIST_LIMIT),
1596
- automation,
1597
- truncated: executions.length > TASK_EXECUTION_LIST_LIMIT
1598
- };
1599
- }
1600
- /** Resolve the source task for one conversation when a terminal execution links it. */
1601
- async function readConversationSourceTask(args) {
1602
- const execution = await readAutomationExecutionByConversationId({ conversationId: args.conversationId });
1603
- if (!execution) return void 0;
1604
- if (!args.viewer) return { kind: execution.kind };
1605
- const candidate = await resolveViewerTaskCandidate(args.viewer, execution.kind, execution.automationId);
1606
- if (!candidate) return { kind: execution.kind };
1607
- if (candidate.kind === "scheduled") {
1608
- const instruction = displayText(candidate.task.task.text, "Untitled scheduled automation");
1609
- return {
1610
- id: candidate.task.id,
1611
- kind: "scheduled",
1612
- label: instruction,
1613
- title: taskDisplayTitle(candidate.task.title, instruction, "Untitled scheduled automation")
1614
- };
1615
- }
1616
- const instruction = displayText(candidate.task.task.text, "Untitled event automation");
1617
- return {
1618
- id: candidate.task.id,
1619
- kind: "event",
1620
- label: instruction,
1621
- title: taskDisplayTitle(candidate.task.title, instruction, "Untitled event automation")
1622
- };
1623
- }
1624
- /** Delete one viewer-owned scheduled or event automation. */
1625
- async function deleteViewerTask(user, kind, id) {
1626
- if (kind === "scheduled") try {
1627
- await deleteViewerScheduledAutomation(getDb(), user, id);
1628
- return;
1629
- } catch (error) {
1630
- if (error instanceof PersonalScheduledAutomationNotFoundError) throw new ViewerTaskNotFoundError();
1631
- throw error;
1632
- }
1633
- const task = await getEventAutomation(getDb(), id);
1634
- if (!task || task.status === "deleted" || !eventAutomationBelongsToUser(task, user)) throw new ViewerTaskNotFoundError();
1635
- await deleteEventAutomation(getDb(), id);
1636
- }
1637
- //#endregion
1638
1141
  //#region src/api/conversations/detail.ts
1639
1142
  /** Project stored metadata and a bounded event page into a signed history cursor. */
1640
1143
  function projectConversationDetail(args) {
@@ -3514,7 +3017,7 @@ async function readPeoplePluginReports(args) {
3514
3017
  reports: [],
3515
3018
  source: "plugins"
3516
3019
  });
3517
- const { getPluginProfileReports } = await import("./agent-hooks-BnZBgDPe.js").then((n) => n.t);
3020
+ const { getPluginProfileReports } = await import("./agent-hooks-DkriF84n.js").then((n) => n.t);
3518
3021
  return pluginOperationalReportFeedSchema.parse({
3519
3022
  generatedAt: new Date(nowMs).toISOString(),
3520
3023
  reports: await getPluginProfileReports({
@@ -4123,7 +3626,7 @@ function readDescriptionText(home) {
4123
3626
  }
4124
3627
  /** Read discovered skill names for authenticated runtime diagnostics. */
4125
3628
  async function readSkillReports() {
4126
- const { discoverSkills } = await import("./skills-DMQkR1Yu.js").then((n) => n.o);
3629
+ const { discoverSkills } = await import("./skills-BoS3b8cg.js").then((n) => n.o);
4127
3630
  const skills = await discoverSkills();
4128
3631
  return skillReportsSchema.parse(skills.map((skill) => ({
4129
3632
  name: skill.name,
@@ -4132,7 +3635,7 @@ async function readSkillReports() {
4132
3635
  }
4133
3636
  /** Read safe configured plugin metadata for authenticated runtime diagnostics. */
4134
3637
  async function readPlugins() {
4135
- const { pluginCatalogRuntime } = await import("./catalog-runtime-0oMD2jas.js").then((n) => n.t);
3638
+ const { pluginCatalogRuntime } = await import("./catalog-runtime-XH_LFA_7.js").then((n) => n.t);
4136
3639
  return pluginsSchema.parse(pluginCatalogRuntime.getProviders().map((plugin) => ({
4137
3640
  configKeys: plugin.manifest.configKeys ?? [],
4138
3641
  description: plugin.manifest.description,
@@ -4144,7 +3647,7 @@ async function readPlugins() {
4144
3647
  async function readRuntimeInfoReport() {
4145
3648
  const [{ homeDir }, { pluginCatalogRuntime }, plugins, skills] = await Promise.all([
4146
3649
  import("./package-discovery-7a9YqLhE.js").then((n) => n.r),
4147
- import("./catalog-runtime-0oMD2jas.js").then((n) => n.t),
3650
+ import("./catalog-runtime-XH_LFA_7.js").then((n) => n.t),
4148
3651
  readPlugins(),
4149
3652
  readSkillReports()
4150
3653
  ]);
@@ -4161,7 +3664,7 @@ async function readRuntimeInfoReport() {
4161
3664
  /** Read sanitized operational summaries contributed by plugins. */
4162
3665
  async function readPluginOperationalReportFeed() {
4163
3666
  const nowMs = Date.now();
4164
- const { getPluginOperationalReports } = await import("./agent-hooks-BnZBgDPe.js").then((n) => n.t);
3667
+ const { getPluginOperationalReports } = await import("./agent-hooks-DkriF84n.js").then((n) => n.t);
4165
3668
  return pluginOperationalReportFeedSchema.parse({
4166
3669
  source: "plugins",
4167
3670
  generatedAt: new Date(nowMs).toISOString(),
@@ -1,5 +1,5 @@
1
1
  import { t as ConversationStore } from "./store-DoewL5mG.js";
2
- import "./history-ClE4toxe.js";
2
+ import "./history-CaV8Ww7M.js";
3
3
  import { n as JuniorPluginSet } from "./plugins-BT2l4We3.js";
4
4
  import { Hono } from "hono";
5
5
  import "@earendil-works/pi-ai/compat";
package/dist/app.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as ModelProfileInput, n as JuniorDashboardOptions, r as createApp, t as JuniorAppOptions } from "./app-BYD2Nyji.js";
1
+ import { i as ModelProfileInput, n as JuniorDashboardOptions, r as createApp, t as JuniorAppOptions } from "./app-C0zbsnr7.js";
2
2
  import { i as defineJuniorPlugins, n as JuniorPluginSet, r as JuniorPluginSetOptions, t as JuniorPluginInput } from "./plugins-BT2l4We3.js";
3
3
  import { t as JUNIOR_VERSION } from "./version-CnXZ614E.js";
4
4
  export { JUNIOR_VERSION, JuniorAppOptions, JuniorDashboardOptions, type JuniorPluginInput, type JuniorPluginSet, type JuniorPluginSetOptions, type ModelProfileInput, createApp, defineJuniorPlugins };