@sentry/junior 0.300.0 → 0.302.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 (81) hide show
  1. package/dist/adapter-context-Cx9fn9B3.js +43 -0
  2. package/dist/{admin-UrTniSPO.js → admin-_poE5NKL.js} +2 -2
  3. package/dist/{agent-runner-bY4_0UPm.js → agent-runner-CY9RvsTX.js} +1367 -10649
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +6 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +124 -67
  8. package/dist/{app-D-AcIcCV.d.ts → app-BpY3wtRP.d.ts} +3 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +71 -299
  11. package/dist/{automation-Dw82oQ-h.js → automation-Cva5ZOwW.js} +1 -1
  12. package/dist/{background-compaction-queue-B6U3060-.js → background-compaction-queue-CXFq1_Cz.js} +94 -203
  13. package/dist/{briefs-DqiwWu-n.js → briefs-B3NG-pid.js} +3 -3
  14. package/dist/{catalog-runtime-D1oYNv04.js → catalog-runtime-Dss0lSV6.js} +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-9nHoFiJP.js → config-CzeZiMKs.js} +2 -2
  23. package/dist/{connections-DZjTN3JC.js → connections-CDYhMfrs.js} +6 -6
  24. package/dist/{continue-in-slack-Dtv7_U42.js → continue-in-slack-7Uf05ndC.js} +5 -6
  25. package/dist/{conversation-Dyjq2CZ8.js → conversation-BNXfq6Lb.js} +11 -1
  26. package/dist/{conversation-feed-CcDxlrlQ.js → conversation-feed-Clf_cv0n.js} +2 -1
  27. package/dist/{conversation-privacy-D-5HTXjS.js → conversation-privacy-D9xnM5mK.js} +1 -1
  28. package/dist/{conversation-turn-Cxl8WZD7.js → conversation-turn-D7SEZgTG.js} +16 -17
  29. package/dist/{credential-sync-C49ClwDX.js → credential-sync-DoD0gW-j.js} +13 -15
  30. package/dist/{db-BJNo6fK5.js → db-B-gtnNjr.js} +314 -5
  31. package/dist/{db-2resqBh1.d.ts → db-BdsCzytP.d.ts} +1 -1
  32. package/dist/{executor-DBIaOeJ_.js → executor-DZg20EqU.js} +39 -4
  33. package/dist/install-t1KQyTUs.js +228 -0
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{state-zSilNpbi.js → legacy-web-actor-id-C-cEeWqL.js} +33 -4
  36. package/dist/{lineage-0dereG7H.js → lineage-C79GjoQr.js} +2 -2
  37. package/dist/{logging-BIclibct.js → logging-C9oDAg4M.js} +7 -3
  38. package/dist/{message-dkOl-Iii.js → message-BLUCzJXN.js} +8 -8
  39. package/dist/{model-input-CLo9TaUd.js → model-input-5jwNC45G.js} +3 -3
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +4 -3
  42. package/dist/{oauth-callback-server-WmpjfJgQ.js → oauth-callback-server-BBl66vCb.js} +2 -2
  43. package/dist/{projection-w_X-zi7v.js → projection-CIBwgD3s.js} +437 -97
  44. package/dist/{prompt-B1Xw46-S.js → prompt-CRQbzp5e.js} +15 -5
  45. package/dist/queue-DtCDaIct.js +115 -0
  46. package/dist/{registry-BmP5vnlj.js → registry-DdFQHZ_d.js} +1 -1
  47. package/dist/{resolve-goo34bJK.js → resolve-CdW4BdrK.js} +4 -229
  48. package/dist/{result-PVBeU0Wf.js → result-oOMv1t4O.js} +9 -9
  49. package/dist/{runner-DKrfvNV6.js → runner-DqitLtm-.js} +9 -9
  50. package/dist/{sandbox-egress-signals-DsUcqrI0.js → sandbox-egress-signals-Bw9I0yfJ.js} +1 -1
  51. package/dist/{schema-Dns-sTas.d.ts → schema-BIFM-U1a.d.ts} +470 -30
  52. package/dist/{schema-C9iNFz5n.js → schema-DnVQepWP.js} +76 -31
  53. package/dist/{service-account-CMAAloAL.js → service-account-B6mKAPVo.js} +3 -3
  54. package/dist/{service-account-CmowamcB.js → service-account-CrZftRTb.js} +257 -6
  55. package/dist/{session-stop-BcAXze8a.js → session-stop-DW63Z3kj.js} +1103 -1007
  56. package/dist/{skills-DfsazET6.js → skills-C16fz60Z.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-CzQonuWz.js → slack-conversation-unfurl-BHhefEb7.js} +8 -7
  58. package/dist/{spawn-C7o0FDDp.js → spawn-D_RnFYfy.js} +6 -6
  59. package/dist/{stop-CFOujp8C.js → stop-7p1i08CY.js} +941 -2311
  60. package/dist/{store-E3x2Fg_F.js → store-C28I0CVW.js} +5 -5
  61. package/dist/{task-queue-D-hCqdZW.js → task-queue-BVUJbQ28.js} +3 -3
  62. package/dist/{task-runner-vohUPLHe.js → task-runner-CWi8j7Z6.js} +6 -8
  63. package/dist/{thread-context-BzvdkgI9.js → thread-context-D3-yYUd0.js} +8 -8
  64. package/dist/{store-Dkeis_8o.js → turn-session-routing-BFMS9ATF.js} +382 -11
  65. package/dist/{turn-user-message-D5RnVmxQ.js → turn-user-message-C3-O8Omt.js} +3 -3
  66. package/dist/{validation-BbWikeSa.js → validation-BSFKUIb4.js} +1 -1
  67. package/dist/{version-GVBMW2jA.js → version-BHHXNi-0.js} +1 -1
  68. package/dist/version.js +1 -1
  69. package/dist/{viewer-BpxRliyO.js → viewer-B1SO21Qa.js} +3 -3
  70. package/dist/warmup-Bz9bzkzN.js +13927 -0
  71. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  72. package/dist/{worker-Cbd-iuwZ.js → worker-BspReIIK.js} +7 -7
  73. package/migrations/0108_conversation_embeddings.sql +13 -0
  74. package/migrations/meta/0108_snapshot.json +4688 -0
  75. package/migrations/meta/_journal.json +7 -0
  76. package/package.json +10 -8
  77. package/dist/adapter-S5UkjNK3.js +0 -303
  78. package/dist/reporting-window-DopzcOHh.js +0 -137
  79. package/dist/turn-session-routing-Bo_LxFum.js +0 -380
  80. package/dist/users-2bggndVg.js +0 -424
  81. package/dist/warmup-BW2qwnal.js +0 -3693
@@ -1,24 +1,24 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Ai as getDashboardObjectIconLink, Bn as SCRIPT_TOOLS_SECTION_TAG, Di as JUNIOR_THREAD_STATE_TTL_MS, Ei as verifyTimerWatchCredentialSubject, Fn as retainRuntimeTurnContext, Gi as listWorkspaces, Hn as TURN_CONTEXT_TAG, In as stripRuntimeTurnContext, Jn as renderUntrustedTag, Kn as renderChildTag, M as normalizeConversationText, Mr as getReviewItem, Nn as latestTurnContextSection, Oi as getDashboardConversationLink, Po as buildSentryConversationUrl, Qa as ToolInputError, Rn as CAPABILITY_SECTION_TAG, Ta as postSlackMessage, Tn as hasRuntimeTurnContext, Un as escapeClosingTags, Vn as SESSION_CONTEXT_SECTION_TAG, Wn as escapeTagText, Yn as tagJson, ao as SANDBOX_REPOS_ROOT, co as sandboxSkillDir, cr as getPluginSystemPromptContributions, ct as listTurnSummaries, dr as getPlugins, fa as escapeSlackMrkdwnText, fn as NO_REPLY_TOOL_NAME, in as REPLY_TOOL_NAME, io as SANDBOX_DATA_ROOT, lo as sandboxSkillFile, ma as normalizeSlackReplyMarkdown, ot as getStoredTurnFields, pa as formatSlackLink, qn as renderTag$1, so as SANDBOX_WORKSPACE_ROOT, sr as getPluginSlackConversationLink, st as getTurnRecord, ui as cancelSubscriptions, uo as sandboxSkillPathResolution, ur as getPluginUserPromptContributions, vn as REPORT_BLOCKED_TOOL_NAME, x as toStoredConversationMessage, zn as REQUEST_CONTEXT_SECTION_TAG } from "./projection-w_X-zi7v.js";
3
- import { I as renderCurrentInstruction, R as escapeXml, n as botConfig, z as escapeXmlText } from "./config-9nHoFiJP.js";
4
- import { h as logWarn, m as logInfo, p as logException, v as serializeGenAiAttribute } from "./logging-BIclibct.js";
2
+ import { Bn as SCRIPT_TOOLS_SECTION_TAG, Da as postSlackMessage, Di as verifyTimerWatchCredentialSubject, Fn as retainRuntimeTurnContext, Hn as TURN_CONTEXT_TAG, In as stripRuntimeTurnContext, Io as buildSentryConversationUrl, Jn as renderUntrustedTag, Ki as listWorkspaces, Kn as renderChildTag, M as normalizeConversationText, Nn as latestTurnContextSection, Nr as getReviewItem, Oi as JUNIOR_THREAD_STATE_TTL_MS, Rn as CAPABILITY_SECTION_TAG, Tn as hasRuntimeTurnContext, Un as escapeClosingTags, Vn as SESSION_CONTEXT_SECTION_TAG, Wn as escapeTagText, Yn as tagJson, _a as slackMention, ct as listTurnSummaries, di as cancelSubscriptions, do as sandboxSkillFile, eo as ToolInputError, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillPathResolution, ha as normalizeSlackReplyMarkdown, in as REPLY_TOOL_NAME, ji as getDashboardObjectIconLink, ki as getDashboardConversationLink, lo as SANDBOX_WORKSPACE_ROOT, lr as getPluginUserPromptContributions, ma as formatSlackLink, oo as SANDBOX_DATA_ROOT, or as getPluginSlackConversationLink, ot as getStoredTurnFields, pa as escapeSlackMrkdwnText, qn as renderTag$1, so as SANDBOX_REPOS_ROOT, sr as getPluginSystemPromptContributions, st as getTurnRecord, uo as sandboxSkillDir, ur as getPlugins, vn as REPORT_BLOCKED_TOOL_NAME, x as toStoredConversationMessage, zn as REQUEST_CONTEXT_SECTION_TAG } from "./projection-CIBwgD3s.js";
3
+ import { I as renderCurrentInstruction, R as escapeXml, n as botConfig, z as escapeXmlText } from "./config-CzeZiMKs.js";
4
+ import { G as normalizeIdentityEmail, h as logWarn, m as logInfo, p as logException, v as serializeGenAiAttribute } from "./logging-C9oDAg4M.js";
5
5
  import { o as isUserActor, t as createActor } from "./actor-D2iXzvlN.js";
6
- import { C as isPersonInput, a as getConversationStore, j as SYSTEM_IDENTITY_ID, nt as nextDetailVersion, o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db-BJNo6fK5.js";
7
- import { N as juniorUsers, j as juniorConversations } from "./executor-DBIaOeJ_.js";
8
- import { r as getStateAdapter } from "./adapter-S5UkjNK3.js";
6
+ import { C as isPersonInput, J as getStateAdapter, M as SYSTEM_IDENTITY_ID, a as getConversationStore, ft as nextDetailVersion, o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db-B-gtnNjr.js";
7
+ import { M as juniorConversations, N as juniorIdentities, P as juniorUsers } from "./executor-DZg20EqU.js";
9
8
  import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-DJhGdS4c.js";
10
- import { h as credentialSubjectSchema } from "./registry-BmP5vnlj.js";
11
- import { i as parseSkillFile } from "./skills-DfsazET6.js";
12
- import { a as EVENT_SYSTEM_ACTOR, d as JUNIOR_NATIVE_EVENT_NAMESPACE, h as conversationNoteEvent, i as EVENT_MESSAGE_AUTHOR, o as isEventConversationMessage, r as EVENT_AUTHOR_ID } from "./prompt-B1Xw46-S.js";
13
- import { r as appendAndEnqueueInboundMessage } from "./store-E3x2Fg_F.js";
14
- import { f as eventCatalogEntry, l as CORE_EVENT_NAMESPACE, p as eventGuidance } from "./turn-session-routing-Bo_LxFum.js";
15
- import { _ as userCustomizationTextSchema, m as isVisionImageMediaType, s as formatUserInputAnswer } from "./statuses-Hn-HsOph.js";
9
+ import { h as credentialSubjectSchema } from "./registry-DdFQHZ_d.js";
10
+ import { i as parseSkillFile } from "./skills-C16fz60Z.js";
11
+ import { a as EVENT_SYSTEM_ACTOR, f as JUNIOR_NATIVE_EVENT_NAMESPACE, g as conversationNoteEvent, i as EVENT_MESSAGE_AUTHOR, o as isEventConversationMessage, r as EVENT_AUTHOR_ID } from "./prompt-CRQbzp5e.js";
12
+ import { bt as eventGuidance, gt as CORE_EVENT_NAMESPACE, yt as eventCatalogEntry } from "./turn-session-routing-BFMS9ATF.js";
13
+ import { c as formatUserInputAnswer, h as isVisionImageMediaType, v as userCustomizationTextSchema } from "./web-message-id-lNodcCOI.js";
14
+ import { r as appendAndEnqueueInboundMessage } from "./store-C28I0CVW.js";
16
15
  import * as z from "zod";
17
16
  import path from "node:path";
18
17
  import { isDeepStrictEqual } from "node:util";
19
18
  import { createHash } from "node:crypto";
20
19
  import { and, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
21
20
  import { agentEventKeys, createEventSource, createLocalSource, createWebSource, eventMatchFieldsSchema, objectFactFields, objectPresentation, objectTypeSchema } from "@sentry/junior-plugin-api";
21
+ import { alias } from "drizzle-orm/pg-core";
22
22
  import fs from "node:fs";
23
23
  import pLimit from "p-limit";
24
24
  // src/chat/repository-instructions.ts
@@ -1114,1069 +1114,1206 @@ async function buildDeploymentSystemPrompt(platform, mode) {
1114
1114
  const pluginSystemPrompt = buildPluginSystemPromptContributions(await getPluginSystemPromptContributions(platform));
1115
1115
  return [buildSystemPrompt(platform, mode), pluginSystemPrompt].filter((section) => Boolean(section)).join("\n\n");
1116
1116
  }
1117
- /** Hash a system prompt, to compare prompts without storing their text. */
1118
- function systemPromptHash(systemPrompt) {
1119
- return createHash("sha256").update(systemPrompt).digest("hex").slice(0, 16);
1120
- }
1121
- // src/chat/conversations/sql/subtree.ts
1122
- /** Columns of the `conversation_subtree` table that `conversationSubtree` returns. */
1123
- const conversationSubtreeColumns = {
1124
- conversationId: sql`conversation_subtree.conversation_id`,
1125
- scopeConversationId: sql`conversation_subtree.scope_conversation_id`
1126
- };
1117
+ // src/chat/sandbox/snapshot/events.ts
1118
+ const WORKSPACE_SNAPSHOT_NAMESPACE = CORE_EVENT_NAMESPACE;
1119
+ const WORKSPACE_SNAPSHOT_RESOURCE_TYPE = "workspace_snapshot";
1120
+ const WORKSPACE_SNAPSHOT_READY_EVENT = "workspace_snapshot.ready";
1121
+ const WORKSPACE_SNAPSHOT_FAILED_EVENT = "workspace_snapshot.failed";
1127
1122
  /**
1128
- * Return a joinable `conversation_subtree` table. It maps each selected
1129
- * Conversation to itself and to each descendant child Conversation at any
1130
- * depth. Reports use it so that a total for a Conversation always includes the
1131
- * work of all its child agents.
1123
+ * Core catalog entry for Workspace snapshot ready and failed events.
1132
1124
  *
1133
- * A descendant must have the same root as the selected Conversation. Thus a
1134
- * Conversation that has no valid root gets only its own work.
1125
+ * Uses the same registration shape as plugins so search, guidance, and tool
1126
+ * schemas treat these events like any other resource type. Snapshot finish
1127
+ * does not run event-automation ingest, so only watches can use these events.
1135
1128
  */
1136
- function conversationSubtree(conversationIds) {
1137
- const selectedIds = sql.join(conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
1138
- return sql`(
1139
- with recursive tree(scope_conversation_id, conversation_id, root_conversation_id) as (
1140
- select selected.conversation_id, selected.conversation_id, selected.root_conversation_id
1141
- from junior_conversations selected
1142
- where selected.conversation_id in (${selectedIds})
1143
- union
1144
- select tree.scope_conversation_id, child.conversation_id, child.root_conversation_id
1145
- from junior_conversations child
1146
- join tree
1147
- on child.parent_conversation_id = tree.conversation_id
1148
- and (child.root_conversation_id || '') = tree.root_conversation_id
1149
- )
1150
- select scope_conversation_id, conversation_id from tree
1151
- ) conversation_subtree`;
1152
- }
1153
- // src/chat/services/automated-turn-limit.ts
1154
- const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
1155
- const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
1156
- const AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS = 2e3;
1157
- const AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS = 25;
1158
- /** Stored consecutive automated-turn count for one Conversation. */
1159
- const automatedTurnLimitStateSchema = z.object({
1160
- consecutiveAutomatedTurns: z.number().int().nonnegative(),
1161
- noticePostedAtMs: z.number().finite().nonnegative().optional(),
1162
- paused: z.boolean(),
1163
- updatedAtMs: z.number().finite().nonnegative()
1164
- }).strict();
1165
- function sleep(ms) {
1166
- return new Promise((resolve) => {
1167
- setTimeout(resolve, ms).unref?.();
1168
- });
1169
- }
1170
- function conversationKey(conversationId) {
1171
- return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
1172
- }
1173
- function lockKey(key) {
1174
- return `${key}:lock`;
1129
+ function workspaceSnapshotEvents() {
1130
+ return {
1131
+ resourceTypes: [{
1132
+ type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE,
1133
+ supportedEvents: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
1134
+ suggestedEvents: []
1135
+ }],
1136
+ events: {
1137
+ [WORKSPACE_SNAPSHOT_READY_EVENT]: {
1138
+ reach: "resource",
1139
+ guidance: "Call switchWorkspace again with the same Workspace name. Do not create another watch when switchWorkspace already returned a subscription."
1140
+ },
1141
+ [WORKSPACE_SNAPSHOT_FAILED_EVENT]: {
1142
+ reach: "resource",
1143
+ guidance: "Report the snapshot failure. Do not keep waiting for this Workspace unless the user asks to retry."
1144
+ }
1145
+ },
1146
+ limits: { [WORKSPACE_SNAPSHOT_RESOURCE_TYPE]: { automation: false } }
1147
+ };
1175
1148
  }
1176
- function parseState(value) {
1177
- const parsed = automatedTurnLimitStateSchema.safeParse(value);
1178
- return parsed.success ? parsed.data : void 0;
1149
+ /** Describe the events that report when a snapshot build ends. */
1150
+ function workspaceSnapshotWatch(input) {
1151
+ return {
1152
+ identifier: input.workspaceId,
1153
+ label: `Workspace ${input.workspaceName} snapshot`,
1154
+ namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
1155
+ supported_events: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
1156
+ suggested_events: [],
1157
+ type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE
1158
+ };
1179
1159
  }
1180
- async function acquireConversationLock(state, key, waitDeadlineMs = Date.now() + AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS) {
1181
- while (true) {
1182
- const lock = await state.acquireLock(lockKey(key), AUTOMATED_TURN_LIMIT_LOCK_TTL_MS);
1183
- if (lock) return lock;
1184
- if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire automated turn limit lock for ${key}`);
1185
- await sleep(AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS);
1186
- }
1160
+ /** Report that a Workspace snapshot build is ready or failed. */
1161
+ function workspaceSnapshotFinishedEvent(input) {
1162
+ const occurredAtMs = input.occurredAtMs ?? Date.now();
1163
+ const eventType = input.status === "ready" ? WORKSPACE_SNAPSHOT_READY_EVENT : WORKSPACE_SNAPSHOT_FAILED_EVENT;
1164
+ const trustedSummary = input.status === "ready" ? "Workspace snapshot is ready." : "Workspace snapshot build failed.";
1165
+ const event = {
1166
+ eventKey: `${WORKSPACE_SNAPSHOT_NAMESPACE}:${input.workspaceId}:${input.resultId}:${input.status}`,
1167
+ eventType,
1168
+ identifier: input.workspaceId,
1169
+ namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
1170
+ occurredAtMs,
1171
+ terminal: true,
1172
+ trustedSummary,
1173
+ data: {
1174
+ workspaceId: input.workspaceId,
1175
+ status: input.status
1176
+ }
1177
+ };
1178
+ if (input.status === "failed" && input.error) event.untrustedText = input.error;
1179
+ return event;
1187
1180
  }
1188
- async function withConversationLock(state, key, callback) {
1189
- const lock = await acquireConversationLock(state, key);
1190
- try {
1191
- return await callback();
1192
- } finally {
1193
- await state.releaseLock(lock);
1181
+ // src/chat/slack/channel-message-events.ts
1182
+ /**
1183
+ * Slack channel-message Events for Event automations.
1184
+ *
1185
+ * Core publishes these Events from Slack ingress, so the `slack` namespace is
1186
+ * core owned, like `junior`. Anyone in the channel writes the Event text, so an
1187
+ * automation can watch only its own channel and always uses system credentials.
1188
+ */
1189
+ /** Core-owned event namespace for Slack Events. Not a plugin publisher. */
1190
+ const SLACK_EVENT_NAMESPACE = "slack";
1191
+ /** The trigger identifier that names the channel of the automation. */
1192
+ const SLACK_CURRENT_CHANNEL_IDENTIFIER = "current_channel";
1193
+ const CHANNEL_RESOURCE_TYPE = "channel";
1194
+ const MESSAGE_POSTED_EVENT = "message.posted";
1195
+ const CHANNEL_ID_PATTERN = /^[CG][A-Z0-9]{2,}$/;
1196
+ const CHANNEL_LOCATION = "channel";
1197
+ const THREAD_LOCATION = "thread";
1198
+ const CHANNEL_MESSAGE_MATCH_FIELDS = eventMatchFieldsSchema.parse({
1199
+ channelId: {
1200
+ kind: "string",
1201
+ description: "Slack channel ID of the message. It is always the channel where the automation posts.",
1202
+ events: [MESSAGE_POSTED_EVENT]
1203
+ },
1204
+ userId: {
1205
+ kind: "string",
1206
+ description: "Slack user ID of the message author, or the bot ID (B…) of a bot post that has no user, such as an app integration. Required to run on bot posts."
1207
+ },
1208
+ location: {
1209
+ kind: "string",
1210
+ enum: [CHANNEL_LOCATION, THREAD_LOCATION],
1211
+ description: "channel for a top-level message, thread for a thread reply. Leave out for top-level only; thread replies run only when this names thread."
1194
1212
  }
1195
- }
1196
- function emptyState(nowMs) {
1213
+ });
1214
+ /**
1215
+ * Event registration for new Slack channel messages and thread replies. Only
1216
+ * event automations can use it, so watchEvents rejects it.
1217
+ */
1218
+ function slackChannelMessageEvents() {
1197
1219
  return {
1198
- consecutiveAutomatedTurns: 0,
1199
- paused: false,
1200
- updatedAtMs: nowMs
1220
+ resourceTypes: [{
1221
+ type: CHANNEL_RESOURCE_TYPE,
1222
+ identifier: {
1223
+ format: `"${SLACK_CURRENT_CHANNEL_IDENTIFIER}" for the channel where the automation is created`,
1224
+ pattern: String.raw`^(?:current_channel|[CG][A-Z0-9]{2,})$`
1225
+ },
1226
+ supportedEvents: [MESSAGE_POSTED_EVENT],
1227
+ suggestedEvents: [],
1228
+ matchFields: CHANNEL_MESSAGE_MATCH_FIELDS
1229
+ }],
1230
+ events: { [MESSAGE_POSTED_EVENT]: {
1231
+ reach: { anyOf: ["channelId"] },
1232
+ guidance: "A person or bot posted a new message in this channel. A bot post runs the automation only when match names the bot in user_id, by its user ID or, for a post with no user, its bot ID. A thread reply runs it only when match.location names thread. A reply goes in the message's Slack thread. If the instructions do not apply to this message, end with no action."
1233
+ } },
1234
+ limits: { [CHANNEL_RESOURCE_TYPE]: {
1235
+ watch: false,
1236
+ watchUnavailableMessage: "Slack channel messages can trigger only an event automation in that channel. Use createAutomation with an event trigger."
1237
+ } }
1201
1238
  };
1202
1239
  }
1203
- /** True when this Source starts an automated Turn rather than a user Turn. */
1204
- function isAutomatedTurnSource(source) {
1205
- if (!source) return false;
1206
- return source.kind === "event" || source.kind === "event_automation" || source.kind === "scheduled_automation" || source.kind === "plugin_dispatch" || source.kind === "agent_invocation";
1207
- }
1208
- /** Plain notice when automatic updates stop until the user replies. */
1209
- function buildAutomatedTurnLimitResponse(args) {
1210
- return `I stopped automatic updates after ${args.maxTurns} replies without a new message from you. Send a message or @mention me in this thread to continue.`;
1211
- }
1212
1240
  /**
1213
- * Allow one automated wake, or refuse once the consecutive-turn limit is full.
1214
- * If a prior pause never posted its notice, claim the notice slot so one caller
1215
- * posts it. Clear the claim if that post fails or is skipped.
1241
+ * Set the `channelId` filter of a Slack channel-message trigger to the
1242
+ * channel where the automation posts. A trigger that names another channel,
1243
+ * or a saved trigger with an identifier, stays as it is for
1244
+ * `requireSlackChannelMessageScope` to check.
1216
1245
  */
1217
- async function admitAutomatedTurn(args) {
1218
- if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
1219
- const state = args.state ?? getStateAdapter();
1220
- await state.connect();
1221
- const nowMs = args.nowMs ?? Date.now();
1222
- const key = conversationKey(args.conversationId);
1223
- return await withConversationLock(state, key, async () => {
1224
- const current = parseState(await state.get(key)) ?? emptyState(nowMs);
1225
- if (current.paused || current.consecutiveAutomatedTurns >= args.maxTurns) {
1226
- const shouldPostNotice = current.noticePostedAtMs === void 0;
1227
- const next = {
1228
- consecutiveAutomatedTurns: Math.max(current.consecutiveAutomatedTurns, args.maxTurns),
1229
- paused: true,
1230
- updatedAtMs: nowMs,
1231
- ...shouldPostNotice ? { noticePostedAtMs: nowMs } : current.noticePostedAtMs !== void 0 ? { noticePostedAtMs: current.noticePostedAtMs } : void 0
1232
- };
1233
- await state.set(key, next, JUNIOR_THREAD_STATE_TTL_MS);
1234
- return {
1235
- status: "paused",
1236
- consecutiveAutomatedTurns: next.consecutiveAutomatedTurns,
1237
- shouldPostNotice
1238
- };
1246
+ function slackChannelMessageTrigger(trigger, channelId) {
1247
+ if (trigger.namespace !== "slack") return trigger;
1248
+ if (trigger.identifier != null || trigger.match?.channelId !== void 0) return trigger;
1249
+ return {
1250
+ ...trigger,
1251
+ match: {
1252
+ ...trigger.match,
1253
+ channelId
1239
1254
  }
1240
- return {
1241
- status: "allow",
1242
- consecutiveAutomatedTurns: current.consecutiveAutomatedTurns
1243
- };
1244
- });
1245
- }
1246
- /** Count one finished automated Turn toward the consecutive-turn limit. */
1247
- async function countAutomatedTurn(args) {
1248
- if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
1249
- const state = args.state ?? getStateAdapter();
1250
- await state.connect();
1251
- const nowMs = args.nowMs ?? Date.now();
1252
- const key = conversationKey(args.conversationId);
1253
- return await withConversationLock(state, key, async () => {
1254
- const current = parseState(await state.get(key)) ?? emptyState(nowMs);
1255
- const consecutiveAutomatedTurns = current.consecutiveAutomatedTurns + 1;
1256
- const paused = consecutiveAutomatedTurns >= args.maxTurns;
1257
- const shouldPostNotice = paused && current.noticePostedAtMs === void 0;
1258
- const next = {
1259
- consecutiveAutomatedTurns,
1260
- paused,
1261
- updatedAtMs: nowMs,
1262
- ...shouldPostNotice ? { noticePostedAtMs: nowMs } : current.noticePostedAtMs !== void 0 ? { noticePostedAtMs: current.noticePostedAtMs } : void 0
1263
- };
1264
- await state.set(key, next, JUNIOR_THREAD_STATE_TTL_MS);
1265
- return {
1266
- consecutiveAutomatedTurns,
1267
- paused,
1268
- shouldPostNotice
1269
- };
1270
- });
1255
+ };
1271
1256
  }
1272
1257
  /**
1273
- * Drop a failed notice claim so a later paused wake can post the notice.
1274
- * Keeps the pause and consecutive count.
1258
+ * Bind a Slack channel-message automation to its own channel.
1259
+ *
1260
+ * The trigger names the channel with a `channelId` filter. A saved trigger
1261
+ * can name it with an identifier instead, where `current_channel` means the
1262
+ * destination channel. Reject other channels, so private channel text cannot
1263
+ * reach another channel.
1275
1264
  */
1276
- async function clearAutomatedTurnLimitNoticeClaim(args) {
1277
- const state = args.state ?? getStateAdapter();
1278
- await state.connect();
1279
- const nowMs = args.nowMs ?? Date.now();
1280
- const key = conversationKey(args.conversationId);
1281
- await withConversationLock(state, key, async () => {
1282
- const current = parseState(await state.get(key));
1283
- if (!current || current.noticePostedAtMs === void 0) return;
1284
- const { noticePostedAtMs: _noticePostedAtMs, ...rest } = current;
1285
- await state.set(key, {
1286
- ...rest,
1287
- updatedAtMs: nowMs
1288
- }, JUNIOR_THREAD_STATE_TTL_MS);
1289
- });
1265
+ function requireSlackChannelMessageScope(automation) {
1266
+ if (automation.trigger.namespace !== "slack") return automation;
1267
+ const channelId = automation.destination.channelId;
1268
+ if (!CHANNEL_ID_PATTERN.test(channelId)) throw new ToolInputError("A Slack channel-message automation works only in a channel, not in a DM.");
1269
+ const { identifier, match } = automation.trigger;
1270
+ if ((identifier === void 0 ? match?.channelId : identifier === "current_channel" ? channelId : identifier) !== channelId) throw new ToolInputError("A Slack channel-message automation can watch only the channel where it posts. Leave out the channel_id filter, or create the automation in the channel to watch.");
1271
+ return {
1272
+ ...automation,
1273
+ credentialMode: "system",
1274
+ trigger: {
1275
+ ...automation.trigger,
1276
+ ...identifier === void 0 ? void 0 : { identifier: channelId }
1277
+ }
1278
+ };
1290
1279
  }
1291
- /** Clear the consecutive automated-turn count after a user-owned Turn. */
1292
- async function resetAutomatedTurnLimit(args) {
1293
- const state = args.state ?? getStateAdapter();
1294
- await state.connect();
1295
- const key = conversationKey(args.conversationId);
1296
- await withConversationLock(state, key, async () => {
1297
- await state.delete(key);
1298
- });
1280
+ /**
1281
+ * Build the Event for one new channel message or thread reply, or nothing.
1282
+ *
1283
+ * Slackbot posts do not count. Bot posts are marked with `postedByBot`, so
1284
+ * only automations that name the bot can run on them. Thread replies carry
1285
+ * the `thread` location, so only automations that name it can run on them.
1286
+ */
1287
+ function slackChannelMessageEvent(input) {
1288
+ const { author } = input;
1289
+ if (author.kind === "user" && author.userId === "USLACKBOT") return void 0;
1290
+ if (!CHANNEL_ID_PATTERN.test(input.channelId)) return void 0;
1291
+ const postedByBot = author.kind === "bot" || Boolean(input.botId || input.subtype === "bot_message");
1292
+ const userId = author.kind === "bot" ? author.botId : author.userId;
1293
+ const threadTs = input.threadTs && input.threadTs !== input.ts ? input.threadTs : void 0;
1294
+ return {
1295
+ eventKey: `${input.channelId}:${input.ts}`,
1296
+ eventType: MESSAGE_POSTED_EVENT,
1297
+ identifier: input.channelId,
1298
+ occurredAtMs: Math.floor(Number(input.ts) * 1e3),
1299
+ trustedSummary: `${postedByBot ? "The bot " : ""}${author.kind === "bot" ? author.botId : `<@${author.userId}>`} posted a new ${threadTs ? `thread reply under message ${threadTs}` : "message"} in <#${input.channelId}>.`,
1300
+ data: {
1301
+ channelId: input.channelId,
1302
+ location: threadTs ? THREAD_LOCATION : CHANNEL_LOCATION,
1303
+ messageTs: input.ts,
1304
+ ...threadTs ? { threadTs } : void 0,
1305
+ userId,
1306
+ ...postedByBot ? { postedByBot: true } : void 0
1307
+ },
1308
+ ...input.text?.trim() ? { untrustedText: input.text } : void 0
1309
+ };
1299
1310
  }
1300
1311
  /**
1301
- * Update consecutive automated-turn counts after one finished Turn.
1312
+ * Decide whether a channel-message Event may run one automation.
1302
1313
  *
1303
- * Automated Turns count on the Conversation. User Turns clear that count so
1304
- * later event wakes can run again.
1314
+ * A message runs only automations that post in its own channel, so private
1315
+ * channel text cannot reach another channel. The trigger already names that
1316
+ * channel, and this check keeps the rule when it does not.
1317
+ * A bot post runs only automations whose match names its author in `userId`.
1318
+ * Bots can post often and would use up the run limit of every other
1319
+ * automation in the channel. A thread reply runs only automations whose
1320
+ * match names the `thread` location, so existing automations stay top-level.
1305
1321
  */
1306
- async function recordFinishedTurnForAutomatedLimit(args) {
1307
- const nowMs = args.nowMs ?? Date.now();
1308
- if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
1309
- conversationId: args.conversationId,
1310
- maxTurns: args.maxTurns,
1311
- nowMs,
1312
- state: args.state
1313
- });
1314
- await resetAutomatedTurnLimit({
1315
- conversationId: args.conversationId,
1316
- nowMs,
1317
- state: args.state
1318
- });
1322
+ function slackChannelMessageRunsAutomation(event, automation) {
1323
+ if (event.namespace !== "slack") return true;
1324
+ if (event.data?.channelId !== automation.destination.channelId) return false;
1325
+ if (event.data?.location === THREAD_LOCATION && ![automation.trigger.match?.location].flat().includes(THREAD_LOCATION)) return false;
1326
+ if (event.data?.postedByBot !== true) return true;
1327
+ return automation.trigger.match?.userId !== void 0;
1319
1328
  }
1320
- // src/chat/slack/automation-card.ts
1321
- function preview(text, length) {
1322
- const compact = text.replace(/\s+/g, " ").trim();
1323
- return compact.length > length ? `${compact.slice(0, length - 1)}…` : compact;
1329
+ /** Return the source message thread for a channel-message run. */
1330
+ function slackChannelMessageReplyThreadTs(event) {
1331
+ if (event.namespace !== "slack") return void 0;
1332
+ const messageTs = event.data?.threadTs ?? event.data?.messageTs;
1333
+ return typeof messageTs === "string" ? messageTs : void 0;
1324
1334
  }
1325
- /** Show an Automation as a native Work Object, not an operation receipt. */
1326
- function renderSlackAutomationCard(card) {
1327
- const title = preview(card.title, 160);
1328
- const iconUrl = getDashboardObjectIconLink("workflow");
1329
- const trigger = preview(card.trigger, 500);
1330
- const warning = card.warning ? preview(card.warning, 500) : null;
1331
- const text = [
1332
- "Automation",
1333
- card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
1334
- escapeSlackMrkdwnText(trigger),
1335
- warning ? escapeSlackMrkdwnText(warning) : null
1336
- ].filter(Boolean).join("\n");
1337
- if (!card.url) return {
1338
- entity: null,
1339
- text
1340
- };
1341
- return {
1342
- text,
1343
- entity: {
1344
- entity_type: "slack#/entities/item",
1345
- external_ref: {
1346
- id: card.id,
1347
- type: "automation"
1335
+ // src/chat/events/runtime-catalog.ts
1336
+ /**
1337
+ * Enabled event registrations for search, guidance, and tool schemas.
1338
+ *
1339
+ * Includes core Workspace snapshot events under the `junior` namespace, Slack
1340
+ * channel-message events under the `slack` namespace, plus every enabled plugin
1341
+ * registration. Plugins may not use the `junior` or `slack` namespaces.
1342
+ */
1343
+ function getEventCatalog() {
1344
+ const snapshot = workspaceSnapshotEvents();
1345
+ const catalog = {
1346
+ [CORE_EVENT_NAMESPACE]: eventCatalogEntry({
1347
+ displayName: botConfig.userName,
1348
+ resourceTypes: [...snapshot.resourceTypes, {
1349
+ type: "timer",
1350
+ supportedEvents: ["timer.fired"],
1351
+ suggestedEvents: []
1352
+ }],
1353
+ events: {
1354
+ ...snapshot.events,
1355
+ "timer.fired": { reach: "resource" }
1348
1356
  },
1349
- url: card.url,
1350
- entity_payload: {
1351
- attributes: {
1352
- title: { text: title },
1353
- display_type: "Automation",
1354
- product_icon: iconUrl ? {
1355
- url: iconUrl,
1356
- alt_text: "Automation"
1357
- } : void 0
1358
- },
1359
- custom_fields: [{
1360
- key: "trigger",
1361
- label: "When",
1362
- type: "string",
1363
- value: trigger,
1364
- long: true
1365
- }, ...warning ? [{
1366
- key: "warning",
1367
- label: "Needs attention",
1368
- type: "string",
1369
- value: warning,
1370
- long: true
1371
- }] : []]
1357
+ limits: {
1358
+ ...snapshot.limits,
1359
+ timer: {
1360
+ automation: false,
1361
+ watch: false,
1362
+ watchUnavailableMessage: "Use watchTimer to create a timer Watch."
1363
+ }
1372
1364
  }
1373
- }
1365
+ }),
1366
+ [SLACK_EVENT_NAMESPACE]: eventCatalogEntry({
1367
+ ...slackChannelMessageEvents(),
1368
+ displayName: "Slack"
1369
+ })
1374
1370
  };
1371
+ for (const plugin of getPlugins()) {
1372
+ const registration = plugin.events;
1373
+ if (!registration || registration.isEnabled?.() === false) continue;
1374
+ if (plugin.manifest.name === "junior" || plugin.manifest.name === "slack") throw new Error(`Plugin "${plugin.manifest.name}" cannot register events; that namespace is reserved for core events`);
1375
+ catalog[plugin.manifest.name] = eventCatalogEntry({
1376
+ ...registration,
1377
+ displayName: plugin.manifest.displayName
1378
+ });
1379
+ }
1380
+ return catalog;
1375
1381
  }
1376
- // src/chat/slack/object-card.ts
1377
- function descriptionPreview(value) {
1378
- const text = value?.replace(/\r\n/g, "\n").trim() ?? "";
1379
- const preview = text.split("\n").slice(0, 6).join("\n").slice(0, 500);
1380
- return preview.length < text.length ? `${preview.slice(0, 499).trimEnd()}…` : preview;
1382
+ // src/chat/experimental.ts
1383
+ /**
1384
+ * Known unstable product features that must be opted into explicitly.
1385
+ * Add new keys here as features graduate from private experiments; remove them
1386
+ * once they become stable defaults.
1387
+ */
1388
+ const EXPERIMENTAL_FEATURES = [
1389
+ "operator-tools",
1390
+ "passive-routing",
1391
+ "user-customization"
1392
+ ];
1393
+ const EXPERIMENTAL_FEATURE_SET = new Set(EXPERIMENTAL_FEATURES);
1394
+ let configuredExperimental = {};
1395
+ function isExperimentalFeature(value) {
1396
+ return EXPERIMENTAL_FEATURE_SET.has(value);
1381
1397
  }
1382
- /** Render a compact Task or Item preview, or the saved facts for its detail panel. */
1383
- function renderSlackObjectCard(card, conversationId, surface = "preview") {
1384
- if (card.objectType === "automation" && card.plugin === "junior") return renderSlackAutomationCard({
1385
- id: card.key,
1386
- title: card.title,
1387
- url: card.url,
1388
- trigger: card.trigger ?? "",
1389
- warning: card.warning ?? null
1390
- });
1391
- const presentation = objectPresentation(card);
1392
- const type = card.displayType ?? presentation.label;
1393
- const iconUrl = getDashboardObjectIconLink(presentation.icon);
1394
- const title = card.title.slice(0, 160);
1395
- const details = surface === "details";
1396
- const deployment = card.objectType === "deployment" || card.objectType === "item" && card.facts?.type === "deployment";
1397
- const calendarEvent = card.objectType === "calendar_event";
1398
- const status = details || deployment || calendarEvent ? card.status : void 0;
1399
- const warning = details || deployment ? card.warning : void 0;
1400
- const facts = objectFactFields(card.facts).filter((field) => details || calendarEvent || deployment && field.key === "environment");
1401
- const description = details ? card.description?.trim() ?? "" : calendarEvent ? "" : descriptionPreview(card.description);
1402
- const text = [
1403
- escapeSlackMrkdwnText(type),
1404
- card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
1405
- escapeSlackMrkdwnText(card.label),
1406
- status ? escapeSlackMrkdwnText(status) : null,
1407
- description ? escapeSlackMrkdwnText(description) : null,
1408
- warning ? escapeSlackMrkdwnText(`Needs attention: ${warning}`) : null,
1409
- ...facts.map((field) => escapeSlackMrkdwnText(`${field.label}: ${field.value}`))
1410
- ].filter(Boolean).join("\n");
1411
- if (!card.url) return {
1412
- entity: null,
1413
- text
1414
- };
1415
- const task = card.objectType === "task";
1416
- const attributes = {
1417
- title: { text: title },
1418
- display_id: card.label,
1419
- display_type: type,
1420
- product_icon: iconUrl ? {
1421
- url: iconUrl,
1422
- alt_text: `${type}${status ? `: ${status}` : ""}`
1423
- } : void 0,
1424
- product_name: card.plugin
1425
- };
1426
- const customFields = [
1427
- ...description ? [{
1428
- key: "description",
1429
- label: "Description",
1430
- type: "string",
1431
- value: description,
1432
- long: true,
1433
- format: "markdown"
1434
- }] : [],
1435
- ...facts.map((field) => ({
1436
- ...field,
1437
- type: "string"
1438
- })),
1439
- ...warning ? [{
1440
- key: "warning",
1441
- label: "Needs attention",
1442
- type: "string",
1443
- value: warning
1444
- }] : []
1445
- ];
1446
- return {
1447
- text,
1448
- entity: {
1449
- ...task ? {
1450
- entity_type: "slack#/entities/task",
1451
- entity_payload: {
1452
- attributes,
1453
- display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
1454
- fields: status ? { status: { value: status } } : void 0,
1455
- custom_fields: customFields
1456
- }
1457
- } : {
1458
- entity_type: "slack#/entities/item",
1459
- entity_payload: {
1460
- attributes,
1461
- display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
1462
- custom_fields: [...status ? [{
1463
- key: "status",
1464
- label: "Status",
1465
- type: "string",
1466
- value: status
1467
- }] : [], ...customFields]
1468
- }
1469
- },
1470
- external_ref: {
1471
- id: Buffer.from(JSON.stringify([
1472
- conversationId,
1473
- card.plugin,
1474
- card.key
1475
- ]), "utf8").toString("base64url"),
1476
- type: "annotation"
1477
- },
1478
- url: card.url
1479
- }
1480
- };
1481
- }
1482
- // src/chat/slack/cards.ts
1483
- /** Select the Slack object renderer for a built-in card. */
1484
- function renderSlackCard(card, conversationId) {
1485
- switch (card.kind) {
1486
- case "object": return renderSlackObjectCard(card, conversationId);
1487
- case "automation": return renderSlackAutomationCard(card);
1398
+ /** Replace app-level experimental opt-ins and return the previous setting. */
1399
+ function setExperimentalFeatures(config) {
1400
+ const previous = { ...configuredExperimental };
1401
+ if (config === void 0) {
1402
+ configuredExperimental = {};
1403
+ return previous;
1404
+ }
1405
+ const next = {};
1406
+ for (const [rawName, enabled] of Object.entries(config)) {
1407
+ if (enabled === void 0) continue;
1408
+ if (typeof enabled !== "boolean") throw new Error(`experimental.${rawName} must be a boolean when provided`);
1409
+ if (!isExperimentalFeature(rawName)) throw new Error(`experimental.${rawName} is not a known experimental feature. Known features: ${EXPERIMENTAL_FEATURES.join(", ")}`);
1410
+ next[rawName] = enabled;
1488
1411
  }
1412
+ configuredExperimental = next;
1413
+ return previous;
1489
1414
  }
1490
- // src/chat/slack/footer.ts
1491
- /** Render compact reply attribution for the Slack footer. */
1492
- function formatReplyAttribution(attribution) {
1493
- return attribution.detail ? `${attribution.label} · ${attribution.detail}` : attribution.label;
1415
+ /** Return a copy of the app-level experimental opt-ins configured by createApp(). */
1416
+ function getExperimentalFeatures() {
1417
+ return { ...configuredExperimental };
1418
+ }
1419
+ /** Return whether one experimental feature is enabled via createApp({ experimental }). */
1420
+ function isExperimentalFeatureEnabled(feature) {
1421
+ return configuredExperimental[feature] === true;
1494
1422
  }
1423
+ // src/chat/conversations/sql/subtree.ts
1424
+ /** Columns of the `conversation_subtree` table that `conversationSubtree` returns. */
1425
+ const conversationSubtreeColumns = {
1426
+ conversationId: sql`conversation_subtree.conversation_id`,
1427
+ scopeConversationId: sql`conversation_subtree.scope_conversation_id`
1428
+ };
1495
1429
  /**
1496
- * Build the compact conversation footer for visible Slack reply surfaces.
1430
+ * Return a joinable `conversation_subtree` table. It maps each selected
1431
+ * Conversation to itself and to each descendant child Conversation at any
1432
+ * depth. Reports use it so that a total for a Conversation always includes the
1433
+ * work of all its child agents.
1497
1434
  *
1498
- * Detailed turn metrics stay in the dashboard instead of Slack-visible copy.
1435
+ * A descendant must have the same root as the selected Conversation. Thus a
1436
+ * Conversation that has no valid root gets only its own work.
1499
1437
  */
1500
- function buildSlackReplyFooter(args) {
1501
- const items = [];
1502
- const conversationId = args.conversationId?.trim();
1503
- if (conversationId) {
1504
- const idItem = {
1505
- label: "ID",
1506
- value: conversationId
1507
- };
1508
- const conversationUrl = getPluginSlackConversationLink(conversationId)?.url ?? getDashboardConversationLink(conversationId) ?? buildSentryConversationUrl(conversationId);
1509
- if (conversationUrl) idItem.url = conversationUrl;
1510
- items.push(idItem);
1511
- }
1512
- return items.length > 0 || args.replyAttribution ? {
1513
- ...args.replyAttribution ? { attribution: args.replyAttribution } : void 0,
1514
- items
1515
- } : void 0;
1438
+ function conversationSubtree(conversationIds) {
1439
+ const selectedIds = sql.join(conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
1440
+ return sql`(
1441
+ with recursive tree(scope_conversation_id, conversation_id, root_conversation_id) as (
1442
+ select selected.conversation_id, selected.conversation_id, selected.root_conversation_id
1443
+ from junior_conversations selected
1444
+ where selected.conversation_id in (${selectedIds})
1445
+ union
1446
+ select tree.scope_conversation_id, child.conversation_id, child.root_conversation_id
1447
+ from junior_conversations child
1448
+ join tree
1449
+ on child.parent_conversation_id = tree.conversation_id
1450
+ and (child.root_conversation_id || '') = tree.root_conversation_id
1451
+ )
1452
+ select scope_conversation_id, conversation_id from tree
1453
+ ) conversation_subtree`;
1516
1454
  }
1517
- /** Build Slack blocks for a reply chunk using the Slack-flavored markdown block for the body. */
1518
- function buildSlackReplyBlocks(text, footer) {
1519
- const blocks = text.trim() ? [{
1520
- type: "markdown",
1521
- text
1522
- }] : [];
1523
- if (footer && (footer.attribution || footer.items.length > 0)) {
1524
- const attributionElements = footer.attribution ? [{
1525
- type: "plain_text",
1526
- text: formatReplyAttribution(footer.attribution)
1527
- }] : [];
1528
- blocks.push({
1529
- type: "context",
1530
- elements: [...attributionElements, ...footer.items.map((item) => ({
1531
- type: "mrkdwn",
1532
- text: item.url ? `*${escapeSlackMrkdwnText(item.label)}:* ${formatSlackLink(item.url, item.value)}` : `*${escapeSlackMrkdwnText(item.label)}:* ${escapeSlackMrkdwnText(item.value)}`
1533
- }))]
1534
- });
1455
+ // src/chat/services/automated-turn-limit.ts
1456
+ const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
1457
+ const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
1458
+ const AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS = 2e3;
1459
+ const AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS = 25;
1460
+ /** Stored consecutive automated-turn count for one Conversation. */
1461
+ const automatedTurnLimitStateSchema = z.object({
1462
+ consecutiveAutomatedTurns: z.number().int().nonnegative(),
1463
+ noticePostedAtMs: z.number().finite().nonnegative().optional(),
1464
+ paused: z.boolean(),
1465
+ updatedAtMs: z.number().finite().nonnegative()
1466
+ }).strict();
1467
+ function sleep(ms) {
1468
+ return new Promise((resolve) => {
1469
+ setTimeout(resolve, ms).unref?.();
1470
+ });
1471
+ }
1472
+ function conversationKey(conversationId) {
1473
+ return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
1474
+ }
1475
+ function lockKey(key) {
1476
+ return `${key}:lock`;
1477
+ }
1478
+ function parseState(value) {
1479
+ const parsed = automatedTurnLimitStateSchema.safeParse(value);
1480
+ return parsed.success ? parsed.data : void 0;
1481
+ }
1482
+ async function acquireConversationLock(state, key, waitDeadlineMs = Date.now() + AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS) {
1483
+ while (true) {
1484
+ const lock = await state.acquireLock(lockKey(key), AUTOMATED_TURN_LIMIT_LOCK_TTL_MS);
1485
+ if (lock) return lock;
1486
+ if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire automated turn limit lock for ${key}`);
1487
+ await sleep(AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS);
1535
1488
  }
1536
- return blocks.length ? blocks : void 0;
1537
1489
  }
1538
- // src/chat/slack/output.ts
1539
- const MAX_INLINE_CHARS = 4e3;
1540
- function getFenceContinuation(text) {
1541
- let open;
1542
- for (const line of text.split("\n")) {
1543
- const trimmed = line.trimStart();
1544
- const openerMatch = trimmed.match(/^(`{3,}|~{3,})(.*)$/);
1545
- if (!openerMatch?.[1]) continue;
1546
- if (!open) {
1547
- open = {
1548
- fence: openerMatch[1],
1549
- openerLine: trimmed
1550
- };
1551
- continue;
1552
- }
1553
- if (new RegExp(`^${open.fence}\\s*$`).test(trimmed)) open = void 0;
1490
+ async function withConversationLock(state, key, callback) {
1491
+ const lock = await acquireConversationLock(state, key);
1492
+ try {
1493
+ return await callback();
1494
+ } finally {
1495
+ await state.releaseLock(lock);
1554
1496
  }
1555
- if (!open) return null;
1497
+ }
1498
+ function emptyState(nowMs) {
1556
1499
  return {
1557
- closeSuffix: text.endsWith("\n") ? open.fence : `\n${open.fence}`,
1558
- reopenPrefix: `${open.openerLine}\n`
1500
+ consecutiveAutomatedTurns: 0,
1501
+ paused: false,
1502
+ updatedAtMs: nowMs
1559
1503
  };
1560
1504
  }
1561
- function findSplitIndex(text, maxChars) {
1562
- const bounded = text.slice(0, maxChars);
1563
- const newlineIndex = bounded.lastIndexOf("\n");
1564
- if (newlineIndex > 0) return newlineIndex;
1565
- const spaceIndex = bounded.lastIndexOf(" ");
1566
- if (spaceIndex > 0) return spaceIndex;
1567
- return maxChars;
1505
+ /** True when this Source starts an automated Turn rather than a user Turn. */
1506
+ function isAutomatedTurnSource(source) {
1507
+ if (!source) return false;
1508
+ return source.kind === "event" || source.kind === "event_automation" || source.kind === "scheduled_automation" || source.kind === "plugin_dispatch" || source.kind === "agent_invocation";
1568
1509
  }
1569
- function takePrefix(text, maxChars) {
1570
- const prefix = text.slice(0, findSplitIndex(text, maxChars)).trimEnd() || text.slice(0, maxChars);
1571
- return {
1572
- prefix,
1573
- rest: text.slice(prefix.length).trimStart()
1574
- };
1510
+ /** Plain notice when automatic updates stop until the user replies. */
1511
+ function buildAutomatedTurnLimitResponse(args) {
1512
+ return `I stopped automatic updates after ${args.maxTurns} replies without a new message from you. Send a message or @mention me in this thread to continue.`;
1575
1513
  }
1576
- /** Take one post that fits the budget, closing a code fence it leaves open. */
1577
- function takeChunk(text) {
1578
- let { prefix, rest } = takePrefix(text, MAX_INLINE_CHARS);
1579
- let carryover = getFenceContinuation(prefix);
1580
- if (!carryover) return {
1581
- chunk: prefix,
1582
- rest
1583
- };
1584
- ({prefix, rest} = takePrefix(text, MAX_INLINE_CHARS - carryover.closeSuffix.length));
1585
- carryover = getFenceContinuation(prefix);
1586
- if (!carryover || !rest) return {
1587
- chunk: prefix,
1588
- rest
1589
- };
1590
- return {
1591
- chunk: `${prefix}${carryover.closeSuffix}`,
1592
- rest: `${carryover.reopenPrefix}${rest}`
1593
- };
1594
- }
1595
- /** Split a normalized Slack reply into thread posts that fit Slack limits. */
1596
- function splitSlackReplyText(text) {
1597
- const chunks = [];
1598
- let remaining = normalizeSlackReplyMarkdown(text);
1599
- while (remaining.length > MAX_INLINE_CHARS) {
1600
- const { chunk, rest } = takeChunk(remaining);
1601
- chunks.push(chunk);
1602
- remaining = rest;
1603
- }
1604
- if (remaining) chunks.push(remaining);
1605
- return chunks;
1606
- }
1607
- // src/chat/slack/reply.ts
1608
1514
  /**
1609
- * Resolve where a Turn posts in Slack.
1610
- *
1611
- * The channel is always the Destination channel. The thread comes from the
1612
- * Turn Source, then the Conversation Location, then the Destination, and each
1613
- * one counts only when it names that channel. Do not derive the target from
1614
- * the Conversation id: an Automation or Watch Conversation can own a Slack
1615
- * thread, and its id is not a Slack thread id.
1515
+ * Allow one automated wake, or refuse once the consecutive-turn limit is full.
1516
+ * If a prior pause never posted its notice, claim the notice slot so one caller
1517
+ * posts it. Clear the claim if that post fails or is skipped.
1616
1518
  */
1617
- function resolveSlackReplyTarget(args) {
1618
- const { channelId } = args.destination;
1619
- const sourceThreadTs = args.source?.kind === "slack" && args.source.channelId === channelId ? args.source.threadTs : void 0;
1620
- const locationThreadTs = args.location?.provider === "slack" && args.location.channelId === channelId ? args.location.threadTs : void 0;
1621
- const threadTs = sourceThreadTs ?? locationThreadTs ?? args.destination.threadTs;
1622
- return {
1623
- channelId,
1624
- ...threadTs ? { threadTs } : void 0
1625
- };
1519
+ async function admitAutomatedTurn(args) {
1520
+ if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
1521
+ const state = args.state ?? getStateAdapter();
1522
+ await state.connect();
1523
+ const nowMs = args.nowMs ?? Date.now();
1524
+ const key = conversationKey(args.conversationId);
1525
+ return await withConversationLock(state, key, async () => {
1526
+ const current = parseState(await state.get(key)) ?? emptyState(nowMs);
1527
+ if (current.paused || current.consecutiveAutomatedTurns >= args.maxTurns) {
1528
+ const shouldPostNotice = current.noticePostedAtMs === void 0;
1529
+ const next = {
1530
+ consecutiveAutomatedTurns: Math.max(current.consecutiveAutomatedTurns, args.maxTurns),
1531
+ paused: true,
1532
+ updatedAtMs: nowMs,
1533
+ ...shouldPostNotice ? { noticePostedAtMs: nowMs } : current.noticePostedAtMs !== void 0 ? { noticePostedAtMs: current.noticePostedAtMs } : void 0
1534
+ };
1535
+ await state.set(key, next, JUNIOR_THREAD_STATE_TTL_MS);
1536
+ return {
1537
+ status: "paused",
1538
+ consecutiveAutomatedTurns: next.consecutiveAutomatedTurns,
1539
+ shouldPostNotice
1540
+ };
1541
+ }
1542
+ return {
1543
+ status: "allow",
1544
+ consecutiveAutomatedTurns: current.consecutiveAutomatedTurns
1545
+ };
1546
+ });
1547
+ }
1548
+ /** Count one finished automated Turn toward the consecutive-turn limit. */
1549
+ async function countAutomatedTurn(args) {
1550
+ if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
1551
+ const state = args.state ?? getStateAdapter();
1552
+ await state.connect();
1553
+ const nowMs = args.nowMs ?? Date.now();
1554
+ const key = conversationKey(args.conversationId);
1555
+ return await withConversationLock(state, key, async () => {
1556
+ const current = parseState(await state.get(key)) ?? emptyState(nowMs);
1557
+ const consecutiveAutomatedTurns = current.consecutiveAutomatedTurns + 1;
1558
+ const paused = consecutiveAutomatedTurns >= args.maxTurns;
1559
+ const shouldPostNotice = paused && current.noticePostedAtMs === void 0;
1560
+ const next = {
1561
+ consecutiveAutomatedTurns,
1562
+ paused,
1563
+ updatedAtMs: nowMs,
1564
+ ...shouldPostNotice ? { noticePostedAtMs: nowMs } : current.noticePostedAtMs !== void 0 ? { noticePostedAtMs: current.noticePostedAtMs } : void 0
1565
+ };
1566
+ await state.set(key, next, JUNIOR_THREAD_STATE_TTL_MS);
1567
+ return {
1568
+ consecutiveAutomatedTurns,
1569
+ paused,
1570
+ shouldPostNotice
1571
+ };
1572
+ });
1626
1573
  }
1627
1574
  /**
1628
- * Send one destination-visible Slack reply.
1629
- *
1630
- * Chunks oversized text, builds compact attribution and conversation footer
1631
- * context, and posts through the shared Slack outbound boundary.
1575
+ * Drop a failed notice claim so a later paused wake can post the notice.
1576
+ * Keeps the pause and consecutive count.
1632
1577
  */
1633
- async function sendSlackReply(args) {
1634
- const posts = splitSlackReplyText(args.text).map((text) => ({
1635
- text,
1636
- cards: []
1637
- }));
1638
- const cards = (args.cards ?? []).map((card) => renderSlackCard(card, args.conversationId));
1639
- for (let index = 0; index < cards.length; index += 5) {
1640
- const group = cards.slice(index, index + 5);
1641
- const lastPost = posts.at(-1);
1642
- if (index === 0 && lastPost) lastPost.cards = group;
1643
- else posts.push({
1644
- text: "",
1645
- cards: group
1646
- });
1647
- }
1648
- const footer = buildSlackReplyFooter({
1649
- conversationId: args.conversationId,
1650
- replyAttribution: args.replyAttribution
1578
+ async function clearAutomatedTurnLimitNoticeClaim(args) {
1579
+ const state = args.state ?? getStateAdapter();
1580
+ await state.connect();
1581
+ const nowMs = args.nowMs ?? Date.now();
1582
+ const key = conversationKey(args.conversationId);
1583
+ await withConversationLock(state, key, async () => {
1584
+ const current = parseState(await state.get(key));
1585
+ if (!current || current.noticePostedAtMs === void 0) return;
1586
+ const { noticePostedAtMs: _noticePostedAtMs, ...rest } = current;
1587
+ await state.set(key, {
1588
+ ...rest,
1589
+ updatedAtMs: nowMs
1590
+ }, JUNIOR_THREAD_STATE_TTL_MS);
1591
+ });
1592
+ }
1593
+ /** Clear the consecutive automated-turn count after a user-owned Turn. */
1594
+ async function resetAutomatedTurnLimit(args) {
1595
+ const state = args.state ?? getStateAdapter();
1596
+ await state.connect();
1597
+ const key = conversationKey(args.conversationId);
1598
+ await withConversationLock(state, key, async () => {
1599
+ await state.delete(key);
1651
1600
  });
1652
- const messageTs = [];
1653
- let threadTs = args.threadTs;
1654
- for (const [index, post] of posts.entries()) {
1655
- const { text, cards } = post;
1656
- const isFinalChunk = index === posts.length - 1;
1657
- const blocks = buildSlackReplyBlocks(text, void 0) ?? [];
1658
- for (const card of cards) if (!card.entity) blocks.push({
1659
- type: "section",
1660
- text: {
1661
- type: "mrkdwn",
1662
- text: card.text
1663
- }
1664
- });
1665
- if (isFinalChunk || !text.trim()) blocks.push(...buildSlackReplyBlocks("", footer) ?? []);
1666
- const entities = cards.flatMap((card) => card.entity ? [card.entity] : []);
1667
- const accessibleText = [text, ...cards.map((card) => card.text)].filter(Boolean).join("\n\n");
1668
- const fallbackText = isFinalChunk && args.replyAttribution ? `${accessibleText}\n\n${escapeSlackMrkdwnText(formatReplyAttribution(args.replyAttribution))}` : accessibleText;
1669
- const response = await postSlackMessage({
1670
- channelId: args.channelId,
1671
- threadTs,
1672
- text: fallbackText,
1673
- ...blocks.length ? { blocks } : void 0,
1674
- ...entities.length ? { entities } : void 0
1675
- });
1676
- if (response.ts) {
1677
- messageTs.push(response.ts);
1678
- threadTs ??= response.ts;
1679
- }
1680
- }
1681
- return messageTs;
1682
1601
  }
1683
- // src/chat/slack/automated-turn-limit-notice.ts
1684
1602
  /**
1685
- * Pause notice for the consecutive automated-turn limit.
1603
+ * Update consecutive automated-turn counts after one finished Turn.
1686
1604
  *
1687
- * Best-effort: a failed post must not fail the Turn or re-enable event wakes.
1688
- * The consecutive-turn limit claims the notice slot before this post. Clear that
1689
- * claim when the post fails or is skipped so a later paused wake can try again.
1605
+ * Automated Turns count on the Conversation. User Turns clear that count so
1606
+ * later event wakes can run again.
1690
1607
  */
1691
- async function releaseFailedNoticeClaim(args) {
1692
- try {
1693
- await clearAutomatedTurnLimitNoticeClaim(args);
1694
- } catch (error) {
1695
- logException(error, "automated_turn_limit.notice_claim_clear_failed");
1696
- }
1697
- }
1698
- /** Post the pause notice for one Conversation Location when known. */
1699
- async function postAutomatedTurnLimitNoticeForConversation(args) {
1700
- try {
1701
- const conversation = await getConversationStore().get({ conversationId: args.conversationId });
1702
- const location = conversation?.parentConversationId ? void 0 : conversation?.location;
1703
- if (!location || location.provider !== "slack") {
1704
- logWarn("automated_turn_limit.notice_skipped", {
1705
- conversationId: args.conversationId,
1706
- "app.automated_turn_limit.reason": location ? "unsupported_location" : "missing_location"
1707
- });
1708
- await releaseFailedNoticeClaim({
1709
- conversationId: args.conversationId,
1710
- nowMs: args.nowMs
1711
- });
1712
- return false;
1713
- }
1714
- await sendSlackReply({
1715
- ...resolveSlackReplyTarget({
1716
- destination: location,
1717
- location,
1718
- source: args.source
1719
- }),
1720
- conversationId: args.conversationId,
1721
- text: buildAutomatedTurnLimitResponse({ maxTurns: args.maxTurns })
1722
- });
1723
- return true;
1724
- } catch (error) {
1725
- logException(error, "automated_turn_limit.notice_failed", { conversationId: args.conversationId });
1726
- await releaseFailedNoticeClaim({
1727
- conversationId: args.conversationId,
1728
- nowMs: args.nowMs
1729
- });
1730
- return false;
1731
- }
1732
- }
1733
- /** Post the pause notice after a finished Turn hits the limit. */
1734
- async function maybePostAutomatedTurnLimitNotice(args) {
1735
- if (!args.update?.shouldPostNotice) return;
1736
- await postAutomatedTurnLimitNoticeForConversation({
1608
+ async function recordFinishedTurnForAutomatedLimit(args) {
1609
+ const nowMs = args.nowMs ?? Date.now();
1610
+ if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
1737
1611
  conversationId: args.conversationId,
1738
1612
  maxTurns: args.maxTurns,
1739
- nowMs: args.nowMs,
1740
- source: args.source
1613
+ nowMs,
1614
+ state: args.state
1615
+ });
1616
+ await resetAutomatedTurnLimit({
1617
+ conversationId: args.conversationId,
1618
+ nowMs,
1619
+ state: args.state
1741
1620
  });
1742
1621
  }
1743
- // src/chat/task-input.ts
1744
- /**
1745
- * Shared agent input for tasks: one `<task>` input tag. A task can come from
1746
- * a schedule, an event, or a watch. Call sites supply facts; this module owns
1747
- * layout and the reply contract. Unit snapshots in
1748
- * `tests/unit/chat/task-input.test.ts` own the exact text. Event data stays in
1749
- * its own child tags, and the outcome rule is always last.
1750
- */
1751
- /**
1752
- * Shared closing lines. Automations pass outcomes and end with an answer
1753
- * tool. Watches follow the Conversation's reply rules. A Watch reply goes
1754
- * only to the Conversation, so a question asked in the provider must also get
1755
- * its answer there. Watch instructions often say to stay silent, so this rule
1756
- * sits in the contract, not in plugin guidance.
1757
- */
1758
- function replyContractLines(outcomes) {
1759
- if (!outcomes) return [
1760
- "When an Event asks you a question, answer it where it was asked, with that provider's tool. Then reply with the answer and a link to it.",
1761
- "When you reply, follow any reply format in the instructions.",
1762
- `When the outcome needs nobody's attention, such as a routine fix that worked or feedback that you handled, end the Turn with \`${NO_REPLY_TOOL_NAME}\` and put the outcome in its \`note\`. The note stays in the Conversation but notifies nobody. Do not use it when the instructions say to notify, mention, or report to a person, when the reply asks a question, when a person must decide or act, or when something failed.`
1763
- ];
1764
- return [`End with \`${REPLY_TOOL_NAME}\`, \`${NO_REPLY_TOOL_NAME}\`, or \`${REPORT_BLOCKED_TOOL_NAME}\`.`];
1765
- }
1766
- function oneLine(value) {
1767
- return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
1768
- }
1769
- function clip(value, maxLength) {
1770
- return maxLength === void 0 ? value : value.slice(0, maxLength);
1622
+ // src/chat/slack/automation-card.ts
1623
+ function preview(text, length) {
1624
+ const compact = text.replace(/\s+/g, " ").trim();
1625
+ return compact.length > length ? `${compact.slice(0, length - 1)}…` : compact;
1771
1626
  }
1772
- const CREATOR_REFERENCE = /\bthe Automation creator\b/gi;
1773
- /**
1774
- * Write the creator mention where the instructions say "the Automation
1775
- * creator", so the run does not have to swap it in.
1776
- */
1777
- function mentionCreator(instructions, creator) {
1778
- return instructions.replace(CREATOR_REFERENCE, () => creator);
1627
+ /** Show an Automation as a native Work Object, not an operation receipt. */
1628
+ function renderSlackAutomationCard(card) {
1629
+ const title = preview(card.title, 160);
1630
+ const iconUrl = getDashboardObjectIconLink("workflow");
1631
+ const trigger = preview(card.trigger, 500);
1632
+ const warning = card.warning ? preview(card.warning, 500) : null;
1633
+ const text = [
1634
+ "Automation",
1635
+ card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
1636
+ escapeSlackMrkdwnText(trigger),
1637
+ warning ? escapeSlackMrkdwnText(warning) : null
1638
+ ].filter(Boolean).join("\n");
1639
+ if (!card.url) return {
1640
+ entity: null,
1641
+ text
1642
+ };
1643
+ return {
1644
+ text,
1645
+ entity: {
1646
+ entity_type: "slack#/entities/item",
1647
+ external_ref: {
1648
+ id: card.id,
1649
+ type: "automation"
1650
+ },
1651
+ url: card.url,
1652
+ entity_payload: {
1653
+ attributes: {
1654
+ title: { text: title },
1655
+ display_type: "Automation",
1656
+ product_icon: iconUrl ? {
1657
+ url: iconUrl,
1658
+ alt_text: "Automation"
1659
+ } : void 0
1660
+ },
1661
+ custom_fields: [{
1662
+ key: "trigger",
1663
+ label: "When",
1664
+ type: "string",
1665
+ value: trigger,
1666
+ long: true
1667
+ }, ...warning ? [{
1668
+ key: "warning",
1669
+ label: "Needs attention",
1670
+ type: "string",
1671
+ value: warning,
1672
+ long: true
1673
+ }] : []]
1674
+ }
1675
+ }
1676
+ };
1779
1677
  }
1780
- function quoted(values) {
1781
- return values.map((value) => `"${value}"`).join(" or ");
1678
+ // src/chat/slack/object-card.ts
1679
+ function descriptionPreview(value) {
1680
+ const text = value?.replace(/\r\n/g, "\n").trim() ?? "";
1681
+ const preview = text.split("\n").slice(0, 6).join("\n").slice(0, 500);
1682
+ return preview.length < text.length ? `${preview.slice(0, 499).trimEnd()}…` : preview;
1782
1683
  }
1783
- /**
1784
- * Render each linked person once. A doer in `<people>` gets a note in that
1785
- * list. Other doers get a `<done-by>` tag. Without one entry per person, the
1786
- * agent can mention a person and then name them again by handle as if they
1787
- * were someone else. The "you" rule covers doers outside `<people>` too,
1788
- * because instructions can still ask to mention them, such as a requester who
1789
- * reviews their own pull request. A child agent replies to its parent, not to
1790
- * the person, so it writes the mention instead of the handle. That carries
1791
- * who the person is up each level to the agent that replies to them.
1792
- */
1793
- function peopleTags(people, doers) {
1794
- const label = (doer) => `${doer.mention} (${[doer.did, ...doer.handles.length > 0 ? [`called ${quoted(doer.handles)} in the Event data`] : []].join("; ")})`;
1795
- const doerByMention = new Map(doers.map((doer) => [doer.mention, doer]));
1796
- const involved = people.map((person) => {
1797
- const doer = doerByMention.get(person);
1798
- return doer ? label(doer) : person;
1684
+ /** Render a compact Task or Item preview, or the saved facts for its detail panel. */
1685
+ function renderSlackObjectCard(card, conversationId, surface = "preview") {
1686
+ if (card.objectType === "automation" && card.plugin === "junior") return renderSlackAutomationCard({
1687
+ id: card.key,
1688
+ title: card.title,
1689
+ url: card.url,
1690
+ trigger: card.trigger ?? "",
1691
+ warning: card.warning ?? null
1799
1692
  });
1800
- return [
1801
- ...involved.length > 0 ? [renderChildTag("people", escapeClosingTags(involved.join(", ")))] : [],
1802
- ...doers.filter((doer) => !people.includes(doer.mention)).map((doer) => renderChildTag("done-by", escapeClosingTags(label(doer)))),
1803
- ...doers.map((doer) => escapeClosingTags(`If your reply is to ${doer.mention}, write to them as "you".${doer.handles.length > 0 ? ` Otherwise call them ${doer.mention}, not ${quoted(doer.handles)}.` : ""}`))
1693
+ const presentation = objectPresentation(card);
1694
+ const type = card.displayType ?? presentation.label;
1695
+ const iconUrl = getDashboardObjectIconLink(presentation.icon);
1696
+ const title = card.title.slice(0, 160);
1697
+ const details = surface === "details";
1698
+ const deployment = card.objectType === "deployment" || card.objectType === "item" && card.facts?.type === "deployment";
1699
+ const calendarEvent = card.objectType === "calendar_event";
1700
+ const status = details || deployment || calendarEvent ? card.status : void 0;
1701
+ const warning = details || deployment ? card.warning : void 0;
1702
+ const facts = objectFactFields(card.facts).filter((field) => details || calendarEvent || deployment && field.key === "environment");
1703
+ const description = details ? card.description?.trim() ?? "" : calendarEvent ? "" : descriptionPreview(card.description);
1704
+ const text = [
1705
+ escapeSlackMrkdwnText(type),
1706
+ card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
1707
+ escapeSlackMrkdwnText(card.label),
1708
+ status ? escapeSlackMrkdwnText(status) : null,
1709
+ description ? escapeSlackMrkdwnText(description) : null,
1710
+ warning ? escapeSlackMrkdwnText(`Needs attention: ${warning}`) : null,
1711
+ ...facts.map((field) => escapeSlackMrkdwnText(`${field.label}: ${field.value}`))
1712
+ ].filter(Boolean).join("\n");
1713
+ if (!card.url) return {
1714
+ entity: null,
1715
+ text
1716
+ };
1717
+ const task = card.objectType === "task";
1718
+ const attributes = {
1719
+ title: { text: title },
1720
+ display_id: card.label,
1721
+ display_type: type,
1722
+ product_icon: iconUrl ? {
1723
+ url: iconUrl,
1724
+ alt_text: `${type}${status ? `: ${status}` : ""}`
1725
+ } : void 0,
1726
+ product_name: card.plugin
1727
+ };
1728
+ const customFields = [
1729
+ ...description ? [{
1730
+ key: "description",
1731
+ label: "Description",
1732
+ type: "string",
1733
+ value: description,
1734
+ long: true,
1735
+ format: "markdown"
1736
+ }] : [],
1737
+ ...facts.map((field) => ({
1738
+ ...field,
1739
+ type: "string"
1740
+ })),
1741
+ ...warning ? [{
1742
+ key: "warning",
1743
+ label: "Needs attention",
1744
+ type: "string",
1745
+ value: warning
1746
+ }] : []
1804
1747
  ];
1748
+ return {
1749
+ text,
1750
+ entity: {
1751
+ ...task ? {
1752
+ entity_type: "slack#/entities/task",
1753
+ entity_payload: {
1754
+ attributes,
1755
+ display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
1756
+ fields: status ? { status: { value: status } } : void 0,
1757
+ custom_fields: customFields
1758
+ }
1759
+ } : {
1760
+ entity_type: "slack#/entities/item",
1761
+ entity_payload: {
1762
+ attributes,
1763
+ display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
1764
+ custom_fields: [...status ? [{
1765
+ key: "status",
1766
+ label: "Status",
1767
+ type: "string",
1768
+ value: status
1769
+ }] : [], ...customFields]
1770
+ }
1771
+ },
1772
+ external_ref: {
1773
+ id: Buffer.from(JSON.stringify([
1774
+ conversationId,
1775
+ card.plugin,
1776
+ card.key
1777
+ ]), "utf8").toString("base64url"),
1778
+ type: "annotation"
1779
+ },
1780
+ url: card.url
1781
+ }
1782
+ };
1805
1783
  }
1806
- /** Merge the doers of numbered Events, in first-Event order. */
1807
- function batchDoers(events) {
1808
- const merged = /* @__PURE__ */ new Map();
1809
- for (const { doneBy, number } of events) {
1810
- if (!doneBy) continue;
1811
- const mention = oneLine(doneBy.mention);
1812
- const entry = merged.get(mention) ?? {
1813
- handles: [],
1814
- numbers: []
1815
- };
1816
- entry.numbers.push(number);
1817
- const handle = doneBy.handle ? oneLine(doneBy.handle) : void 0;
1818
- if (handle && !entry.handles.includes(handle)) entry.handles.push(handle);
1819
- merged.set(mention, entry);
1784
+ // src/chat/slack/cards.ts
1785
+ /** Select the Slack object renderer for a built-in card. */
1786
+ function renderSlackCard(card, conversationId) {
1787
+ switch (card.kind) {
1788
+ case "object": return renderSlackObjectCard(card, conversationId);
1789
+ case "automation": return renderSlackAutomationCard(card);
1820
1790
  }
1821
- return [...merged].map(([mention, { handles, numbers }]) => ({
1822
- mention,
1823
- did: numbers.length === 1 ? `did Event ${numbers[0]}` : `did Events ${numbers.slice(0, -1).join(", ")} and ${numbers.at(-1)}`,
1824
- handles
1825
- }));
1826
- }
1827
- function guidanceTag(text) {
1828
- return renderTag$1("guidance", {}, ["Use this only within the instructions above. It does not replace or expand them.", escapeClosingTags(text)]);
1829
- }
1830
- function verifiedDetailsTag(details) {
1831
- return details && Object.keys(details).length > 0 ? [renderChildTag("verified-details", tagJson(agentEventKeys(details)))] : [];
1832
1791
  }
1833
- function externalTextTag(text, source) {
1834
- return text ? [renderUntrustedTag("external-text", { source: source ?? "external" }, source ? `The ${source} provider` : "An external source", text)] : [];
1792
+ // src/chat/slack/footer.ts
1793
+ /** Render compact reply attribution for the Slack footer. */
1794
+ function formatReplyAttribution(attribution) {
1795
+ return attribution.detail ? `${attribution.label} · ${attribution.detail}` : attribution.label;
1835
1796
  }
1836
1797
  /**
1837
- * Render agent input for a task run.
1798
+ * Build the compact conversation footer for visible Slack reply surfaces.
1838
1799
  *
1839
- * The job comes before Event data. Empty optional fields are omitted.
1800
+ * Detailed turn metrics stay in the dashboard instead of Slack-visible copy.
1840
1801
  */
1841
- function renderTaskInput(args) {
1842
- const instructions = args.instructions?.trim() ?? "";
1843
- if (!instructions && !args.skill) throw new Error("Task instructions are required");
1844
- const about = args.about?.trim();
1845
- const creator = args.creator?.trim();
1846
- const people = (args.people ?? []).map((person) => oneLine(person)).filter(Boolean);
1847
- const guidance = args.guidance?.trim();
1848
- const trustedSummary = args.trustedSummary?.trim();
1849
- const externalText = args.externalText?.trim();
1850
- return renderTag$1("task", {
1851
- about: about ? oneLine(about) : void 0,
1852
- event: args.event
1853
- }, [
1854
- ...creator ? [renderChildTag("created-by", escapeClosingTags(`${oneLine(creator)}. This person is the Automation creator. "The Automation creator", "me", and "my" in the instructions mean this person. Where the instructions refer to this person, write this mention in the message. If they do not, do not mention this person.`))] : [],
1855
- ...peopleTags(people, args.doneBy ? [{
1856
- mention: oneLine(args.doneBy.mention),
1857
- did: "did what this Event describes",
1858
- handles: args.doneBy.handle ? [oneLine(args.doneBy.handle)] : []
1859
- }] : []),
1860
- ...args.skill ? [instructions ? `Run the ${args.skill} skill. The instructions below add context for this run.` : `Run the ${args.skill} skill.`] : [],
1861
- ...instructions ? [renderChildTag("instructions", escapeClosingTags(creator ? mentionCreator(instructions, oneLine(creator)) : instructions))] : [],
1862
- ...guidance ? [guidanceTag(guidance)] : [],
1863
- ...trustedSummary ? [renderChildTag("summary", escapeClosingTags(clip(trustedSummary, args.trustedSummaryMaxLength)))] : [],
1864
- ...verifiedDetailsTag(args.verifiedDetails),
1865
- ...externalTextTag(externalText && clip(externalText, args.externalTextMaxLength), args.source),
1866
- ...replyContractLines(args.outcomes)
1867
- ]);
1802
+ function buildSlackReplyFooter(args) {
1803
+ const items = [];
1804
+ const conversationId = args.conversationId?.trim();
1805
+ if (conversationId) {
1806
+ const idItem = {
1807
+ label: "ID",
1808
+ value: conversationId
1809
+ };
1810
+ const conversationUrl = getPluginSlackConversationLink(conversationId)?.url ?? getDashboardConversationLink(conversationId) ?? buildSentryConversationUrl(conversationId);
1811
+ if (conversationUrl) idItem.url = conversationUrl;
1812
+ items.push(idItem);
1813
+ }
1814
+ return items.length > 0 || args.replyAttribution ? {
1815
+ ...args.replyAttribution ? { attribution: args.replyAttribution } : void 0,
1816
+ items
1817
+ } : void 0;
1868
1818
  }
1869
- function eventTag(event, index) {
1870
- const trustedSummary = event.trustedSummary?.trim();
1871
- return renderTag$1("event", {
1872
- index,
1873
- type: event.eventType
1874
- }, [
1875
- ...trustedSummary ? [renderChildTag("summary", escapeClosingTags(trustedSummary))] : [],
1876
- ...verifiedDetailsTag(event.verifiedDetails),
1877
- ...externalTextTag(event.externalText?.trim(), event.source)
1878
- ]);
1819
+ /** Build Slack blocks for a reply chunk using the Slack-flavored markdown block for the body. */
1820
+ function buildSlackReplyBlocks(text, footer) {
1821
+ const blocks = text.trim() ? [{
1822
+ type: "markdown",
1823
+ text
1824
+ }] : [];
1825
+ if (footer && (footer.attribution || footer.items.length > 0)) {
1826
+ const attributionElements = footer.attribution ? [{
1827
+ type: "plain_text",
1828
+ text: formatReplyAttribution(footer.attribution)
1829
+ }] : [];
1830
+ blocks.push({
1831
+ type: "context",
1832
+ elements: [...attributionElements, ...footer.items.map((item) => ({
1833
+ type: "mrkdwn",
1834
+ text: item.url ? `*${escapeSlackMrkdwnText(item.label)}:* ${formatSlackLink(item.url, item.value)}` : `*${escapeSlackMrkdwnText(item.label)}:* ${escapeSlackMrkdwnText(item.value)}`
1835
+ }))]
1836
+ });
1837
+ }
1838
+ return blocks.length ? blocks : void 0;
1879
1839
  }
1880
- /**
1881
- * Render one `<task>` for several Watch Events that arrived together.
1882
- *
1883
- * Each `<watch>` group states its instructions once, then lists its Events.
1884
- * Child tags match `renderTaskInput`. The outcome rule appears once, at the
1885
- * end.
1886
- */
1887
- function renderTaskBatchInput(args) {
1888
- const total = args.groups.reduce((count, group) => count + group.events.length, 0);
1889
- if (total === 0) throw new Error("Task batch requires at least one Event");
1890
- const body = [`You received ${total} ${total === 1 ? "event" : "events"}.`];
1891
- let number = 0;
1892
- for (const group of args.groups) {
1893
- const instructions = group.instructions.trim();
1894
- if (!instructions) throw new Error("Task instructions are required");
1895
- const about = group.about?.trim();
1896
- const people = group.people.map((person) => oneLine(person)).filter(Boolean);
1897
- const numbered = group.events.map((event, index) => ({
1898
- ...event,
1899
- number: number + index + 1
1900
- }));
1901
- number += group.events.length;
1902
- const guidance = /* @__PURE__ */ new Map();
1903
- for (const event of group.events) {
1904
- const text = event.guidance?.trim();
1905
- if (text && !guidance.has(event.eventType)) guidance.set(event.eventType, text);
1906
- }
1907
- body.push(renderTag$1("watch", { about: about ? oneLine(about) : void 0 }, [
1908
- ...peopleTags(people, batchDoers(numbered)),
1909
- renderChildTag("instructions", escapeClosingTags(instructions)),
1910
- ...guidance.size > 0 ? [guidanceTag([...guidance].map(([eventType, text]) => `- ${eventType}: ${text}`).join("\n"))] : [],
1911
- ...numbered.map((event) => eventTag(event, event.number))
1912
- ]));
1840
+ // src/chat/events/people.ts
1841
+ const linkedSlackIdentity = alias(juniorIdentities, "event_people_slack");
1842
+ function personKey(person) {
1843
+ return "email" in person ? `email:${normalizeIdentityEmail(person.email)}` : `${person.provider}:${person.handle.toLowerCase()}`;
1844
+ }
1845
+ function personCondition(person) {
1846
+ if ("email" in person) return and(eq(juniorIdentities.emailVerified, true), eq(juniorIdentities.emailNormalized, normalizeIdentityEmail(person.email)));
1847
+ return and(eq(juniorIdentities.provider, person.provider), sql`lower(${juniorIdentities.handle}) = lower(${person.handle})`);
1848
+ }
1849
+ /**
1850
+ * Read the Slack users in one workspace whose linked User has an identity that
1851
+ * matches `condition`, by person key. A key with more than one Slack user is
1852
+ * ambiguous, so callers must not mention it.
1853
+ */
1854
+ async function readLinkedSlackUsers(condition, slackTeamId) {
1855
+ const rows = await getSqlExecutor().db().select({
1856
+ emailNormalized: juniorIdentities.emailNormalized,
1857
+ emailVerified: juniorIdentities.emailVerified,
1858
+ handle: juniorIdentities.handle,
1859
+ provider: juniorIdentities.provider,
1860
+ slackUserId: linkedSlackIdentity.providerSubjectId
1861
+ }).from(juniorIdentities).innerJoin(linkedSlackIdentity, and(eq(linkedSlackIdentity.userId, juniorIdentities.userId), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, slackTeamId))).where(and(eq(juniorIdentities.kind, "user"), condition));
1862
+ const slackUsersByKey = /* @__PURE__ */ new Map();
1863
+ const add = (key, slackUserId) => {
1864
+ const users = slackUsersByKey.get(key) ?? /* @__PURE__ */ new Set();
1865
+ users.add(slackUserId);
1866
+ slackUsersByKey.set(key, users);
1867
+ };
1868
+ for (const row of rows) {
1869
+ if (row.handle) add(`${row.provider}:${row.handle.toLowerCase()}`, row.slackUserId);
1870
+ if (row.emailVerified && row.emailNormalized) add(`email:${row.emailNormalized}`, row.slackUserId);
1913
1871
  }
1914
- return renderTag$1("task", {}, [...body, ...replyContractLines(void 0)]);
1872
+ return slackUsersByKey;
1873
+ }
1874
+ function soleMention(users) {
1875
+ return users?.size === 1 ? slackMention([...users][0]) : void 0;
1876
+ }
1877
+ const HANDLE_MENTION_PATTERN = /(?<![\w.@/-])@([A-Za-z0-9][A-Za-z0-9_.-]*[A-Za-z0-9]|[A-Za-z0-9])/g;
1878
+ const MAX_REPLY_HANDLES = 50;
1879
+ /**
1880
+ * Resolve the `@handle` words in reply text to Slack mentions of known people
1881
+ * in one Slack workspace, by `provider:handle` key in lowercase. A handle
1882
+ * resolves only when exactly one linked Slack user has it for that provider.
1883
+ * Plugins pick the provider when they format the reply.
1884
+ */
1885
+ async function resolveHandleMentions(text, slackTeamId) {
1886
+ const handles = [...new Set([...text.matchAll(HANDLE_MENTION_PATTERN)].map((match) => match[1].toLowerCase()))].slice(0, MAX_REPLY_HANDLES);
1887
+ if (handles.length === 0) return /* @__PURE__ */ new Map();
1888
+ const slackUsersByKey = await readLinkedSlackUsers(inArray(sql`lower(${juniorIdentities.handle})`, handles), slackTeamId);
1889
+ const mentions = /* @__PURE__ */ new Map();
1890
+ for (const [key, users] of slackUsersByKey) {
1891
+ const mention = soleMention(users);
1892
+ if (mention && !key.startsWith("email:")) mentions.set(key, mention);
1893
+ }
1894
+ return mentions;
1915
1895
  }
1916
- // src/chat/sandbox/snapshot/events.ts
1917
- const WORKSPACE_SNAPSHOT_NAMESPACE = CORE_EVENT_NAMESPACE;
1918
- const WORKSPACE_SNAPSHOT_RESOURCE_TYPE = "workspace_snapshot";
1919
- const WORKSPACE_SNAPSHOT_READY_EVENT = "workspace_snapshot.ready";
1920
- const WORKSPACE_SNAPSHOT_FAILED_EVENT = "workspace_snapshot.failed";
1921
1896
  /**
1922
- * Core catalog entry for Workspace snapshot ready and failed events.
1897
+ * Resolve the Event people and the Event doer to Slack mentions through
1898
+ * linked user identities in one Slack workspace, with one query.
1923
1899
  *
1924
- * Uses the same registration shape as plugins so search, guidance, and tool
1925
- * schemas treat these events like any other resource type. Snapshot finish
1926
- * does not run event-automation ingest, so only watches can use these events.
1927
- */
1928
- function workspaceSnapshotEvents() {
1900
+ * A person resolves only when exactly one linked Slack user in that workspace
1901
+ * matches. Core drops unlinked and ambiguous people, so a provider value never
1902
+ * guesses a mention.
1903
+ */
1904
+ async function resolveEventMentions(event, slackTeamId) {
1905
+ const people = event.people ?? [];
1906
+ const lookup = event.doneBy ? [...people, event.doneBy] : people;
1907
+ if (lookup.length === 0) return { people: [] };
1908
+ const slackUsersByKey = await readLinkedSlackUsers(or(...lookup.map(personCondition)), slackTeamId);
1909
+ const mentionOf = (person) => soleMention(slackUsersByKey.get(personKey(person)));
1910
+ const mentions = [];
1911
+ for (const person of people) {
1912
+ const mention = mentionOf(person);
1913
+ if (mention && !mentions.includes(mention)) mentions.push(mention);
1914
+ }
1915
+ const doneByMention = event.doneBy ? mentionOf(event.doneBy) : void 0;
1916
+ if (!doneByMention || !event.doneBy) return { people: mentions };
1929
1917
  return {
1930
- resourceTypes: [{
1931
- type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE,
1932
- supportedEvents: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
1933
- suggestedEvents: []
1934
- }],
1935
- events: {
1936
- [WORKSPACE_SNAPSHOT_READY_EVENT]: {
1937
- reach: "resource",
1938
- guidance: "Call switchWorkspace again with the same Workspace name. Do not create another watch when switchWorkspace already returned a subscription."
1939
- },
1940
- [WORKSPACE_SNAPSHOT_FAILED_EVENT]: {
1941
- reach: "resource",
1942
- guidance: "Report the snapshot failure. Do not keep waiting for this Workspace unless the user asks to retry."
1943
- }
1944
- },
1945
- limits: { [WORKSPACE_SNAPSHOT_RESOURCE_TYPE]: { automation: false } }
1918
+ people: mentions,
1919
+ doneBy: {
1920
+ mention: doneByMention,
1921
+ ..."handle" in event.doneBy ? { handle: event.doneBy.handle } : void 0
1922
+ }
1946
1923
  };
1947
1924
  }
1948
- /** Describe the events that report when a snapshot build ends. */
1949
- function workspaceSnapshotWatch(input) {
1925
+ // src/chat/slack/output.ts
1926
+ const MAX_INLINE_CHARS = 4e3;
1927
+ function getFenceContinuation(text) {
1928
+ let open;
1929
+ for (const line of text.split("\n")) {
1930
+ const trimmed = line.trimStart();
1931
+ const openerMatch = trimmed.match(/^(`{3,}|~{3,})(.*)$/);
1932
+ if (!openerMatch?.[1]) continue;
1933
+ if (!open) {
1934
+ open = {
1935
+ fence: openerMatch[1],
1936
+ openerLine: trimmed
1937
+ };
1938
+ continue;
1939
+ }
1940
+ if (new RegExp(`^${open.fence}\\s*$`).test(trimmed)) open = void 0;
1941
+ }
1942
+ if (!open) return null;
1950
1943
  return {
1951
- identifier: input.workspaceId,
1952
- label: `Workspace ${input.workspaceName} snapshot`,
1953
- namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
1954
- supported_events: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
1955
- suggested_events: [],
1956
- type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE
1944
+ closeSuffix: text.endsWith("\n") ? open.fence : `\n${open.fence}`,
1945
+ reopenPrefix: `${open.openerLine}\n`
1957
1946
  };
1958
1947
  }
1959
- /** Report that a Workspace snapshot build is ready or failed. */
1960
- function workspaceSnapshotFinishedEvent(input) {
1961
- const occurredAtMs = input.occurredAtMs ?? Date.now();
1962
- const eventType = input.status === "ready" ? WORKSPACE_SNAPSHOT_READY_EVENT : WORKSPACE_SNAPSHOT_FAILED_EVENT;
1963
- const trustedSummary = input.status === "ready" ? "Workspace snapshot is ready." : "Workspace snapshot build failed.";
1964
- const event = {
1965
- eventKey: `${WORKSPACE_SNAPSHOT_NAMESPACE}:${input.workspaceId}:${input.resultId}:${input.status}`,
1966
- eventType,
1967
- identifier: input.workspaceId,
1968
- namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
1969
- occurredAtMs,
1970
- terminal: true,
1971
- trustedSummary,
1972
- data: {
1973
- workspaceId: input.workspaceId,
1974
- status: input.status
1975
- }
1948
+ function findSplitIndex(text, maxChars) {
1949
+ const bounded = text.slice(0, maxChars);
1950
+ const newlineIndex = bounded.lastIndexOf("\n");
1951
+ if (newlineIndex > 0) return newlineIndex;
1952
+ const spaceIndex = bounded.lastIndexOf(" ");
1953
+ if (spaceIndex > 0) return spaceIndex;
1954
+ return maxChars;
1955
+ }
1956
+ function takePrefix(text, maxChars) {
1957
+ const prefix = text.slice(0, findSplitIndex(text, maxChars)).trimEnd() || text.slice(0, maxChars);
1958
+ return {
1959
+ prefix,
1960
+ rest: text.slice(prefix.length).trimStart()
1961
+ };
1962
+ }
1963
+ /** Take one post that fits the budget, closing a code fence it leaves open. */
1964
+ function takeChunk(text) {
1965
+ let { prefix, rest } = takePrefix(text, MAX_INLINE_CHARS);
1966
+ let carryover = getFenceContinuation(prefix);
1967
+ if (!carryover) return {
1968
+ chunk: prefix,
1969
+ rest
1970
+ };
1971
+ ({prefix, rest} = takePrefix(text, MAX_INLINE_CHARS - carryover.closeSuffix.length));
1972
+ carryover = getFenceContinuation(prefix);
1973
+ if (!carryover || !rest) return {
1974
+ chunk: prefix,
1975
+ rest
1976
+ };
1977
+ return {
1978
+ chunk: `${prefix}${carryover.closeSuffix}`,
1979
+ rest: `${carryover.reopenPrefix}${rest}`
1976
1980
  };
1977
- if (input.status === "failed" && input.error) event.untrustedText = input.error;
1978
- return event;
1979
1981
  }
1980
- // src/chat/slack/channel-message-events.ts
1981
- /**
1982
- * Slack channel-message Events for Event automations.
1983
- *
1984
- * Core publishes these Events from Slack ingress, so the `slack` namespace is
1985
- * core owned, like `junior`. Anyone in the channel writes the Event text, so an
1986
- * automation can watch only its own channel and always uses system credentials.
1987
- */
1988
- /** Core-owned event namespace for Slack Events. Not a plugin publisher. */
1989
- const SLACK_EVENT_NAMESPACE = "slack";
1990
- /** The trigger identifier that names the channel of the automation. */
1991
- const SLACK_CURRENT_CHANNEL_IDENTIFIER = "current_channel";
1992
- const CHANNEL_RESOURCE_TYPE = "channel";
1993
- const MESSAGE_POSTED_EVENT = "message.posted";
1994
- const CHANNEL_ID_PATTERN = /^[CG][A-Z0-9]{2,}$/;
1995
- const CHANNEL_LOCATION = "channel";
1996
- const THREAD_LOCATION = "thread";
1997
- const CHANNEL_MESSAGE_MATCH_FIELDS = eventMatchFieldsSchema.parse({
1998
- channelId: {
1999
- kind: "string",
2000
- description: "Slack channel ID of the message. It is always the channel where the automation posts.",
2001
- events: [MESSAGE_POSTED_EVENT]
2002
- },
2003
- userId: {
2004
- kind: "string",
2005
- description: "Slack user ID of the message author, or the bot ID (B…) of a bot post that has no user, such as an app integration. Required to run on bot posts."
2006
- },
2007
- location: {
2008
- kind: "string",
2009
- enum: [CHANNEL_LOCATION, THREAD_LOCATION],
2010
- description: "channel for a top-level message, thread for a thread reply. Leave out for top-level only; thread replies run only when this names thread."
1982
+ /** Split a normalized Slack reply into thread posts that fit Slack limits. */
1983
+ function splitSlackReplyText(text, format) {
1984
+ const chunks = [];
1985
+ let remaining = normalizeSlackReplyMarkdown(text, format);
1986
+ while (remaining.length > MAX_INLINE_CHARS) {
1987
+ const { chunk, rest } = takeChunk(remaining);
1988
+ chunks.push(chunk);
1989
+ remaining = rest;
2011
1990
  }
2012
- });
1991
+ if (remaining) chunks.push(remaining);
1992
+ return chunks;
1993
+ }
1994
+ // src/chat/slack/reply.ts
2013
1995
  /**
2014
- * Event registration for new Slack channel messages and thread replies. Only
2015
- * event automations can use it, so watchEvents rejects it.
1996
+ * Resolve where a Turn posts in Slack.
1997
+ *
1998
+ * The channel is always the Destination channel. The thread comes from the
1999
+ * Turn Source, then the Conversation Location, then the Destination, and each
2000
+ * one counts only when it names that channel. Do not derive the target from
2001
+ * the Conversation id: an Automation or Watch Conversation can own a Slack
2002
+ * thread, and its id is not a Slack thread id.
2016
2003
  */
2017
- function slackChannelMessageEvents() {
2004
+ function resolveSlackReplyTarget(args) {
2005
+ const { channelId } = args.destination;
2006
+ const sourceThreadTs = args.source?.kind === "slack" && args.source.channelId === channelId ? args.source.threadTs : void 0;
2007
+ const locationThreadTs = args.location?.provider === "slack" && args.location.channelId === channelId ? args.location.threadTs : void 0;
2008
+ const threadTs = sourceThreadTs ?? locationThreadTs ?? args.destination.threadTs;
2018
2009
  return {
2019
- resourceTypes: [{
2020
- type: CHANNEL_RESOURCE_TYPE,
2021
- identifier: {
2022
- format: `"${SLACK_CURRENT_CHANNEL_IDENTIFIER}" for the channel where the automation is created`,
2023
- pattern: String.raw`^(?:current_channel|[CG][A-Z0-9]{2,})$`
2024
- },
2025
- supportedEvents: [MESSAGE_POSTED_EVENT],
2026
- suggestedEvents: [],
2027
- matchFields: CHANNEL_MESSAGE_MATCH_FIELDS
2028
- }],
2029
- events: { [MESSAGE_POSTED_EVENT]: {
2030
- reach: { anyOf: ["channelId"] },
2031
- guidance: "A person or bot posted a new message in this channel. A bot post runs the automation only when match names the bot in user_id, by its user ID or, for a post with no user, its bot ID. A thread reply runs it only when match.location names thread. A reply goes in the message's Slack thread. If the instructions do not apply to this message, end with no action."
2032
- } },
2033
- limits: { [CHANNEL_RESOURCE_TYPE]: {
2034
- watch: false,
2035
- watchUnavailableMessage: "Slack channel messages can trigger only an event automation in that channel. Use createAutomation with an event trigger."
2036
- } }
2010
+ channelId,
2011
+ ...threadTs ? { threadTs } : void 0
2037
2012
  };
2038
2013
  }
2014
+ /** Resolve known people for plugin formatting. Fails open, like the hooks. */
2015
+ async function resolveReplyMentions(text, teamId) {
2016
+ try {
2017
+ return await resolveHandleMentions(text, teamId);
2018
+ } catch (error) {
2019
+ logWarn("slack.reply.mentions.failed", { "exception.message": error instanceof Error ? error.message : String(error) });
2020
+ return;
2021
+ }
2022
+ }
2039
2023
  /**
2040
- * Set the `channelId` filter of a Slack channel-message trigger to the
2041
- * channel where the automation posts. A trigger that names another channel,
2042
- * or a saved trigger with an identifier, stays as it is for
2043
- * `requireSlackChannelMessageScope` to check.
2024
+ * Send one destination-visible Slack reply.
2025
+ *
2026
+ * Chunks oversized text, builds compact attribution and conversation footer
2027
+ * context, and posts through the shared Slack outbound boundary. Pass
2028
+ * `formatting` for agent replies so plugin formatting can use Location
2029
+ * defaults, such as a default repository, and mention known people.
2044
2030
  */
2045
- function slackChannelMessageTrigger(trigger, channelId) {
2046
- if (trigger.namespace !== "slack") return trigger;
2047
- if (trigger.identifier != null || trigger.match?.channelId !== void 0) return trigger;
2048
- return {
2049
- ...trigger,
2050
- match: {
2051
- ...trigger.match,
2052
- channelId
2053
- }
2031
+ async function sendSlackReply(args) {
2032
+ const format = args.formatting && {
2033
+ configuration: args.formatting.configuration,
2034
+ mentions: await resolveReplyMentions(args.text, args.formatting.teamId)
2054
2035
  };
2036
+ const posts = splitSlackReplyText(args.text, format).map((text) => ({
2037
+ text,
2038
+ cards: []
2039
+ }));
2040
+ const cards = (args.cards ?? []).map((card) => renderSlackCard(card, args.conversationId));
2041
+ for (let index = 0; index < cards.length; index += 5) {
2042
+ const group = cards.slice(index, index + 5);
2043
+ const lastPost = posts.at(-1);
2044
+ if (index === 0 && lastPost) lastPost.cards = group;
2045
+ else posts.push({
2046
+ text: "",
2047
+ cards: group
2048
+ });
2049
+ }
2050
+ const footer = buildSlackReplyFooter({
2051
+ conversationId: args.conversationId,
2052
+ replyAttribution: args.replyAttribution
2053
+ });
2054
+ const messageTs = [];
2055
+ let threadTs = args.threadTs;
2056
+ for (const [index, post] of posts.entries()) {
2057
+ const { text, cards } = post;
2058
+ const isFinalChunk = index === posts.length - 1;
2059
+ const blocks = buildSlackReplyBlocks(text, void 0) ?? [];
2060
+ for (const card of cards) if (!card.entity) blocks.push({
2061
+ type: "section",
2062
+ text: {
2063
+ type: "mrkdwn",
2064
+ text: card.text
2065
+ }
2066
+ });
2067
+ if (isFinalChunk || !text.trim()) blocks.push(...buildSlackReplyBlocks("", footer) ?? []);
2068
+ const entities = cards.flatMap((card) => card.entity ? [card.entity] : []);
2069
+ const accessibleText = [text, ...cards.map((card) => card.text)].filter(Boolean).join("\n\n");
2070
+ const fallbackText = isFinalChunk && args.replyAttribution ? `${accessibleText}\n\n${escapeSlackMrkdwnText(formatReplyAttribution(args.replyAttribution))}` : accessibleText;
2071
+ const response = await postSlackMessage({
2072
+ channelId: args.channelId,
2073
+ threadTs,
2074
+ text: fallbackText,
2075
+ ...blocks.length ? { blocks } : void 0,
2076
+ ...entities.length ? { entities } : void 0
2077
+ });
2078
+ if (response.ts) {
2079
+ messageTs.push(response.ts);
2080
+ threadTs ??= response.ts;
2081
+ }
2082
+ }
2083
+ return messageTs;
2055
2084
  }
2085
+ // src/chat/slack/automated-turn-limit-notice.ts
2056
2086
  /**
2057
- * Bind a Slack channel-message automation to its own channel.
2087
+ * Pause notice for the consecutive automated-turn limit.
2058
2088
  *
2059
- * The trigger names the channel with a `channelId` filter. A saved trigger
2060
- * can name it with an identifier instead, where `current_channel` means the
2061
- * destination channel. Reject other channels, so private channel text cannot
2062
- * reach another channel.
2089
+ * Best-effort: a failed post must not fail the Turn or re-enable event wakes.
2090
+ * The consecutive-turn limit claims the notice slot before this post. Clear that
2091
+ * claim when the post fails or is skipped so a later paused wake can try again.
2063
2092
  */
2064
- function requireSlackChannelMessageScope(automation) {
2065
- if (automation.trigger.namespace !== "slack") return automation;
2066
- const channelId = automation.destination.channelId;
2067
- if (!CHANNEL_ID_PATTERN.test(channelId)) throw new ToolInputError("A Slack channel-message automation works only in a channel, not in a DM.");
2068
- const { identifier, match } = automation.trigger;
2069
- if ((identifier === void 0 ? match?.channelId : identifier === "current_channel" ? channelId : identifier) !== channelId) throw new ToolInputError("A Slack channel-message automation can watch only the channel where it posts. Leave out the channel_id filter, or create the automation in the channel to watch.");
2070
- return {
2071
- ...automation,
2072
- credentialMode: "system",
2073
- trigger: {
2074
- ...automation.trigger,
2075
- ...identifier === void 0 ? void 0 : { identifier: channelId }
2093
+ async function releaseFailedNoticeClaim(args) {
2094
+ try {
2095
+ await clearAutomatedTurnLimitNoticeClaim(args);
2096
+ } catch (error) {
2097
+ logException(error, "automated_turn_limit.notice_claim_clear_failed");
2098
+ }
2099
+ }
2100
+ /** Post the pause notice for one Conversation Location when known. */
2101
+ async function postAutomatedTurnLimitNoticeForConversation(args) {
2102
+ try {
2103
+ const conversation = await getConversationStore().get({ conversationId: args.conversationId });
2104
+ const location = conversation?.parentConversationId ? void 0 : conversation?.location;
2105
+ if (!location || location.provider !== "slack") {
2106
+ logWarn("automated_turn_limit.notice_skipped", {
2107
+ conversationId: args.conversationId,
2108
+ "app.automated_turn_limit.reason": location ? "unsupported_location" : "missing_location"
2109
+ });
2110
+ await releaseFailedNoticeClaim({
2111
+ conversationId: args.conversationId,
2112
+ nowMs: args.nowMs
2113
+ });
2114
+ return false;
2076
2115
  }
2077
- };
2116
+ await sendSlackReply({
2117
+ ...resolveSlackReplyTarget({
2118
+ destination: location,
2119
+ location,
2120
+ source: args.source
2121
+ }),
2122
+ conversationId: args.conversationId,
2123
+ text: buildAutomatedTurnLimitResponse({ maxTurns: args.maxTurns })
2124
+ });
2125
+ return true;
2126
+ } catch (error) {
2127
+ logException(error, "automated_turn_limit.notice_failed", { conversationId: args.conversationId });
2128
+ await releaseFailedNoticeClaim({
2129
+ conversationId: args.conversationId,
2130
+ nowMs: args.nowMs
2131
+ });
2132
+ return false;
2133
+ }
2134
+ }
2135
+ /** Post the pause notice after a finished Turn hits the limit. */
2136
+ async function maybePostAutomatedTurnLimitNotice(args) {
2137
+ if (!args.update?.shouldPostNotice) return;
2138
+ await postAutomatedTurnLimitNoticeForConversation({
2139
+ conversationId: args.conversationId,
2140
+ maxTurns: args.maxTurns,
2141
+ nowMs: args.nowMs,
2142
+ source: args.source
2143
+ });
2144
+ }
2145
+ // src/chat/task-input.ts
2146
+ /**
2147
+ * Shared agent input for tasks: one `<task>` input tag. A task can come from
2148
+ * a schedule, an event, or a watch. Call sites supply facts; this module owns
2149
+ * layout and the reply contract. Unit snapshots in
2150
+ * `tests/unit/chat/task-input.test.ts` own the exact text. Event data stays in
2151
+ * its own child tags, and the outcome rule is always last.
2152
+ */
2153
+ /**
2154
+ * Shared closing lines. Automations pass outcomes and end with an answer
2155
+ * tool. Watches follow the Conversation's reply rules. A Watch reply goes
2156
+ * only to the Conversation, so a question asked in the provider must also get
2157
+ * its answer there. Watch instructions often say to stay silent, so this rule
2158
+ * sits in the contract, not in plugin guidance.
2159
+ */
2160
+ function replyContractLines(outcomes) {
2161
+ if (!outcomes) return [
2162
+ "When an Event asks you a question, answer it where it was asked, with that provider's tool. Then reply with the answer and a link to it.",
2163
+ "When you reply, follow any reply format in the instructions.",
2164
+ `When the outcome needs nobody's attention, such as a routine fix that worked or feedback that you handled, end the Turn with \`${NO_REPLY_TOOL_NAME}\` and put the outcome in its \`note\`. The note stays in the Conversation but notifies nobody. Do not use it when the instructions say to notify, mention, or report to a person, when the reply asks a question, when a person must decide or act, or when something failed.`
2165
+ ];
2166
+ return [`End with \`${REPLY_TOOL_NAME}\`, \`${NO_REPLY_TOOL_NAME}\`, or \`${REPORT_BLOCKED_TOOL_NAME}\`.`];
2167
+ }
2168
+ function oneLine(value) {
2169
+ return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
2170
+ }
2171
+ function clip(value, maxLength) {
2172
+ return maxLength === void 0 ? value : value.slice(0, maxLength);
2173
+ }
2174
+ const CREATOR_REFERENCE = /\bthe Automation creator\b/gi;
2175
+ /**
2176
+ * Write the creator mention where the instructions say "the Automation
2177
+ * creator", so the run does not have to swap it in.
2178
+ */
2179
+ function mentionCreator(instructions, creator) {
2180
+ return instructions.replace(CREATOR_REFERENCE, () => creator);
2181
+ }
2182
+ function quoted(values) {
2183
+ return values.map((value) => `"${value}"`).join(" or ");
2078
2184
  }
2079
2185
  /**
2080
- * Build the Event for one new channel message or thread reply, or nothing.
2081
- *
2082
- * Slackbot posts do not count. Bot posts are marked with `postedByBot`, so
2083
- * only automations that name the bot can run on them. Thread replies carry
2084
- * the `thread` location, so only automations that name it can run on them.
2186
+ * Render each linked person once. A doer in `<people>` gets a note in that
2187
+ * list. Other doers get a `<done-by>` tag. Without one entry per person, the
2188
+ * agent can mention a person and then name them again by handle as if they
2189
+ * were someone else. The "you" rule covers doers outside `<people>` too,
2190
+ * because instructions can still ask to mention them, such as a requester who
2191
+ * reviews their own pull request. A child agent replies to its parent, not to
2192
+ * the person, so it writes the mention instead of the handle. That carries
2193
+ * who the person is up each level to the agent that replies to them.
2085
2194
  */
2086
- function slackChannelMessageEvent(input) {
2087
- const { author } = input;
2088
- if (author.kind === "user" && author.userId === "USLACKBOT") return void 0;
2089
- if (!CHANNEL_ID_PATTERN.test(input.channelId)) return void 0;
2090
- const postedByBot = author.kind === "bot" || Boolean(input.botId || input.subtype === "bot_message");
2091
- const userId = author.kind === "bot" ? author.botId : author.userId;
2092
- const threadTs = input.threadTs && input.threadTs !== input.ts ? input.threadTs : void 0;
2093
- return {
2094
- eventKey: `${input.channelId}:${input.ts}`,
2095
- eventType: MESSAGE_POSTED_EVENT,
2096
- identifier: input.channelId,
2097
- occurredAtMs: Math.floor(Number(input.ts) * 1e3),
2098
- trustedSummary: `${postedByBot ? "The bot " : ""}${author.kind === "bot" ? author.botId : `<@${author.userId}>`} posted a new ${threadTs ? `thread reply under message ${threadTs}` : "message"} in <#${input.channelId}>.`,
2099
- data: {
2100
- channelId: input.channelId,
2101
- location: threadTs ? THREAD_LOCATION : CHANNEL_LOCATION,
2102
- messageTs: input.ts,
2103
- ...threadTs ? { threadTs } : void 0,
2104
- userId,
2105
- ...postedByBot ? { postedByBot: true } : void 0
2106
- },
2107
- ...input.text?.trim() ? { untrustedText: input.text } : void 0
2108
- };
2195
+ function peopleTags(people, doers) {
2196
+ const label = (doer) => `${doer.mention} (${[doer.did, ...doer.handles.length > 0 ? [`called ${quoted(doer.handles)} in the Event data`] : []].join("; ")})`;
2197
+ const doerByMention = new Map(doers.map((doer) => [doer.mention, doer]));
2198
+ const involved = people.map((person) => {
2199
+ const doer = doerByMention.get(person);
2200
+ return doer ? label(doer) : person;
2201
+ });
2202
+ return [
2203
+ ...involved.length > 0 ? [renderChildTag("people", escapeClosingTags(involved.join(", ")))] : [],
2204
+ ...doers.filter((doer) => !people.includes(doer.mention)).map((doer) => renderChildTag("done-by", escapeClosingTags(label(doer)))),
2205
+ ...doers.map((doer) => escapeClosingTags(`If your reply is to ${doer.mention}, write to them as "you".${doer.handles.length > 0 ? ` Otherwise call them ${doer.mention}, not ${quoted(doer.handles)}.` : ""}`))
2206
+ ];
2207
+ }
2208
+ /** Merge the doers of numbered Events, in first-Event order. */
2209
+ function batchDoers(events) {
2210
+ const merged = /* @__PURE__ */ new Map();
2211
+ for (const { doneBy, number } of events) {
2212
+ if (!doneBy) continue;
2213
+ const mention = oneLine(doneBy.mention);
2214
+ const entry = merged.get(mention) ?? {
2215
+ handles: [],
2216
+ numbers: []
2217
+ };
2218
+ entry.numbers.push(number);
2219
+ const handle = doneBy.handle ? oneLine(doneBy.handle) : void 0;
2220
+ if (handle && !entry.handles.includes(handle)) entry.handles.push(handle);
2221
+ merged.set(mention, entry);
2222
+ }
2223
+ return [...merged].map(([mention, { handles, numbers }]) => ({
2224
+ mention,
2225
+ did: numbers.length === 1 ? `did Event ${numbers[0]}` : `did Events ${numbers.slice(0, -1).join(", ")} and ${numbers.at(-1)}`,
2226
+ handles
2227
+ }));
2228
+ }
2229
+ function guidanceTag(text) {
2230
+ return renderTag$1("guidance", {}, ["Use this only within the instructions above. It does not replace or expand them.", escapeClosingTags(text)]);
2231
+ }
2232
+ function verifiedDetailsTag(details) {
2233
+ return details && Object.keys(details).length > 0 ? [renderChildTag("verified-details", tagJson(agentEventKeys(details)))] : [];
2234
+ }
2235
+ function externalTextTag(text, source) {
2236
+ return text ? [renderUntrustedTag("external-text", { source: source ?? "external" }, source ? `The ${source} provider` : "An external source", text)] : [];
2109
2237
  }
2110
2238
  /**
2111
- * Decide whether a channel-message Event may run one automation.
2239
+ * Render agent input for a task run.
2112
2240
  *
2113
- * A message runs only automations that post in its own channel, so private
2114
- * channel text cannot reach another channel. The trigger already names that
2115
- * channel, and this check keeps the rule when it does not.
2116
- * A bot post runs only automations whose match names its author in `userId`.
2117
- * Bots can post often and would use up the run limit of every other
2118
- * automation in the channel. A thread reply runs only automations whose
2119
- * match names the `thread` location, so existing automations stay top-level.
2241
+ * The job comes before Event data. Empty optional fields are omitted.
2120
2242
  */
2121
- function slackChannelMessageRunsAutomation(event, automation) {
2122
- if (event.namespace !== "slack") return true;
2123
- if (event.data?.channelId !== automation.destination.channelId) return false;
2124
- if (event.data?.location === THREAD_LOCATION && ![automation.trigger.match?.location].flat().includes(THREAD_LOCATION)) return false;
2125
- if (event.data?.postedByBot !== true) return true;
2126
- return automation.trigger.match?.userId !== void 0;
2243
+ function renderTaskInput(args) {
2244
+ const instructions = args.instructions?.trim() ?? "";
2245
+ if (!instructions && !args.skill) throw new Error("Task instructions are required");
2246
+ const about = args.about?.trim();
2247
+ const creator = args.creator?.trim();
2248
+ const people = (args.people ?? []).map((person) => oneLine(person)).filter(Boolean);
2249
+ const guidance = args.guidance?.trim();
2250
+ const trustedSummary = args.trustedSummary?.trim();
2251
+ const externalText = args.externalText?.trim();
2252
+ return renderTag$1("task", {
2253
+ about: about ? oneLine(about) : void 0,
2254
+ event: args.event
2255
+ }, [
2256
+ ...creator ? [renderChildTag("created-by", escapeClosingTags(`${oneLine(creator)}. This person is the Automation creator. "The Automation creator", "me", and "my" in the instructions mean this person. Where the instructions refer to this person, write this mention in the message. If they do not, do not mention this person.`))] : [],
2257
+ ...peopleTags(people, args.doneBy ? [{
2258
+ mention: oneLine(args.doneBy.mention),
2259
+ did: "did what this Event describes",
2260
+ handles: args.doneBy.handle ? [oneLine(args.doneBy.handle)] : []
2261
+ }] : []),
2262
+ ...args.skill ? [instructions ? `Run the ${args.skill} skill. The instructions below add context for this run.` : `Run the ${args.skill} skill.`] : [],
2263
+ ...instructions ? [renderChildTag("instructions", escapeClosingTags(creator ? mentionCreator(instructions, oneLine(creator)) : instructions))] : [],
2264
+ ...guidance ? [guidanceTag(guidance)] : [],
2265
+ ...trustedSummary ? [renderChildTag("summary", escapeClosingTags(clip(trustedSummary, args.trustedSummaryMaxLength)))] : [],
2266
+ ...verifiedDetailsTag(args.verifiedDetails),
2267
+ ...externalTextTag(externalText && clip(externalText, args.externalTextMaxLength), args.source),
2268
+ ...replyContractLines(args.outcomes)
2269
+ ]);
2127
2270
  }
2128
- /** Return the source message thread for a channel-message run. */
2129
- function slackChannelMessageReplyThreadTs(event) {
2130
- if (event.namespace !== "slack") return void 0;
2131
- const messageTs = event.data?.threadTs ?? event.data?.messageTs;
2132
- return typeof messageTs === "string" ? messageTs : void 0;
2271
+ function eventTag(event, index) {
2272
+ const trustedSummary = event.trustedSummary?.trim();
2273
+ return renderTag$1("event", {
2274
+ index,
2275
+ type: event.eventType
2276
+ }, [
2277
+ ...trustedSummary ? [renderChildTag("summary", escapeClosingTags(trustedSummary))] : [],
2278
+ ...verifiedDetailsTag(event.verifiedDetails),
2279
+ ...externalTextTag(event.externalText?.trim(), event.source)
2280
+ ]);
2133
2281
  }
2134
- // src/chat/events/runtime-catalog.ts
2135
2282
  /**
2136
- * Enabled event registrations for search, guidance, and tool schemas.
2283
+ * Render one `<task>` for several Watch Events that arrived together.
2137
2284
  *
2138
- * Includes core Workspace snapshot events under the `junior` namespace, Slack
2139
- * channel-message events under the `slack` namespace, plus every enabled plugin
2140
- * registration. Plugins may not use the `junior` or `slack` namespaces.
2285
+ * Each `<watch>` group states its instructions once, then lists its Events.
2286
+ * Child tags match `renderTaskInput`. The outcome rule appears once, at the
2287
+ * end.
2141
2288
  */
2142
- function getEventCatalog() {
2143
- const snapshot = workspaceSnapshotEvents();
2144
- const catalog = {
2145
- [CORE_EVENT_NAMESPACE]: eventCatalogEntry({
2146
- displayName: botConfig.userName,
2147
- resourceTypes: [...snapshot.resourceTypes, {
2148
- type: "timer",
2149
- supportedEvents: ["timer.fired"],
2150
- suggestedEvents: []
2151
- }],
2152
- events: {
2153
- ...snapshot.events,
2154
- "timer.fired": { reach: "resource" }
2155
- },
2156
- limits: {
2157
- ...snapshot.limits,
2158
- timer: {
2159
- automation: false,
2160
- watch: false,
2161
- watchUnavailableMessage: "Use watchTimer to create a timer Watch."
2162
- }
2163
- }
2164
- }),
2165
- [SLACK_EVENT_NAMESPACE]: eventCatalogEntry({
2166
- ...slackChannelMessageEvents(),
2167
- displayName: "Slack"
2168
- })
2169
- };
2170
- for (const plugin of getPlugins()) {
2171
- const registration = plugin.events;
2172
- if (!registration || registration.isEnabled?.() === false) continue;
2173
- if (plugin.manifest.name === "junior" || plugin.manifest.name === "slack") throw new Error(`Plugin "${plugin.manifest.name}" cannot register events; that namespace is reserved for core events`);
2174
- catalog[plugin.manifest.name] = eventCatalogEntry({
2175
- ...registration,
2176
- displayName: plugin.manifest.displayName
2177
- });
2289
+ function renderTaskBatchInput(args) {
2290
+ const total = args.groups.reduce((count, group) => count + group.events.length, 0);
2291
+ if (total === 0) throw new Error("Task batch requires at least one Event");
2292
+ const body = [`You received ${total} ${total === 1 ? "event" : "events"}.`];
2293
+ let number = 0;
2294
+ for (const group of args.groups) {
2295
+ const instructions = group.instructions.trim();
2296
+ if (!instructions) throw new Error("Task instructions are required");
2297
+ const about = group.about?.trim();
2298
+ const people = group.people.map((person) => oneLine(person)).filter(Boolean);
2299
+ const numbered = group.events.map((event, index) => ({
2300
+ ...event,
2301
+ number: number + index + 1
2302
+ }));
2303
+ number += group.events.length;
2304
+ const guidance = /* @__PURE__ */ new Map();
2305
+ for (const event of group.events) {
2306
+ const text = event.guidance?.trim();
2307
+ if (text && !guidance.has(event.eventType)) guidance.set(event.eventType, text);
2308
+ }
2309
+ body.push(renderTag$1("watch", { about: about ? oneLine(about) : void 0 }, [
2310
+ ...peopleTags(people, batchDoers(numbered)),
2311
+ renderChildTag("instructions", escapeClosingTags(instructions)),
2312
+ ...guidance.size > 0 ? [guidanceTag([...guidance].map(([eventType, text]) => `- ${eventType}: ${text}`).join("\n"))] : [],
2313
+ ...numbered.map((event) => eventTag(event, event.number))
2314
+ ]));
2178
2315
  }
2179
- return catalog;
2316
+ return renderTag$1("task", {}, [...body, ...replyContractLines(void 0)]);
2180
2317
  }
2181
2318
  // src/chat/events/notification.ts
2182
2319
  const EVENT_WAIT_MS = 3e4;
@@ -2683,47 +2820,6 @@ async function loadTurnConversationNotes(input) {
2683
2820
  }
2684
2821
  return newestFirst.reverse();
2685
2822
  }
2686
- // src/chat/experimental.ts
2687
- /**
2688
- * Known unstable product features that must be opted into explicitly.
2689
- * Add new keys here as features graduate from private experiments; remove them
2690
- * once they become stable defaults.
2691
- */
2692
- const EXPERIMENTAL_FEATURES = [
2693
- "operator-tools",
2694
- "passive-routing",
2695
- "user-customization"
2696
- ];
2697
- const EXPERIMENTAL_FEATURE_SET = new Set(EXPERIMENTAL_FEATURES);
2698
- let configuredExperimental = {};
2699
- function isExperimentalFeature(value) {
2700
- return EXPERIMENTAL_FEATURE_SET.has(value);
2701
- }
2702
- /** Replace app-level experimental opt-ins and return the previous setting. */
2703
- function setExperimentalFeatures(config) {
2704
- const previous = { ...configuredExperimental };
2705
- if (config === void 0) {
2706
- configuredExperimental = {};
2707
- return previous;
2708
- }
2709
- const next = {};
2710
- for (const [rawName, enabled] of Object.entries(config)) {
2711
- if (enabled === void 0) continue;
2712
- if (typeof enabled !== "boolean") throw new Error(`experimental.${rawName} must be a boolean when provided`);
2713
- if (!isExperimentalFeature(rawName)) throw new Error(`experimental.${rawName} is not a known experimental feature. Known features: ${EXPERIMENTAL_FEATURES.join(", ")}`);
2714
- next[rawName] = enabled;
2715
- }
2716
- configuredExperimental = next;
2717
- return previous;
2718
- }
2719
- /** Return a copy of the app-level experimental opt-ins configured by createApp(). */
2720
- function getExperimentalFeatures() {
2721
- return { ...configuredExperimental };
2722
- }
2723
- /** Return whether one experimental feature is enabled via createApp({ experimental }). */
2724
- function isExperimentalFeatureEnabled(feature) {
2725
- return configuredExperimental[feature] === true;
2726
- }
2727
2823
  // src/chat/identities/customization.ts
2728
2824
  /** Read the saved customization for one user. */
2729
2825
  async function readUserCustomization(userId) {
@@ -3327,4 +3423,4 @@ async function saveStoppedConversationEvents(conversationId, messages) {
3327
3423
  }
3328
3424
  }]);
3329
3425
  }
3330
- export { sendSlackReply as $, turnInputFactsFromConversationMessage as A, requireSlackChannelMessageScope as B, getAuthPausedConversationTurnId as C, parseEventMessages as D, listActiveMailboxTurns as E, isEventMailboxMetadata as F, WORKSPACE_SNAPSHOT_FAILED_EVENT as G, slackChannelMessageReplyThreadTs as H, renderEventBatchInputs as I, workspaceSnapshotWatch as J, WORKSPACE_SNAPSHOT_READY_EVENT as K, timerWatchCredentialSubject as L, EVENT_WAIT_MS as M, enqueueEventNotification as N, resolveMailboxTurnWork as O, eventBatchMessageMeta as P, resolveSlackReplyTarget as Q, getEventCatalog as R, addConversationNote as S, listActiveMailboxTurnSources as T, slackChannelMessageRunsAutomation as U, slackChannelMessageEvent as V, slackChannelMessageTrigger as W, maybePostAutomatedTurnLimitNotice as X, renderTaskInput as Y, postAutomatedTurnLimitNoticeForConversation as Z, readUserCustomization as _, session_stop_exports as a, conversationSubtreeColumns as at, isExperimentalFeatureEnabled as b, loadReviewItemInput as c, JUNIOR_PERSONALITY as ct, buildPromptInput as d, buildAgentsInstructionsMessage as dt, renderSlackObjectCard as et, buildSteeringPiMessage as f, findVisibleAgentsInstructions as ft, withoutSavedSteeringMessages as g, loadPromptTurnContext as h, showsAgentsInstructions as ht, resumeStoppedConversationTree as i, conversationSubtree as it, legacyWebMailboxMetadataSchema as j, sourceFromTurnInput as k, savedInputInstruction as l, AGENTS_REMOVAL_NOTICE as lt, instructionForInputs as m, renderAgentsInstructions as mt, isSkippedAfterConversationStop as n, recordFinishedTurnForAutomatedLimit as nt, skipInputAfterConversationStop as o, buildDeploymentSystemPrompt as ot, instructionActorFor as p, readRepositoryInstructions as pt, workspaceSnapshotFinishedEvent as q, markConversationsStopped as r, resetAutomatedTurnLimit as rt, eventReviewItemInputs as s, systemPromptHash as st, getConversationStoppedAtMs as t, admitAutomatedTurn as tt, assemblePrompt as u, AGENTS_REPLACEMENT_NOTICE as ut, saveUserCustomization as v, getEventBatchDelayMs as w, setExperimentalFeatures as x, getExperimentalFeatures as y, SLACK_EVENT_NAMESPACE as z };
3426
+ export { slackChannelMessageEvent as $, enqueueEventNotification as A, resolveEventMentions as B, listActiveMailboxTurns as C, turnInputFactsFromConversationMessage as D, sourceFromTurnInput as E, renderTaskInput as F, conversationSubtree as G, admitAutomatedTurn as H, maybePostAutomatedTurnLimitNotice as I, isExperimentalFeatureEnabled as J, conversationSubtreeColumns as K, postAutomatedTurnLimitNoticeForConversation as L, isEventMailboxMetadata as M, renderEventBatchInputs as N, legacyWebMailboxMetadataSchema as O, timerWatchCredentialSubject as P, requireSlackChannelMessageScope as Q, resolveSlackReplyTarget as R, listActiveMailboxTurnSources as S, resolveMailboxTurnWork as T, recordFinishedTurnForAutomatedLimit as U, renderSlackObjectCard as V, resetAutomatedTurnLimit as W, getEventCatalog as X, setExperimentalFeatures as Y, SLACK_EVENT_NAMESPACE as Z, readUserCustomization as _, session_stop_exports as a, workspaceSnapshotFinishedEvent as at, getAuthPausedConversationTurnId as b, loadReviewItemInput as c, JUNIOR_PERSONALITY as ct, buildPromptInput as d, buildAgentsInstructionsMessage as dt, slackChannelMessageReplyThreadTs as et, buildSteeringPiMessage as f, findVisibleAgentsInstructions as ft, withoutSavedSteeringMessages as g, loadPromptTurnContext as h, showsAgentsInstructions as ht, resumeStoppedConversationTree as i, WORKSPACE_SNAPSHOT_READY_EVENT as it, eventBatchMessageMeta as j, EVENT_WAIT_MS as k, savedInputInstruction as l, AGENTS_REMOVAL_NOTICE as lt, instructionForInputs as m, renderAgentsInstructions as mt, isSkippedAfterConversationStop as n, slackChannelMessageTrigger as nt, skipInputAfterConversationStop as o, workspaceSnapshotWatch as ot, instructionActorFor as p, readRepositoryInstructions as pt, getExperimentalFeatures as q, markConversationsStopped as r, WORKSPACE_SNAPSHOT_FAILED_EVENT as rt, eventReviewItemInputs as s, buildDeploymentSystemPrompt as st, getConversationStoppedAtMs as t, slackChannelMessageRunsAutomation as tt, assemblePrompt as u, AGENTS_REPLACEMENT_NOTICE as ut, saveUserCustomization as v, parseEventMessages as w, getEventBatchDelayMs as x, addConversationNote as y, sendSlackReply as z };