@sentry/junior 0.301.0 → 0.303.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 (101) hide show
  1. package/dist/adapter-context-BdVnSuY5.js +43 -0
  2. package/dist/{admin-CRJHvCGg.js → admin-AfeAdS3J.js} +2 -2
  3. package/dist/{agent-runner-H4YhvNBj.js → agent-runner-BP8_DLUv.js} +4688 -13870
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -8
  6. package/dist/api.d.ts +13 -12
  7. package/dist/api.js +268 -118
  8. package/dist/{app-HDZglaIu.d.ts → app-Dd9v1mNx.d.ts} +15 -15
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +99 -330
  11. package/dist/{automation-Cva5ZOwW.js → automation-D9MvhOWY.js} +3 -1
  12. package/dist/{background-compaction-queue-CNrZ3QcU.js → background-compaction-queue-xaE05jxH.js} +97 -206
  13. package/dist/{briefs-x6Mzwxmg.js → briefs-D8i-dKTp.js} +4 -4
  14. package/dist/{catalog-runtime-BEY6EGRi.js → catalog-runtime-d1EM6Z0V.js} +2 -2
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +21 -21
  17. package/dist/cli/check.js +8 -8
  18. package/dist/cli/env.d.ts +1 -0
  19. package/dist/cli/env.js +8 -7
  20. package/dist/cli/init.js +13 -4
  21. package/dist/cli/main.js +4 -4
  22. package/dist/cli/plugins.js +6 -6
  23. package/dist/cli/snapshot-create.js +7 -5
  24. package/dist/cli/upgrade.d.ts +2 -2
  25. package/dist/cli/upgrade.js +5 -5
  26. package/dist/{config-CmjhyqgB.js → config-oGM7KA9M.js} +44 -63
  27. package/dist/{connections-CfIRm0xv.js → connections-BlikzEJv.js} +6 -6
  28. package/dist/{continue-in-slack-DPoABVkB.js → continue-in-slack-BZnYifiG.js} +5 -6
  29. package/dist/{conversation-BNXfq6Lb.js → conversation-CY1jnBiC.js} +1 -1
  30. package/dist/{conversation-feed-CfpyFMHP.js → conversation-feed-BZJRk6UV.js} +2 -1
  31. package/dist/{conversation-privacy-0CM0V2qK.js → conversation-privacy-Cx515ddM.js} +7 -7
  32. package/dist/{conversation-turn-C0sxyvS-.js → conversation-turn-DAhRdX4m.js} +20 -24
  33. package/dist/{credential-sync-tEMKZ_8M.js → credential-sync-DfhmWFeo.js} +18 -20
  34. package/dist/{db-Czra10QW.js → db-C-2tFxk3.js} +326 -17
  35. package/dist/{db-BdUHQhrC.d.ts → db-DPqcEM9_.d.ts} +25 -25
  36. package/dist/{executor-D_023K0H.js → executor-NVfS8aQ2.js} +51 -10
  37. package/dist/{history-IjdmO_r6.js → history-UZ3M2M9r.js} +13 -10
  38. package/dist/install-CHLrpRZc.js +228 -0
  39. package/dist/instrumentation.d.ts +4 -4
  40. package/dist/instrumentation.js +10 -10
  41. package/dist/{lineage-DmMIE0VL.js → lineage-HGLhd_-N.js} +2 -2
  42. package/dist/{logging-DcjLDDqi.js → logging-DiyqRLBx.js} +24 -20
  43. package/dist/{message-C0JY9RJP.js → message-CkCOcbFH.js} +9 -9
  44. package/dist/{model-input-CBp-p24N.js → model-input-DmoPPtPE.js} +5 -10
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +7 -6
  47. package/dist/{oauth-callback-server-BRq9QNhU.js → oauth-callback-server-CIf_6YmA.js} +5 -4
  48. package/dist/{oauth-relay-DRzq73b6.js → oauth-relay-DAmfVmJu.js} +3 -6
  49. package/dist/{package-discovery-DJhGdS4c.js → package-discovery-x4AvVhMj.js} +1 -1
  50. package/dist/{plugin-module-Cf5gVPWP.js → plugin-module-Cv2ETe8Y.js} +1 -1
  51. package/dist/{plugins-BBX07Jzt.js → plugins-Bkk0XRo2.js} +3 -3
  52. package/dist/{projection-CQNDOi82.js → projection-DBq8tsA5.js} +489 -223
  53. package/dist/{prompt-DLUB5m72.js → prompt-D2KlJopL.js} +15 -5
  54. package/dist/{queue-CZyYgPF0.d.ts → queue-CbEHUO0l.d.ts} +1 -1
  55. package/dist/queue-DFaOscp5.js +115 -0
  56. package/dist/{registry-Dj377ADs.js → registry-Bu0Z9BEO.js} +37 -37
  57. package/dist/{resolve-DJkh9Fky.js → resolve-DXuA3G0g.js} +4 -229
  58. package/dist/{result-C8iIpDl1.js → result-DpiNseDA.js} +11 -16
  59. package/dist/rolldown-runtime-BKpuH2hG.js +26 -0
  60. package/dist/{runner-DZqrOy8C.js → runner-iu1heRFv.js} +10 -10
  61. package/dist/{sandbox-egress-signals-CGwH86S9.js → sandbox-egress-signals-2HFYDcQf.js} +1 -1
  62. package/dist/{schema-CdZFn7Qd.d.ts → schema-DHMOaRzC.d.ts} +959 -41
  63. package/dist/{schema-DyHXiQKI.js → schema-DvfX3Gq_.js} +141 -40
  64. package/dist/{secrets-DebYU866.js → secrets-DHaJ5TTn.js} +4 -4
  65. package/dist/{sentry-BRTJqumy.js → sentry-CPbZjomA.js} +3 -28
  66. package/dist/{sentry-route-name-BhwWnfqj.js → sentry-route-name-C6EIzAGP.js} +1 -1
  67. package/dist/{service-account-suY004dx.js → service-account-BcT5LR7V.js} +271 -20
  68. package/dist/{service-account-D6jGR4a1.js → service-account-xYkaQTrw.js} +3 -3
  69. package/dist/{session-stop-BLmfFI3d.js → session-stop-BLLp1IP_.js} +1098 -1110
  70. package/dist/{skills-CmNG0dHb.js → skills-CNAGH4ju.js} +6 -9
  71. package/dist/{slack-conversation-unfurl-Bty-DlHe.js → slack-conversation-unfurl-DYnqe5ci.js} +10 -14
  72. package/dist/{spawn-CNjkpXpk.js → spawn-cGasWW33.js} +7 -7
  73. package/dist/{state-CEbZuZD6.js → state-CDS6h_Wv.js} +34 -5
  74. package/dist/{stop-Bjy2-K4H.js → stop-DMMA67yT.js} +896 -196
  75. package/dist/{store-DmV4CoNr.js → store-Dgs7Oe44.js} +5 -5
  76. package/dist/{task-queue-AhG1tSXR.js → task-queue-DcF0nhhz.js} +3 -3
  77. package/dist/{task-runner-BMxZI3o7.js → task-runner-BGXF7Fo7.js} +15 -20
  78. package/dist/{thread-context-CXLnbg7g.js → thread-context-BPky1KBe.js} +12 -12
  79. package/dist/{store-Epv6t4vV.js → turn-session-routing-DGvn9MSl.js} +384 -13
  80. package/dist/{turn-user-message-DsUZi9gn.js → turn-user-message-19CkuUvM.js} +3 -3
  81. package/dist/{validation-DOz8X9BU.js → validation-lu1DgjNQ.js} +2 -2
  82. package/dist/vercel.js +1 -1
  83. package/dist/{version-CGMRmMPK.js → version-Uo3c94Dx.js} +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/{viewer-H3EsMWtJ.js → viewer-BPQHMx3-.js} +3 -3
  86. package/dist/warmup-H8uLvW9e.js +13946 -0
  87. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  88. package/dist/{worker-ClphajjD.js → worker-B-pM_-3K.js} +9 -12
  89. package/migrations/0108_conversation_embeddings.sql +13 -0
  90. package/migrations/0109_user_preferences.sql +1 -0
  91. package/migrations/0110_code_change_repository_state_index.sql +1 -0
  92. package/migrations/meta/0108_snapshot.json +4688 -0
  93. package/migrations/meta/0109_snapshot.json +4925 -0
  94. package/migrations/meta/0110_snapshot.json +4952 -0
  95. package/migrations/meta/_journal.json +22 -1
  96. package/package.json +16 -17
  97. package/dist/adapter-CNjGEJO9.js +0 -303
  98. package/dist/reporting-window-DopzcOHh.js +0 -137
  99. package/dist/turn-session-routing-BD3-jJl7.js +0 -380
  100. package/dist/users-BxvYclQg.js +0 -424
  101. package/dist/warmup-CdU5hR49.js +0 -3715
@@ -1,18 +1,17 @@
1
- import { v as __exportAll } from "./sentry-BRTJqumy.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, cr as getPluginSlackConversationLink, ct as listTurnSummaries, di as cancelSubscriptions, do as sandboxSkillFile, dr as getPluginUserPromptContributions, eo as ToolInputError, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillPathResolution, fr as getPlugins, ha as normalizeSlackReplyMarkdown, in as REPLY_TOOL_NAME, ji as getDashboardObjectIconLink, ki as getDashboardConversationLink, lo as SANDBOX_WORKSPACE_ROOT, lr as getPluginSystemPromptContributions, ma as formatSlackLink, oo as SANDBOX_DATA_ROOT, ot as getStoredTurnFields, pa as escapeSlackMrkdwnText, qn as renderTag$1, so as SANDBOX_REPOS_ROOT, st as getTurnRecord, uo as sandboxSkillDir, vn as REPORT_BLOCKED_TOOL_NAME, x as toStoredConversationMessage, zn as REQUEST_CONTEXT_SECTION_TAG } from "./projection-CQNDOi82.js";
3
- import { I as renderCurrentInstruction, R as escapeXml, n as botConfig, z as escapeXmlText } from "./config-CmjhyqgB.js";
4
- import { W as normalizeIdentityEmail, h as logWarn, m as logInfo, p as logException, v as serializeGenAiAttribute } from "./logging-DcjLDDqi.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
+ import { Ai as JUNIOR_THREAD_STATE_TTL_MS, Bn as SCRIPT_TOOLS_SECTION_TAG, Fn as retainRuntimeTurnContext, Hn as TURN_CONTEXT_TAG, In as stripRuntimeTurnContext, Ji as listWorkspaces, Jn as renderUntrustedTag, Kn as renderChildTag, M as normalizeConversationText, Ni as getDashboardObjectIconLink, Nn as latestTurnContextSection, Pr as getReviewItem, Rn as CAPABILITY_SECTION_TAG, Ro as buildSentryConversationUrl, Tn as hasRuntimeTurnContext, Un as escapeClosingTags, Vn as SESSION_CONTEXT_SECTION_TAG, Wn as escapeTagText, Yn as tagJson, _a as normalizeSlackReplyMarkdown, co as SANDBOX_DATA_ROOT, ct as listTurnSummaries, do as SANDBOX_WORKSPACE_ROOT, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillDir, ga as formatSlackLink, ha as escapeSlackMrkdwnText, in as REPLY_TOOL_NAME, ji as getDashboardConversationLink, ka as postSlackMessage, ki as verifyTimerWatchCredentialSubject, lo as SANDBOX_REPOS_ROOT, lr as getPluginUserPromptContributions, mo as sandboxSkillPathResolution, no as ToolInputError, or as getPluginSlackConversationLink, ot as getStoredTurnFields, pi as cancelSubscriptions, po as sandboxSkillFile, qn as renderTag$1, sr as getPluginSystemPromptContributions, st as getTurnRecord, ur as getPlugins, vn as REPORT_BLOCKED_TOOL_NAME, x as toStoredConversationMessage, ya as slackMention, zn as REQUEST_CONTEXT_SECTION_TAG } from "./projection-DBq8tsA5.js";
3
+ 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-C-2tFxk3.js";
4
+ import { I as renderCurrentInstruction, R as escapeXml, n as botConfig, z as escapeXmlText } from "./config-oGM7KA9M.js";
5
+ import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-x4AvVhMj.js";
6
+ import { G as normalizeIdentityEmail, h as logWarn, m as logInfo, p as logException, v as serializeGenAiAttribute } from "./logging-DiyqRLBx.js";
7
+ 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-D2KlJopL.js";
8
+ import { c as formatUserInputAnswer, h as isVisionImageMediaType, v as userCustomizationTextSchema } from "./web-message-id-lNodcCOI.js";
9
+ import { M as juniorConversations, N as juniorIdentities, P as juniorUsers } from "./executor-NVfS8aQ2.js";
10
+ import { i as parseSkillFile } from "./skills-CNAGH4ju.js";
5
11
  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-Czra10QW.js";
7
- import { M as juniorIdentities, N as juniorUsers, j as juniorConversations } from "./executor-D_023K0H.js";
8
- import { r as getStateAdapter } from "./adapter-CNjGEJO9.js";
9
- import { a as listReferenceFiles, c as soulPathCandidates, l as worldPathCandidates } from "./package-discovery-DJhGdS4c.js";
10
- import { h as credentialSubjectSchema } from "./registry-Dj377ADs.js";
11
- import { i as parseSkillFile } from "./skills-CmNG0dHb.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-DLUB5m72.js";
13
- import { r as appendAndEnqueueInboundMessage } from "./store-DmV4CoNr.js";
14
- import { f as eventCatalogEntry, l as CORE_EVENT_NAMESPACE, p as eventGuidance } from "./turn-session-routing-BD3-jJl7.js";
15
- import { _ as userCustomizationTextSchema, m as isVisionImageMediaType, s as formatUserInputAnswer } from "./statuses-Hn-HsOph.js";
12
+ import { r as appendAndEnqueueInboundMessage } from "./store-Dgs7Oe44.js";
13
+ import { bt as eventGuidance, gt as CORE_EVENT_NAMESPACE, yt as eventCatalogEntry } from "./turn-session-routing-DGvn9MSl.js";
14
+ import { h as credentialSubjectSchema } from "./registry-Bu0Z9BEO.js";
16
15
  import * as z from "zod";
17
16
  import path from "node:path";
18
17
  import { isDeepStrictEqual } from "node:util";
@@ -1115,1169 +1114,1206 @@ async function buildDeploymentSystemPrompt(platform, mode) {
1115
1114
  const pluginSystemPrompt = buildPluginSystemPromptContributions(await getPluginSystemPromptContributions(platform));
1116
1115
  return [buildSystemPrompt(platform, mode), pluginSystemPrompt].filter((section) => Boolean(section)).join("\n\n");
1117
1116
  }
1118
- /** Hash a system prompt, to compare prompts without storing their text. */
1119
- function systemPromptHash(systemPrompt) {
1120
- return createHash("sha256").update(systemPrompt).digest("hex").slice(0, 16);
1121
- }
1122
- // src/chat/conversations/sql/subtree.ts
1123
- /** Columns of the `conversation_subtree` table that `conversationSubtree` returns. */
1124
- const conversationSubtreeColumns = {
1125
- conversationId: sql`conversation_subtree.conversation_id`,
1126
- scopeConversationId: sql`conversation_subtree.scope_conversation_id`
1127
- };
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";
1128
1122
  /**
1129
- * Return a joinable `conversation_subtree` table. It maps each selected
1130
- * Conversation to itself and to each descendant child Conversation at any
1131
- * depth. Reports use it so that a total for a Conversation always includes the
1132
- * work of all its child agents.
1123
+ * Core catalog entry for Workspace snapshot ready and failed events.
1133
1124
  *
1134
- * A descendant must have the same root as the selected Conversation. Thus a
1135
- * 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.
1136
1128
  */
1137
- function conversationSubtree(conversationIds) {
1138
- const selectedIds = sql.join(conversationIds.map((conversationId) => sql`${conversationId}`), sql`, `);
1139
- return sql`(
1140
- with recursive tree(scope_conversation_id, conversation_id, root_conversation_id) as (
1141
- select selected.conversation_id, selected.conversation_id, selected.root_conversation_id
1142
- from junior_conversations selected
1143
- where selected.conversation_id in (${selectedIds})
1144
- union
1145
- select tree.scope_conversation_id, child.conversation_id, child.root_conversation_id
1146
- from junior_conversations child
1147
- join tree
1148
- on child.parent_conversation_id = tree.conversation_id
1149
- and (child.root_conversation_id || '') = tree.root_conversation_id
1150
- )
1151
- select scope_conversation_id, conversation_id from tree
1152
- ) conversation_subtree`;
1153
- }
1154
- // src/chat/services/automated-turn-limit.ts
1155
- const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
1156
- const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
1157
- const AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS = 2e3;
1158
- const AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS = 25;
1159
- /** Stored consecutive automated-turn count for one Conversation. */
1160
- const automatedTurnLimitStateSchema = z.object({
1161
- consecutiveAutomatedTurns: z.number().int().nonnegative(),
1162
- noticePostedAtMs: z.number().finite().nonnegative().optional(),
1163
- paused: z.boolean(),
1164
- updatedAtMs: z.number().finite().nonnegative()
1165
- }).strict();
1166
- function sleep(ms) {
1167
- return new Promise((resolve) => {
1168
- setTimeout(resolve, ms).unref?.();
1169
- });
1170
- }
1171
- function conversationKey(conversationId) {
1172
- return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
1173
- }
1174
- function lockKey(key) {
1175
- 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
+ };
1176
1148
  }
1177
- function parseState(value) {
1178
- const parsed = automatedTurnLimitStateSchema.safeParse(value);
1179
- 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
+ };
1180
1159
  }
1181
- async function acquireConversationLock(state, key, waitDeadlineMs = Date.now() + AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS) {
1182
- while (true) {
1183
- const lock = await state.acquireLock(lockKey(key), AUTOMATED_TURN_LIMIT_LOCK_TTL_MS);
1184
- if (lock) return lock;
1185
- if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire automated turn limit lock for ${key}`);
1186
- await sleep(AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS);
1187
- }
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;
1188
1180
  }
1189
- async function withConversationLock(state, key, callback) {
1190
- const lock = await acquireConversationLock(state, key);
1191
- try {
1192
- return await callback();
1193
- } finally {
1194
- 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."
1195
1212
  }
1196
- }
1197
- 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() {
1198
1219
  return {
1199
- consecutiveAutomatedTurns: 0,
1200
- paused: false,
1201
- 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
+ } }
1202
1238
  };
1203
1239
  }
1204
- /** True when this Source starts an automated Turn rather than a user Turn. */
1205
- function isAutomatedTurnSource(source) {
1206
- if (!source) return false;
1207
- return source.kind === "event" || source.kind === "event_automation" || source.kind === "scheduled_automation" || source.kind === "plugin_dispatch" || source.kind === "agent_invocation";
1208
- }
1209
- /** Plain notice when automatic updates stop until the user replies. */
1210
- function buildAutomatedTurnLimitResponse(args) {
1211
- 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.`;
1212
- }
1213
1240
  /**
1214
- * Allow one automated wake, or refuse once the consecutive-turn limit is full.
1215
- * If a prior pause never posted its notice, claim the notice slot so one caller
1216
- * 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.
1217
1245
  */
1218
- async function admitAutomatedTurn(args) {
1219
- if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
1220
- const state = args.state ?? getStateAdapter();
1221
- await state.connect();
1222
- const nowMs = args.nowMs ?? Date.now();
1223
- const key = conversationKey(args.conversationId);
1224
- return await withConversationLock(state, key, async () => {
1225
- const current = parseState(await state.get(key)) ?? emptyState(nowMs);
1226
- if (current.paused || current.consecutiveAutomatedTurns >= args.maxTurns) {
1227
- const shouldPostNotice = current.noticePostedAtMs === void 0;
1228
- const next = {
1229
- consecutiveAutomatedTurns: Math.max(current.consecutiveAutomatedTurns, args.maxTurns),
1230
- paused: true,
1231
- updatedAtMs: nowMs,
1232
- ...shouldPostNotice ? { noticePostedAtMs: nowMs } : current.noticePostedAtMs !== void 0 ? { noticePostedAtMs: current.noticePostedAtMs } : void 0
1233
- };
1234
- await state.set(key, next, JUNIOR_THREAD_STATE_TTL_MS);
1235
- return {
1236
- status: "paused",
1237
- consecutiveAutomatedTurns: next.consecutiveAutomatedTurns,
1238
- shouldPostNotice
1239
- };
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
1240
1254
  }
1241
- return {
1242
- status: "allow",
1243
- consecutiveAutomatedTurns: current.consecutiveAutomatedTurns
1244
- };
1245
- });
1246
- }
1247
- /** Count one finished automated Turn toward the consecutive-turn limit. */
1248
- async function countAutomatedTurn(args) {
1249
- if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
1250
- const state = args.state ?? getStateAdapter();
1251
- await state.connect();
1252
- const nowMs = args.nowMs ?? Date.now();
1253
- const key = conversationKey(args.conversationId);
1254
- return await withConversationLock(state, key, async () => {
1255
- const current = parseState(await state.get(key)) ?? emptyState(nowMs);
1256
- const consecutiveAutomatedTurns = current.consecutiveAutomatedTurns + 1;
1257
- const paused = consecutiveAutomatedTurns >= args.maxTurns;
1258
- const shouldPostNotice = paused && current.noticePostedAtMs === void 0;
1259
- const next = {
1260
- consecutiveAutomatedTurns,
1261
- paused,
1262
- updatedAtMs: nowMs,
1263
- ...shouldPostNotice ? { noticePostedAtMs: nowMs } : current.noticePostedAtMs !== void 0 ? { noticePostedAtMs: current.noticePostedAtMs } : void 0
1264
- };
1265
- await state.set(key, next, JUNIOR_THREAD_STATE_TTL_MS);
1266
- return {
1267
- consecutiveAutomatedTurns,
1268
- paused,
1269
- shouldPostNotice
1270
- };
1271
- });
1255
+ };
1272
1256
  }
1273
1257
  /**
1274
- * Drop a failed notice claim so a later paused wake can post the notice.
1275
- * 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.
1276
1264
  */
1277
- async function clearAutomatedTurnLimitNoticeClaim(args) {
1278
- const state = args.state ?? getStateAdapter();
1279
- await state.connect();
1280
- const nowMs = args.nowMs ?? Date.now();
1281
- const key = conversationKey(args.conversationId);
1282
- await withConversationLock(state, key, async () => {
1283
- const current = parseState(await state.get(key));
1284
- if (!current || current.noticePostedAtMs === void 0) return;
1285
- const { noticePostedAtMs: _noticePostedAtMs, ...rest } = current;
1286
- await state.set(key, {
1287
- ...rest,
1288
- updatedAtMs: nowMs
1289
- }, JUNIOR_THREAD_STATE_TTL_MS);
1290
- });
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
+ };
1291
1279
  }
1292
- /** Clear the consecutive automated-turn count after a user-owned Turn. */
1293
- async function resetAutomatedTurnLimit(args) {
1294
- const state = args.state ?? getStateAdapter();
1295
- await state.connect();
1296
- const key = conversationKey(args.conversationId);
1297
- await withConversationLock(state, key, async () => {
1298
- await state.delete(key);
1299
- });
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
+ };
1300
1310
  }
1301
1311
  /**
1302
- * Update consecutive automated-turn counts after one finished Turn.
1312
+ * Decide whether a channel-message Event may run one automation.
1303
1313
  *
1304
- * Automated Turns count on the Conversation. User Turns clear that count so
1305
- * 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.
1306
1321
  */
1307
- async function recordFinishedTurnForAutomatedLimit(args) {
1308
- const nowMs = args.nowMs ?? Date.now();
1309
- if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
1310
- conversationId: args.conversationId,
1311
- maxTurns: args.maxTurns,
1312
- nowMs,
1313
- state: args.state
1314
- });
1315
- await resetAutomatedTurnLimit({
1316
- conversationId: args.conversationId,
1317
- nowMs,
1318
- state: args.state
1319
- });
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;
1320
1328
  }
1321
- // src/chat/slack/automation-card.ts
1322
- function preview(text, length) {
1323
- const compact = text.replace(/\s+/g, " ").trim();
1324
- 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;
1325
1334
  }
1326
- /** Show an Automation as a native Work Object, not an operation receipt. */
1327
- function renderSlackAutomationCard(card) {
1328
- const title = preview(card.title, 160);
1329
- const iconUrl = getDashboardObjectIconLink("workflow");
1330
- const trigger = preview(card.trigger, 500);
1331
- const warning = card.warning ? preview(card.warning, 500) : null;
1332
- const text = [
1333
- "Automation",
1334
- card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
1335
- escapeSlackMrkdwnText(trigger),
1336
- warning ? escapeSlackMrkdwnText(warning) : null
1337
- ].filter(Boolean).join("\n");
1338
- if (!card.url) return {
1339
- entity: null,
1340
- text
1341
- };
1342
- return {
1343
- text,
1344
- entity: {
1345
- entity_type: "slack#/entities/item",
1346
- external_ref: {
1347
- id: card.id,
1348
- 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" }
1349
1356
  },
1350
- url: card.url,
1351
- entity_payload: {
1352
- attributes: {
1353
- title: { text: title },
1354
- display_type: "Automation",
1355
- product_icon: iconUrl ? {
1356
- url: iconUrl,
1357
- alt_text: "Automation"
1358
- } : void 0
1359
- },
1360
- custom_fields: [{
1361
- key: "trigger",
1362
- label: "When",
1363
- type: "string",
1364
- value: trigger,
1365
- long: true
1366
- }, ...warning ? [{
1367
- key: "warning",
1368
- label: "Needs attention",
1369
- type: "string",
1370
- value: warning,
1371
- long: true
1372
- }] : []]
1357
+ limits: {
1358
+ ...snapshot.limits,
1359
+ timer: {
1360
+ automation: false,
1361
+ watch: false,
1362
+ watchUnavailableMessage: "Use watchTimer to create a timer Watch."
1363
+ }
1373
1364
  }
1374
- }
1365
+ }),
1366
+ [SLACK_EVENT_NAMESPACE]: eventCatalogEntry({
1367
+ ...slackChannelMessageEvents(),
1368
+ displayName: "Slack"
1369
+ })
1375
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;
1376
1381
  }
1377
- // src/chat/slack/object-card.ts
1378
- function descriptionPreview(value) {
1379
- const text = value?.replace(/\r\n/g, "\n").trim() ?? "";
1380
- const preview = text.split("\n").slice(0, 6).join("\n").slice(0, 500);
1381
- 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);
1382
1397
  }
1383
- /** Render a compact Task or Item preview, or the saved facts for its detail panel. */
1384
- function renderSlackObjectCard(card, conversationId, surface = "preview") {
1385
- if (card.objectType === "automation" && card.plugin === "junior") return renderSlackAutomationCard({
1386
- id: card.key,
1387
- title: card.title,
1388
- url: card.url,
1389
- trigger: card.trigger ?? "",
1390
- warning: card.warning ?? null
1391
- });
1392
- const presentation = objectPresentation(card);
1393
- const type = card.displayType ?? presentation.label;
1394
- const iconUrl = getDashboardObjectIconLink(presentation.icon);
1395
- const title = card.title.slice(0, 160);
1396
- const details = surface === "details";
1397
- const deployment = card.objectType === "deployment" || card.objectType === "item" && card.facts?.type === "deployment";
1398
- const calendarEvent = card.objectType === "calendar_event";
1399
- const status = details || deployment || calendarEvent ? card.status : void 0;
1400
- const warning = details || deployment ? card.warning : void 0;
1401
- const facts = objectFactFields(card.facts).filter((field) => details || calendarEvent || deployment && field.key === "environment");
1402
- const description = details ? card.description?.trim() ?? "" : calendarEvent ? "" : descriptionPreview(card.description);
1403
- const text = [
1404
- escapeSlackMrkdwnText(type),
1405
- card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
1406
- escapeSlackMrkdwnText(card.label),
1407
- status ? escapeSlackMrkdwnText(status) : null,
1408
- description ? escapeSlackMrkdwnText(description) : null,
1409
- warning ? escapeSlackMrkdwnText(`Needs attention: ${warning}`) : null,
1410
- ...facts.map((field) => escapeSlackMrkdwnText(`${field.label}: ${field.value}`))
1411
- ].filter(Boolean).join("\n");
1412
- if (!card.url) return {
1413
- entity: null,
1414
- text
1415
- };
1416
- const task = card.objectType === "task";
1417
- const attributes = {
1418
- title: { text: title },
1419
- display_id: card.label,
1420
- display_type: type,
1421
- product_icon: iconUrl ? {
1422
- url: iconUrl,
1423
- alt_text: `${type}${status ? `: ${status}` : ""}`
1424
- } : void 0,
1425
- product_name: card.plugin
1426
- };
1427
- const customFields = [
1428
- ...description ? [{
1429
- key: "description",
1430
- label: "Description",
1431
- type: "string",
1432
- value: description,
1433
- long: true,
1434
- format: "markdown"
1435
- }] : [],
1436
- ...facts.map((field) => ({
1437
- ...field,
1438
- type: "string"
1439
- })),
1440
- ...warning ? [{
1441
- key: "warning",
1442
- label: "Needs attention",
1443
- type: "string",
1444
- value: warning
1445
- }] : []
1446
- ];
1447
- return {
1448
- text,
1449
- entity: {
1450
- ...task ? {
1451
- entity_type: "slack#/entities/task",
1452
- entity_payload: {
1453
- attributes,
1454
- display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
1455
- fields: status ? { status: { value: status } } : void 0,
1456
- custom_fields: customFields
1457
- }
1458
- } : {
1459
- entity_type: "slack#/entities/item",
1460
- entity_payload: {
1461
- attributes,
1462
- display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
1463
- custom_fields: [...status ? [{
1464
- key: "status",
1465
- label: "Status",
1466
- type: "string",
1467
- value: status
1468
- }] : [], ...customFields]
1469
- }
1470
- },
1471
- external_ref: {
1472
- id: Buffer.from(JSON.stringify([
1473
- conversationId,
1474
- card.plugin,
1475
- card.key
1476
- ]), "utf8").toString("base64url"),
1477
- type: "annotation"
1478
- },
1479
- url: card.url
1480
- }
1481
- };
1482
- }
1483
- // src/chat/slack/cards.ts
1484
- /** Select the Slack object renderer for a built-in card. */
1485
- function renderSlackCard(card, conversationId) {
1486
- switch (card.kind) {
1487
- case "object": return renderSlackObjectCard(card, conversationId);
1488
- 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;
1489
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;
1411
+ }
1412
+ configuredExperimental = next;
1413
+ return previous;
1490
1414
  }
1491
- // src/chat/slack/footer.ts
1492
- /** Render compact reply attribution for the Slack footer. */
1493
- function formatReplyAttribution(attribution) {
1494
- 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 };
1495
1418
  }
1419
+ /** Return whether one experimental feature is enabled via createApp({ experimental }). */
1420
+ function isExperimentalFeatureEnabled(feature) {
1421
+ return configuredExperimental[feature] === true;
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
+ };
1496
1429
  /**
1497
- * 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.
1498
1434
  *
1499
- * 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.
1500
1437
  */
1501
- function buildSlackReplyFooter(args) {
1502
- const items = [];
1503
- const conversationId = args.conversationId?.trim();
1504
- if (conversationId) {
1505
- const idItem = {
1506
- label: "ID",
1507
- value: conversationId
1508
- };
1509
- const conversationUrl = getPluginSlackConversationLink(conversationId)?.url ?? getDashboardConversationLink(conversationId) ?? buildSentryConversationUrl(conversationId);
1510
- if (conversationUrl) idItem.url = conversationUrl;
1511
- items.push(idItem);
1512
- }
1513
- return items.length > 0 || args.replyAttribution ? {
1514
- ...args.replyAttribution ? { attribution: args.replyAttribution } : void 0,
1515
- items
1516
- } : 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`;
1517
1454
  }
1518
- /** Build Slack blocks for a reply chunk using the Slack-flavored markdown block for the body. */
1519
- function buildSlackReplyBlocks(text, footer) {
1520
- const blocks = text.trim() ? [{
1521
- type: "markdown",
1522
- text
1523
- }] : [];
1524
- if (footer && (footer.attribution || footer.items.length > 0)) {
1525
- const attributionElements = footer.attribution ? [{
1526
- type: "plain_text",
1527
- text: formatReplyAttribution(footer.attribution)
1528
- }] : [];
1529
- blocks.push({
1530
- type: "context",
1531
- elements: [...attributionElements, ...footer.items.map((item) => ({
1532
- type: "mrkdwn",
1533
- text: item.url ? `*${escapeSlackMrkdwnText(item.label)}:* ${formatSlackLink(item.url, item.value)}` : `*${escapeSlackMrkdwnText(item.label)}:* ${escapeSlackMrkdwnText(item.value)}`
1534
- }))]
1535
- });
1536
- }
1537
- return blocks.length ? blocks : void 0;
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
+ });
1538
1471
  }
1539
- // src/chat/events/people.ts
1540
- const linkedSlackIdentity = alias(juniorIdentities, "event_people_slack");
1541
- function personKey(person) {
1542
- return "email" in person ? `email:${normalizeIdentityEmail(person.email)}` : `${person.provider}:${person.handle.toLowerCase()}`;
1472
+ function conversationKey(conversationId) {
1473
+ return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
1543
1474
  }
1544
- function personCondition(person) {
1545
- if ("email" in person) return and(eq(juniorIdentities.emailVerified, true), eq(juniorIdentities.emailNormalized, normalizeIdentityEmail(person.email)));
1546
- return and(eq(juniorIdentities.provider, person.provider), sql`lower(${juniorIdentities.handle}) = lower(${person.handle})`);
1475
+ function lockKey(key) {
1476
+ return `${key}:lock`;
1547
1477
  }
1548
- /**
1549
- * Read the Slack users in one workspace whose linked User has an identity that
1550
- * matches `condition`, by person key. A key with more than one Slack user is
1551
- * ambiguous, so callers must not mention it.
1552
- */
1553
- async function readLinkedSlackUsers(condition, slackTeamId) {
1554
- const rows = await getSqlExecutor().db().select({
1555
- emailNormalized: juniorIdentities.emailNormalized,
1556
- emailVerified: juniorIdentities.emailVerified,
1557
- handle: juniorIdentities.handle,
1558
- provider: juniorIdentities.provider,
1559
- slackUserId: linkedSlackIdentity.providerSubjectId
1560
- }).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));
1561
- const slackUsersByKey = /* @__PURE__ */ new Map();
1562
- const add = (key, slackUserId) => {
1563
- const users = slackUsersByKey.get(key) ?? /* @__PURE__ */ new Set();
1564
- users.add(slackUserId);
1565
- slackUsersByKey.set(key, users);
1566
- };
1567
- for (const row of rows) {
1568
- if (row.handle) add(`${row.provider}:${row.handle.toLowerCase()}`, row.slackUserId);
1569
- if (row.emailVerified && row.emailNormalized) add(`email:${row.emailNormalized}`, row.slackUserId);
1570
- }
1571
- return slackUsersByKey;
1478
+ function parseState(value) {
1479
+ const parsed = automatedTurnLimitStateSchema.safeParse(value);
1480
+ return parsed.success ? parsed.data : void 0;
1572
1481
  }
1573
- function soleMention(users) {
1574
- return users?.size === 1 ? slackMention([...users][0]) : void 0;
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);
1488
+ }
1575
1489
  }
1576
- const HANDLE_MENTION_PATTERN = /(?<![\w.@/-])@([A-Za-z0-9][A-Za-z0-9_.-]*[A-Za-z0-9]|[A-Za-z0-9])/g;
1577
- const MAX_REPLY_HANDLES = 50;
1578
- /**
1579
- * Resolve the `@handle` words in reply text to Slack mentions of known people
1580
- * in one Slack workspace, by `provider:handle` key in lowercase. A handle
1581
- * resolves only when exactly one linked Slack user has it for that provider.
1582
- * Plugins pick the provider when they format the reply.
1583
- */
1584
- async function resolveHandleMentions(text, slackTeamId) {
1585
- const handles = [...new Set([...text.matchAll(HANDLE_MENTION_PATTERN)].map((match) => match[1].toLowerCase()))].slice(0, MAX_REPLY_HANDLES);
1586
- if (handles.length === 0) return /* @__PURE__ */ new Map();
1587
- const slackUsersByKey = await readLinkedSlackUsers(inArray(sql`lower(${juniorIdentities.handle})`, handles), slackTeamId);
1588
- const mentions = /* @__PURE__ */ new Map();
1589
- for (const [key, users] of slackUsersByKey) {
1590
- const mention = soleMention(users);
1591
- if (mention && !key.startsWith("email:")) mentions.set(key, mention);
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);
1592
1496
  }
1593
- return mentions;
1594
1497
  }
1595
- /**
1596
- * Resolve the Event people and the Event doer to Slack mentions through
1597
- * linked user identities in one Slack workspace, with one query.
1598
- *
1599
- * A person resolves only when exactly one linked Slack user in that workspace
1600
- * matches. Core drops unlinked and ambiguous people, so a provider value never
1601
- * guesses a mention.
1602
- */
1603
- async function resolveEventMentions(event, slackTeamId) {
1604
- const people = event.people ?? [];
1605
- const lookup = event.doneBy ? [...people, event.doneBy] : people;
1606
- if (lookup.length === 0) return { people: [] };
1607
- const slackUsersByKey = await readLinkedSlackUsers(or(...lookup.map(personCondition)), slackTeamId);
1608
- const mentionOf = (person) => soleMention(slackUsersByKey.get(personKey(person)));
1609
- const mentions = [];
1610
- for (const person of people) {
1611
- const mention = mentionOf(person);
1612
- if (mention && !mentions.includes(mention)) mentions.push(mention);
1613
- }
1614
- const doneByMention = event.doneBy ? mentionOf(event.doneBy) : void 0;
1615
- if (!doneByMention || !event.doneBy) return { people: mentions };
1616
- return {
1617
- people: mentions,
1618
- doneBy: {
1619
- mention: doneByMention,
1620
- ..."handle" in event.doneBy ? { handle: event.doneBy.handle } : void 0
1621
- }
1622
- };
1623
- }
1624
- // src/chat/slack/output.ts
1625
- const MAX_INLINE_CHARS = 4e3;
1626
- function getFenceContinuation(text) {
1627
- let open;
1628
- for (const line of text.split("\n")) {
1629
- const trimmed = line.trimStart();
1630
- const openerMatch = trimmed.match(/^(`{3,}|~{3,})(.*)$/);
1631
- if (!openerMatch?.[1]) continue;
1632
- if (!open) {
1633
- open = {
1634
- fence: openerMatch[1],
1635
- openerLine: trimmed
1636
- };
1637
- continue;
1638
- }
1639
- if (new RegExp(`^${open.fence}\\s*$`).test(trimmed)) open = void 0;
1640
- }
1641
- if (!open) return null;
1498
+ function emptyState(nowMs) {
1642
1499
  return {
1643
- closeSuffix: text.endsWith("\n") ? open.fence : `\n${open.fence}`,
1644
- reopenPrefix: `${open.openerLine}\n`
1500
+ consecutiveAutomatedTurns: 0,
1501
+ paused: false,
1502
+ updatedAtMs: nowMs
1645
1503
  };
1646
1504
  }
1647
- function findSplitIndex(text, maxChars) {
1648
- const bounded = text.slice(0, maxChars);
1649
- const newlineIndex = bounded.lastIndexOf("\n");
1650
- if (newlineIndex > 0) return newlineIndex;
1651
- const spaceIndex = bounded.lastIndexOf(" ");
1652
- if (spaceIndex > 0) return spaceIndex;
1653
- 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";
1654
1509
  }
1655
- function takePrefix(text, maxChars) {
1656
- const prefix = text.slice(0, findSplitIndex(text, maxChars)).trimEnd() || text.slice(0, maxChars);
1657
- return {
1658
- prefix,
1659
- rest: text.slice(prefix.length).trimStart()
1660
- };
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.`;
1661
1513
  }
1662
- /** Take one post that fits the budget, closing a code fence it leaves open. */
1663
- function takeChunk(text) {
1664
- let { prefix, rest } = takePrefix(text, MAX_INLINE_CHARS);
1665
- let carryover = getFenceContinuation(prefix);
1666
- if (!carryover) return {
1667
- chunk: prefix,
1668
- rest
1669
- };
1670
- ({prefix, rest} = takePrefix(text, MAX_INLINE_CHARS - carryover.closeSuffix.length));
1671
- carryover = getFenceContinuation(prefix);
1672
- if (!carryover || !rest) return {
1673
- chunk: prefix,
1674
- rest
1675
- };
1676
- return {
1677
- chunk: `${prefix}${carryover.closeSuffix}`,
1678
- rest: `${carryover.reopenPrefix}${rest}`
1679
- };
1514
+ /**
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.
1518
+ */
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
+ });
1680
1547
  }
1681
- /** Split a normalized Slack reply into thread posts that fit Slack limits. */
1682
- function splitSlackReplyText(text, format) {
1683
- const chunks = [];
1684
- let remaining = normalizeSlackReplyMarkdown(text, format);
1685
- while (remaining.length > MAX_INLINE_CHARS) {
1686
- const { chunk, rest } = takeChunk(remaining);
1687
- chunks.push(chunk);
1688
- remaining = rest;
1689
- }
1690
- if (remaining) chunks.push(remaining);
1691
- return chunks;
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
+ });
1692
1573
  }
1693
- // src/chat/slack/reply.ts
1694
1574
  /**
1695
- * Resolve where a Turn posts in Slack.
1696
- *
1697
- * The channel is always the Destination channel. The thread comes from the
1698
- * Turn Source, then the Conversation Location, then the Destination, and each
1699
- * one counts only when it names that channel. Do not derive the target from
1700
- * the Conversation id: an Automation or Watch Conversation can own a Slack
1701
- * thread, and its id is not a Slack thread id.
1575
+ * Drop a failed notice claim so a later paused wake can post the notice.
1576
+ * Keeps the pause and consecutive count.
1702
1577
  */
1703
- function resolveSlackReplyTarget(args) {
1704
- const { channelId } = args.destination;
1705
- const sourceThreadTs = args.source?.kind === "slack" && args.source.channelId === channelId ? args.source.threadTs : void 0;
1706
- const locationThreadTs = args.location?.provider === "slack" && args.location.channelId === channelId ? args.location.threadTs : void 0;
1707
- const threadTs = sourceThreadTs ?? locationThreadTs ?? args.destination.threadTs;
1708
- return {
1709
- channelId,
1710
- ...threadTs ? { threadTs } : void 0
1711
- };
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
+ });
1712
1592
  }
1713
- /** Resolve known people for plugin formatting. Fails open, like the hooks. */
1714
- async function resolveReplyMentions(text, teamId) {
1715
- try {
1716
- return await resolveHandleMentions(text, teamId);
1717
- } catch (error) {
1718
- logWarn("slack.reply.mentions.failed", { "exception.message": error instanceof Error ? error.message : String(error) });
1719
- return;
1720
- }
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);
1600
+ });
1721
1601
  }
1722
1602
  /**
1723
- * Send one destination-visible Slack reply.
1603
+ * Update consecutive automated-turn counts after one finished Turn.
1724
1604
  *
1725
- * Chunks oversized text, builds compact attribution and conversation footer
1726
- * context, and posts through the shared Slack outbound boundary. Pass
1727
- * `formatting` for agent replies so plugin formatting can use Location
1728
- * defaults, such as a default repository, and mention known people.
1605
+ * Automated Turns count on the Conversation. User Turns clear that count so
1606
+ * later event wakes can run again.
1729
1607
  */
1730
- async function sendSlackReply(args) {
1731
- const format = args.formatting && {
1732
- configuration: args.formatting.configuration,
1733
- mentions: await resolveReplyMentions(args.text, args.formatting.teamId)
1734
- };
1735
- const posts = splitSlackReplyText(args.text, format).map((text) => ({
1736
- text,
1737
- cards: []
1738
- }));
1739
- const cards = (args.cards ?? []).map((card) => renderSlackCard(card, args.conversationId));
1740
- for (let index = 0; index < cards.length; index += 5) {
1741
- const group = cards.slice(index, index + 5);
1742
- const lastPost = posts.at(-1);
1743
- if (index === 0 && lastPost) lastPost.cards = group;
1744
- else posts.push({
1745
- text: "",
1746
- cards: group
1747
- });
1748
- }
1749
- const footer = buildSlackReplyFooter({
1608
+ async function recordFinishedTurnForAutomatedLimit(args) {
1609
+ const nowMs = args.nowMs ?? Date.now();
1610
+ if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
1750
1611
  conversationId: args.conversationId,
1751
- replyAttribution: args.replyAttribution
1612
+ maxTurns: args.maxTurns,
1613
+ nowMs,
1614
+ state: args.state
1615
+ });
1616
+ await resetAutomatedTurnLimit({
1617
+ conversationId: args.conversationId,
1618
+ nowMs,
1619
+ state: args.state
1752
1620
  });
1753
- const messageTs = [];
1754
- let threadTs = args.threadTs;
1755
- for (const [index, post] of posts.entries()) {
1756
- const { text, cards } = post;
1757
- const isFinalChunk = index === posts.length - 1;
1758
- const blocks = buildSlackReplyBlocks(text, void 0) ?? [];
1759
- for (const card of cards) if (!card.entity) blocks.push({
1760
- type: "section",
1761
- text: {
1762
- type: "mrkdwn",
1763
- text: card.text
1764
- }
1765
- });
1766
- if (isFinalChunk || !text.trim()) blocks.push(...buildSlackReplyBlocks("", footer) ?? []);
1767
- const entities = cards.flatMap((card) => card.entity ? [card.entity] : []);
1768
- const accessibleText = [text, ...cards.map((card) => card.text)].filter(Boolean).join("\n\n");
1769
- const fallbackText = isFinalChunk && args.replyAttribution ? `${accessibleText}\n\n${escapeSlackMrkdwnText(formatReplyAttribution(args.replyAttribution))}` : accessibleText;
1770
- const response = await postSlackMessage({
1771
- channelId: args.channelId,
1772
- threadTs,
1773
- text: fallbackText,
1774
- ...blocks.length ? { blocks } : void 0,
1775
- ...entities.length ? { entities } : void 0
1776
- });
1777
- if (response.ts) {
1778
- messageTs.push(response.ts);
1779
- threadTs ??= response.ts;
1780
- }
1781
- }
1782
- return messageTs;
1783
1621
  }
1784
- // src/chat/slack/automated-turn-limit-notice.ts
1785
- /**
1786
- * Pause notice for the consecutive automated-turn limit.
1787
- *
1788
- * Best-effort: a failed post must not fail the Turn or re-enable event wakes.
1789
- * The consecutive-turn limit claims the notice slot before this post. Clear that
1790
- * claim when the post fails or is skipped so a later paused wake can try again.
1791
- */
1792
- async function releaseFailedNoticeClaim(args) {
1793
- try {
1794
- await clearAutomatedTurnLimitNoticeClaim(args);
1795
- } catch (error) {
1796
- logException(error, "automated_turn_limit.notice_claim_clear_failed");
1797
- }
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;
1798
1626
  }
1799
- /** Post the pause notice for one Conversation Location when known. */
1800
- async function postAutomatedTurnLimitNoticeForConversation(args) {
1801
- try {
1802
- const conversation = await getConversationStore().get({ conversationId: args.conversationId });
1803
- const location = conversation?.parentConversationId ? void 0 : conversation?.location;
1804
- if (!location || location.provider !== "slack") {
1805
- logWarn("automated_turn_limit.notice_skipped", {
1806
- conversationId: args.conversationId,
1807
- "app.automated_turn_limit.reason": location ? "unsupported_location" : "missing_location"
1808
- });
1809
- await releaseFailedNoticeClaim({
1810
- conversationId: args.conversationId,
1811
- nowMs: args.nowMs
1812
- });
1813
- return false;
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
+ }
1814
1675
  }
1815
- await sendSlackReply({
1816
- ...resolveSlackReplyTarget({
1817
- destination: location,
1818
- location,
1819
- source: args.source
1820
- }),
1821
- conversationId: args.conversationId,
1822
- text: buildAutomatedTurnLimitResponse({ maxTurns: args.maxTurns })
1823
- });
1824
- return true;
1825
- } catch (error) {
1826
- logException(error, "automated_turn_limit.notice_failed", { conversationId: args.conversationId });
1827
- await releaseFailedNoticeClaim({
1828
- conversationId: args.conversationId,
1829
- nowMs: args.nowMs
1830
- });
1831
- return false;
1832
- }
1676
+ };
1833
1677
  }
1834
- /** Post the pause notice after a finished Turn hits the limit. */
1835
- async function maybePostAutomatedTurnLimitNotice(args) {
1836
- if (!args.update?.shouldPostNotice) return;
1837
- await postAutomatedTurnLimitNoticeForConversation({
1838
- conversationId: args.conversationId,
1839
- maxTurns: args.maxTurns,
1840
- nowMs: args.nowMs,
1841
- source: args.source
1842
- });
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;
1843
1683
  }
1844
- // src/chat/task-input.ts
1845
- /**
1846
- * Shared agent input for tasks: one `<task>` input tag. A task can come from
1847
- * a schedule, an event, or a watch. Call sites supply facts; this module owns
1848
- * layout and the reply contract. Unit snapshots in
1849
- * `tests/unit/chat/task-input.test.ts` own the exact text. Event data stays in
1850
- * its own child tags, and the outcome rule is always last.
1851
- */
1852
- /**
1853
- * Shared closing lines. Automations pass outcomes and end with an answer
1854
- * tool. Watches follow the Conversation's reply rules. A Watch reply goes
1855
- * only to the Conversation, so a question asked in the provider must also get
1856
- * its answer there. Watch instructions often say to stay silent, so this rule
1857
- * sits in the contract, not in plugin guidance.
1858
- */
1859
- function replyContractLines(outcomes) {
1860
- if (!outcomes) return [
1861
- "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.",
1862
- "When you reply, follow any reply format in the instructions.",
1863
- `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.`
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
1692
+ });
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
+ }] : []
1864
1747
  ];
1865
- return [`End with \`${REPLY_TOOL_NAME}\`, \`${NO_REPLY_TOOL_NAME}\`, or \`${REPORT_BLOCKED_TOOL_NAME}\`.`];
1866
- }
1867
- function oneLine(value) {
1868
- return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
1869
- }
1870
- function clip(value, maxLength) {
1871
- return maxLength === void 0 ? value : value.slice(0, maxLength);
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
+ };
1872
1783
  }
1873
- const CREATOR_REFERENCE = /\bthe Automation creator\b/gi;
1874
- /**
1875
- * Write the creator mention where the instructions say "the Automation
1876
- * creator", so the run does not have to swap it in.
1877
- */
1878
- function mentionCreator(instructions, creator) {
1879
- return instructions.replace(CREATOR_REFERENCE, () => creator);
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);
1790
+ }
1880
1791
  }
1881
- function quoted(values) {
1882
- return values.map((value) => `"${value}"`).join(" or ");
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;
1883
1796
  }
1884
1797
  /**
1885
- * Render each linked person once. A doer in `<people>` gets a note in that
1886
- * list. Other doers get a `<done-by>` tag. Without one entry per person, the
1887
- * agent can mention a person and then name them again by handle as if they
1888
- * were someone else. The "you" rule covers doers outside `<people>` too,
1889
- * because instructions can still ask to mention them, such as a requester who
1890
- * reviews their own pull request. A child agent replies to its parent, not to
1891
- * the person, so it writes the mention instead of the handle. That carries
1892
- * who the person is up each level to the agent that replies to them.
1798
+ * Build the compact conversation footer for visible Slack reply surfaces.
1799
+ *
1800
+ * Detailed turn metrics stay in the dashboard instead of Slack-visible copy.
1893
1801
  */
1894
- function peopleTags(people, doers) {
1895
- const label = (doer) => `${doer.mention} (${[doer.did, ...doer.handles.length > 0 ? [`called ${quoted(doer.handles)} in the Event data`] : []].join("; ")})`;
1896
- const doerByMention = new Map(doers.map((doer) => [doer.mention, doer]));
1897
- const involved = people.map((person) => {
1898
- const doer = doerByMention.get(person);
1899
- return doer ? label(doer) : person;
1900
- });
1901
- return [
1902
- ...involved.length > 0 ? [renderChildTag("people", escapeClosingTags(involved.join(", ")))] : [],
1903
- ...doers.filter((doer) => !people.includes(doer.mention)).map((doer) => renderChildTag("done-by", escapeClosingTags(label(doer)))),
1904
- ...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)}.` : ""}`))
1905
- ];
1906
- }
1907
- /** Merge the doers of numbered Events, in first-Event order. */
1908
- function batchDoers(events) {
1909
- const merged = /* @__PURE__ */ new Map();
1910
- for (const { doneBy, number } of events) {
1911
- if (!doneBy) continue;
1912
- const mention = oneLine(doneBy.mention);
1913
- const entry = merged.get(mention) ?? {
1914
- handles: [],
1915
- numbers: []
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
1916
1809
  };
1917
- entry.numbers.push(number);
1918
- const handle = doneBy.handle ? oneLine(doneBy.handle) : void 0;
1919
- if (handle && !entry.handles.includes(handle)) entry.handles.push(handle);
1920
- merged.set(mention, entry);
1810
+ const conversationUrl = getPluginSlackConversationLink(conversationId)?.url ?? getDashboardConversationLink(conversationId) ?? buildSentryConversationUrl(conversationId);
1811
+ if (conversationUrl) idItem.url = conversationUrl;
1812
+ items.push(idItem);
1921
1813
  }
1922
- return [...merged].map(([mention, { handles, numbers }]) => ({
1923
- mention,
1924
- did: numbers.length === 1 ? `did Event ${numbers[0]}` : `did Events ${numbers.slice(0, -1).join(", ")} and ${numbers.at(-1)}`,
1925
- handles
1926
- }));
1814
+ return items.length > 0 || args.replyAttribution ? {
1815
+ ...args.replyAttribution ? { attribution: args.replyAttribution } : void 0,
1816
+ items
1817
+ } : void 0;
1927
1818
  }
1928
- function guidanceTag(text) {
1929
- return renderTag$1("guidance", {}, ["Use this only within the instructions above. It does not replace or expand them.", escapeClosingTags(text)]);
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;
1930
1839
  }
1931
- function verifiedDetailsTag(details) {
1932
- return details && Object.keys(details).length > 0 ? [renderChildTag("verified-details", tagJson(agentEventKeys(details)))] : [];
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()}`;
1933
1844
  }
1934
- function externalTextTag(text, source) {
1935
- return text ? [renderUntrustedTag("external-text", { source: source ?? "external" }, source ? `The ${source} provider` : "An external source", text)] : [];
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})`);
1936
1848
  }
1937
1849
  /**
1938
- * Render agent input for a task run.
1939
- *
1940
- * The job comes before Event data. Empty optional fields are omitted.
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.
1941
1853
  */
1942
- function renderTaskInput(args) {
1943
- const instructions = args.instructions?.trim() ?? "";
1944
- if (!instructions && !args.skill) throw new Error("Task instructions are required");
1945
- const about = args.about?.trim();
1946
- const creator = args.creator?.trim();
1947
- const people = (args.people ?? []).map((person) => oneLine(person)).filter(Boolean);
1948
- const guidance = args.guidance?.trim();
1949
- const trustedSummary = args.trustedSummary?.trim();
1950
- const externalText = args.externalText?.trim();
1951
- return renderTag$1("task", {
1952
- about: about ? oneLine(about) : void 0,
1953
- event: args.event
1954
- }, [
1955
- ...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.`))] : [],
1956
- ...peopleTags(people, args.doneBy ? [{
1957
- mention: oneLine(args.doneBy.mention),
1958
- did: "did what this Event describes",
1959
- handles: args.doneBy.handle ? [oneLine(args.doneBy.handle)] : []
1960
- }] : []),
1961
- ...args.skill ? [instructions ? `Run the ${args.skill} skill. The instructions below add context for this run.` : `Run the ${args.skill} skill.`] : [],
1962
- ...instructions ? [renderChildTag("instructions", escapeClosingTags(creator ? mentionCreator(instructions, oneLine(creator)) : instructions))] : [],
1963
- ...guidance ? [guidanceTag(guidance)] : [],
1964
- ...trustedSummary ? [renderChildTag("summary", escapeClosingTags(clip(trustedSummary, args.trustedSummaryMaxLength)))] : [],
1965
- ...verifiedDetailsTag(args.verifiedDetails),
1966
- ...externalTextTag(externalText && clip(externalText, args.externalTextMaxLength), args.source),
1967
- ...replyContractLines(args.outcomes)
1968
- ]);
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);
1871
+ }
1872
+ return slackUsersByKey;
1969
1873
  }
1970
- function eventTag(event, index) {
1971
- const trustedSummary = event.trustedSummary?.trim();
1972
- return renderTag$1("event", {
1973
- index,
1974
- type: event.eventType
1975
- }, [
1976
- ...trustedSummary ? [renderChildTag("summary", escapeClosingTags(trustedSummary))] : [],
1977
- ...verifiedDetailsTag(event.verifiedDetails),
1978
- ...externalTextTag(event.externalText?.trim(), event.source)
1979
- ]);
1874
+ function soleMention(users) {
1875
+ return users?.size === 1 ? slackMention([...users][0]) : void 0;
1980
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;
1981
1879
  /**
1982
- * Render one `<task>` for several Watch Events that arrived together.
1983
- *
1984
- * Each `<watch>` group states its instructions once, then lists its Events.
1985
- * Child tags match `renderTaskInput`. The outcome rule appears once, at the
1986
- * end.
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.
1987
1884
  */
1988
- function renderTaskBatchInput(args) {
1989
- const total = args.groups.reduce((count, group) => count + group.events.length, 0);
1990
- if (total === 0) throw new Error("Task batch requires at least one Event");
1991
- const body = [`You received ${total} ${total === 1 ? "event" : "events"}.`];
1992
- let number = 0;
1993
- for (const group of args.groups) {
1994
- const instructions = group.instructions.trim();
1995
- if (!instructions) throw new Error("Task instructions are required");
1996
- const about = group.about?.trim();
1997
- const people = group.people.map((person) => oneLine(person)).filter(Boolean);
1998
- const numbered = group.events.map((event, index) => ({
1999
- ...event,
2000
- number: number + index + 1
2001
- }));
2002
- number += group.events.length;
2003
- const guidance = /* @__PURE__ */ new Map();
2004
- for (const event of group.events) {
2005
- const text = event.guidance?.trim();
2006
- if (text && !guidance.has(event.eventType)) guidance.set(event.eventType, text);
2007
- }
2008
- body.push(renderTag$1("watch", { about: about ? oneLine(about) : void 0 }, [
2009
- ...peopleTags(people, batchDoers(numbered)),
2010
- renderChildTag("instructions", escapeClosingTags(instructions)),
2011
- ...guidance.size > 0 ? [guidanceTag([...guidance].map(([eventType, text]) => `- ${eventType}: ${text}`).join("\n"))] : [],
2012
- ...numbered.map((event) => eventTag(event, event.number))
2013
- ]));
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);
2014
1893
  }
2015
- return renderTag$1("task", {}, [...body, ...replyContractLines(void 0)]);
1894
+ return mentions;
2016
1895
  }
2017
- // src/chat/sandbox/snapshot/events.ts
2018
- const WORKSPACE_SNAPSHOT_NAMESPACE = CORE_EVENT_NAMESPACE;
2019
- const WORKSPACE_SNAPSHOT_RESOURCE_TYPE = "workspace_snapshot";
2020
- const WORKSPACE_SNAPSHOT_READY_EVENT = "workspace_snapshot.ready";
2021
- const WORKSPACE_SNAPSHOT_FAILED_EVENT = "workspace_snapshot.failed";
2022
1896
  /**
2023
- * 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.
2024
1899
  *
2025
- * Uses the same registration shape as plugins so search, guidance, and tool
2026
- * schemas treat these events like any other resource type. Snapshot finish
2027
- * does not run event-automation ingest, so only watches can use these events.
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.
2028
1903
  */
2029
- function workspaceSnapshotEvents() {
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 };
2030
1917
  return {
2031
- resourceTypes: [{
2032
- type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE,
2033
- supportedEvents: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
2034
- suggestedEvents: []
2035
- }],
2036
- events: {
2037
- [WORKSPACE_SNAPSHOT_READY_EVENT]: {
2038
- reach: "resource",
2039
- guidance: "Call switchWorkspace again with the same Workspace name. Do not create another watch when switchWorkspace already returned a subscription."
2040
- },
2041
- [WORKSPACE_SNAPSHOT_FAILED_EVENT]: {
2042
- reach: "resource",
2043
- guidance: "Report the snapshot failure. Do not keep waiting for this Workspace unless the user asks to retry."
2044
- }
2045
- },
2046
- 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
+ }
2047
1923
  };
2048
1924
  }
2049
- /** Describe the events that report when a snapshot build ends. */
2050
- 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;
2051
1943
  return {
2052
- identifier: input.workspaceId,
2053
- label: `Workspace ${input.workspaceName} snapshot`,
2054
- namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
2055
- supported_events: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
2056
- suggested_events: [],
2057
- type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE
1944
+ closeSuffix: text.endsWith("\n") ? open.fence : `\n${open.fence}`,
1945
+ reopenPrefix: `${open.openerLine}\n`
2058
1946
  };
2059
1947
  }
2060
- /** Report that a Workspace snapshot build is ready or failed. */
2061
- function workspaceSnapshotFinishedEvent(input) {
2062
- const occurredAtMs = input.occurredAtMs ?? Date.now();
2063
- const eventType = input.status === "ready" ? WORKSPACE_SNAPSHOT_READY_EVENT : WORKSPACE_SNAPSHOT_FAILED_EVENT;
2064
- const trustedSummary = input.status === "ready" ? "Workspace snapshot is ready." : "Workspace snapshot build failed.";
2065
- const event = {
2066
- eventKey: `${WORKSPACE_SNAPSHOT_NAMESPACE}:${input.workspaceId}:${input.resultId}:${input.status}`,
2067
- eventType,
2068
- identifier: input.workspaceId,
2069
- namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
2070
- occurredAtMs,
2071
- terminal: true,
2072
- trustedSummary,
2073
- data: {
2074
- workspaceId: input.workspaceId,
2075
- status: input.status
2076
- }
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()
2077
1961
  };
2078
- if (input.status === "failed" && input.error) event.untrustedText = input.error;
2079
- return event;
2080
1962
  }
2081
- // src/chat/slack/channel-message-events.ts
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}`
1980
+ };
1981
+ }
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;
1990
+ }
1991
+ if (remaining) chunks.push(remaining);
1992
+ return chunks;
1993
+ }
1994
+ // src/chat/slack/reply.ts
2082
1995
  /**
2083
- * Slack channel-message Events for Event automations.
1996
+ * Resolve where a Turn posts in Slack.
2084
1997
  *
2085
- * Core publishes these Events from Slack ingress, so the `slack` namespace is
2086
- * core owned, like `junior`. Anyone in the channel writes the Event text, so an
2087
- * automation can watch only its own channel and always uses system credentials.
2088
- */
2089
- /** Core-owned event namespace for Slack Events. Not a plugin publisher. */
2090
- const SLACK_EVENT_NAMESPACE = "slack";
2091
- /** The trigger identifier that names the channel of the automation. */
2092
- const SLACK_CURRENT_CHANNEL_IDENTIFIER = "current_channel";
2093
- const CHANNEL_RESOURCE_TYPE = "channel";
2094
- const MESSAGE_POSTED_EVENT = "message.posted";
2095
- const CHANNEL_ID_PATTERN = /^[CG][A-Z0-9]{2,}$/;
2096
- const CHANNEL_LOCATION = "channel";
2097
- const THREAD_LOCATION = "thread";
2098
- const CHANNEL_MESSAGE_MATCH_FIELDS = eventMatchFieldsSchema.parse({
2099
- channelId: {
2100
- kind: "string",
2101
- description: "Slack channel ID of the message. It is always the channel where the automation posts.",
2102
- events: [MESSAGE_POSTED_EVENT]
2103
- },
2104
- userId: {
2105
- kind: "string",
2106
- 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."
2107
- },
2108
- location: {
2109
- kind: "string",
2110
- enum: [CHANNEL_LOCATION, THREAD_LOCATION],
2111
- 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."
2112
- }
2113
- });
2114
- /**
2115
- * Event registration for new Slack channel messages and thread replies. Only
2116
- * event automations can use it, so watchEvents rejects it.
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.
2117
2003
  */
2118
- 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;
2119
2009
  return {
2120
- resourceTypes: [{
2121
- type: CHANNEL_RESOURCE_TYPE,
2122
- identifier: {
2123
- format: `"${SLACK_CURRENT_CHANNEL_IDENTIFIER}" for the channel where the automation is created`,
2124
- pattern: String.raw`^(?:current_channel|[CG][A-Z0-9]{2,})$`
2125
- },
2126
- supportedEvents: [MESSAGE_POSTED_EVENT],
2127
- suggestedEvents: [],
2128
- matchFields: CHANNEL_MESSAGE_MATCH_FIELDS
2129
- }],
2130
- events: { [MESSAGE_POSTED_EVENT]: {
2131
- reach: { anyOf: ["channelId"] },
2132
- 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."
2133
- } },
2134
- limits: { [CHANNEL_RESOURCE_TYPE]: {
2135
- watch: false,
2136
- watchUnavailableMessage: "Slack channel messages can trigger only an event automation in that channel. Use createAutomation with an event trigger."
2137
- } }
2010
+ channelId,
2011
+ ...threadTs ? { threadTs } : void 0
2138
2012
  };
2139
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
+ }
2140
2023
  /**
2141
- * Set the `channelId` filter of a Slack channel-message trigger to the
2142
- * channel where the automation posts. A trigger that names another channel,
2143
- * or a saved trigger with an identifier, stays as it is for
2144
- * `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.
2145
2030
  */
2146
- function slackChannelMessageTrigger(trigger, channelId) {
2147
- if (trigger.namespace !== "slack") return trigger;
2148
- if (trigger.identifier != null || trigger.match?.channelId !== void 0) return trigger;
2149
- return {
2150
- ...trigger,
2151
- match: {
2152
- ...trigger.match,
2153
- channelId
2154
- }
2031
+ async function sendSlackReply(args) {
2032
+ const format = args.formatting && {
2033
+ configuration: args.formatting.configuration,
2034
+ mentions: await resolveReplyMentions(args.text, args.formatting.teamId)
2155
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;
2156
2084
  }
2085
+ // src/chat/slack/automated-turn-limit-notice.ts
2157
2086
  /**
2158
- * Bind a Slack channel-message automation to its own channel.
2087
+ * Pause notice for the consecutive automated-turn limit.
2159
2088
  *
2160
- * The trigger names the channel with a `channelId` filter. A saved trigger
2161
- * can name it with an identifier instead, where `current_channel` means the
2162
- * destination channel. Reject other channels, so private channel text cannot
2163
- * 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.
2164
2092
  */
2165
- function requireSlackChannelMessageScope(automation) {
2166
- if (automation.trigger.namespace !== "slack") return automation;
2167
- const channelId = automation.destination.channelId;
2168
- if (!CHANNEL_ID_PATTERN.test(channelId)) throw new ToolInputError("A Slack channel-message automation works only in a channel, not in a DM.");
2169
- const { identifier, match } = automation.trigger;
2170
- 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.");
2171
- return {
2172
- ...automation,
2173
- credentialMode: "system",
2174
- trigger: {
2175
- ...automation.trigger,
2176
- ...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;
2177
2115
  }
2178
- };
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 ");
2179
2184
  }
2180
2185
  /**
2181
- * Build the Event for one new channel message or thread reply, or nothing.
2182
- *
2183
- * Slackbot posts do not count. Bot posts are marked with `postedByBot`, so
2184
- * only automations that name the bot can run on them. Thread replies carry
2185
- * 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.
2186
2194
  */
2187
- function slackChannelMessageEvent(input) {
2188
- const { author } = input;
2189
- if (author.kind === "user" && author.userId === "USLACKBOT") return void 0;
2190
- if (!CHANNEL_ID_PATTERN.test(input.channelId)) return void 0;
2191
- const postedByBot = author.kind === "bot" || Boolean(input.botId || input.subtype === "bot_message");
2192
- const userId = author.kind === "bot" ? author.botId : author.userId;
2193
- const threadTs = input.threadTs && input.threadTs !== input.ts ? input.threadTs : void 0;
2194
- return {
2195
- eventKey: `${input.channelId}:${input.ts}`,
2196
- eventType: MESSAGE_POSTED_EVENT,
2197
- identifier: input.channelId,
2198
- occurredAtMs: Math.floor(Number(input.ts) * 1e3),
2199
- trustedSummary: `${postedByBot ? "The bot " : ""}${author.kind === "bot" ? author.botId : `<@${author.userId}>`} posted a new ${threadTs ? `thread reply under message ${threadTs}` : "message"} in <#${input.channelId}>.`,
2200
- data: {
2201
- channelId: input.channelId,
2202
- location: threadTs ? THREAD_LOCATION : CHANNEL_LOCATION,
2203
- messageTs: input.ts,
2204
- ...threadTs ? { threadTs } : void 0,
2205
- userId,
2206
- ...postedByBot ? { postedByBot: true } : void 0
2207
- },
2208
- ...input.text?.trim() ? { untrustedText: input.text } : void 0
2209
- };
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)] : [];
2210
2237
  }
2211
2238
  /**
2212
- * Decide whether a channel-message Event may run one automation.
2239
+ * Render agent input for a task run.
2213
2240
  *
2214
- * A message runs only automations that post in its own channel, so private
2215
- * channel text cannot reach another channel. The trigger already names that
2216
- * channel, and this check keeps the rule when it does not.
2217
- * A bot post runs only automations whose match names its author in `userId`.
2218
- * Bots can post often and would use up the run limit of every other
2219
- * automation in the channel. A thread reply runs only automations whose
2220
- * match names the `thread` location, so existing automations stay top-level.
2241
+ * The job comes before Event data. Empty optional fields are omitted.
2221
2242
  */
2222
- function slackChannelMessageRunsAutomation(event, automation) {
2223
- if (event.namespace !== "slack") return true;
2224
- if (event.data?.channelId !== automation.destination.channelId) return false;
2225
- if (event.data?.location === THREAD_LOCATION && ![automation.trigger.match?.location].flat().includes(THREAD_LOCATION)) return false;
2226
- if (event.data?.postedByBot !== true) return true;
2227
- 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
+ ]);
2228
2270
  }
2229
- /** Return the source message thread for a channel-message run. */
2230
- function slackChannelMessageReplyThreadTs(event) {
2231
- if (event.namespace !== "slack") return void 0;
2232
- const messageTs = event.data?.threadTs ?? event.data?.messageTs;
2233
- 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
+ ]);
2234
2281
  }
2235
- // src/chat/events/runtime-catalog.ts
2236
2282
  /**
2237
- * Enabled event registrations for search, guidance, and tool schemas.
2283
+ * Render one `<task>` for several Watch Events that arrived together.
2238
2284
  *
2239
- * Includes core Workspace snapshot events under the `junior` namespace, Slack
2240
- * channel-message events under the `slack` namespace, plus every enabled plugin
2241
- * 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.
2242
2288
  */
2243
- function getEventCatalog() {
2244
- const snapshot = workspaceSnapshotEvents();
2245
- const catalog = {
2246
- [CORE_EVENT_NAMESPACE]: eventCatalogEntry({
2247
- displayName: botConfig.userName,
2248
- resourceTypes: [...snapshot.resourceTypes, {
2249
- type: "timer",
2250
- supportedEvents: ["timer.fired"],
2251
- suggestedEvents: []
2252
- }],
2253
- events: {
2254
- ...snapshot.events,
2255
- "timer.fired": { reach: "resource" }
2256
- },
2257
- limits: {
2258
- ...snapshot.limits,
2259
- timer: {
2260
- automation: false,
2261
- watch: false,
2262
- watchUnavailableMessage: "Use watchTimer to create a timer Watch."
2263
- }
2264
- }
2265
- }),
2266
- [SLACK_EVENT_NAMESPACE]: eventCatalogEntry({
2267
- ...slackChannelMessageEvents(),
2268
- displayName: "Slack"
2269
- })
2270
- };
2271
- for (const plugin of getPlugins()) {
2272
- const registration = plugin.events;
2273
- if (!registration || registration.isEnabled?.() === false) continue;
2274
- 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`);
2275
- catalog[plugin.manifest.name] = eventCatalogEntry({
2276
- ...registration,
2277
- displayName: plugin.manifest.displayName
2278
- });
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
+ ]));
2279
2315
  }
2280
- return catalog;
2316
+ return renderTag$1("task", {}, [...body, ...replyContractLines(void 0)]);
2281
2317
  }
2282
2318
  // src/chat/events/notification.ts
2283
2319
  const EVENT_WAIT_MS = 3e4;
@@ -2317,11 +2353,11 @@ function eventTaskFacts(subscription, event, people = [], doneBy) {
2317
2353
  function isEventMailboxMetadata(value) {
2318
2354
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2319
2355
  const record = value;
2320
- if (record.kind !== "event") return false;
2321
- const event = record.event;
2356
+ if (record["kind"] !== "event") return false;
2357
+ const event = record["event"];
2322
2358
  if (!event || typeof event !== "object" || Array.isArray(event)) return false;
2323
2359
  const fields = event;
2324
- return typeof fields.eventKey === "string" && typeof fields.eventType === "string" && typeof fields.namespace === "string" && typeof fields.identifier === "string" && (fields.subscriptionId === void 0 || typeof fields.subscriptionId === "string") && (fields.objectType === void 0 || objectTypeSchema.safeParse(fields.objectType).success) && (fields.trustedSummary === void 0 || typeof fields.trustedSummary === "string");
2360
+ return typeof fields["eventKey"] === "string" && typeof fields["eventType"] === "string" && typeof fields["namespace"] === "string" && typeof fields["identifier"] === "string" && (fields["subscriptionId"] === void 0 || typeof fields["subscriptionId"] === "string") && (fields["objectType"] === void 0 || objectTypeSchema.safeParse(fields["objectType"]).success) && (fields["trustedSummary"] === void 0 || typeof fields["trustedSummary"] === "string");
2325
2361
  }
2326
2362
  /**
2327
2363
  * Return the timer creator subject when every event in the batch carries a
@@ -2776,7 +2812,7 @@ async function loadTurnConversationNotes(input) {
2776
2812
  newestFirst.push(failedTurnNote(data.failureCode, data.eventId));
2777
2813
  if (newestFirst.length === MAX_CONVERSATION_NOTES_PER_TURN) break scan;
2778
2814
  } else if (foundTurn && data.type === "structured_event" && data.namespace === "junior" && data.name === conversationNoteEvent.eventName && data.version === conversationNoteEvent.version) {
2779
- newestFirst.push(conversationNoteEvent.parse(data.content).text);
2815
+ newestFirst.push(conversationNoteEvent.parse(data.content)["text"]);
2780
2816
  if (newestFirst.length === MAX_CONVERSATION_NOTES_PER_TURN) break scan;
2781
2817
  }
2782
2818
  if (!page.hasOlder || page.events.length === 0) break;
@@ -2784,47 +2820,6 @@ async function loadTurnConversationNotes(input) {
2784
2820
  }
2785
2821
  return newestFirst.reverse();
2786
2822
  }
2787
- // src/chat/experimental.ts
2788
- /**
2789
- * Known unstable product features that must be opted into explicitly.
2790
- * Add new keys here as features graduate from private experiments; remove them
2791
- * once they become stable defaults.
2792
- */
2793
- const EXPERIMENTAL_FEATURES = [
2794
- "operator-tools",
2795
- "passive-routing",
2796
- "user-customization"
2797
- ];
2798
- const EXPERIMENTAL_FEATURE_SET = new Set(EXPERIMENTAL_FEATURES);
2799
- let configuredExperimental = {};
2800
- function isExperimentalFeature(value) {
2801
- return EXPERIMENTAL_FEATURE_SET.has(value);
2802
- }
2803
- /** Replace app-level experimental opt-ins and return the previous setting. */
2804
- function setExperimentalFeatures(config) {
2805
- const previous = { ...configuredExperimental };
2806
- if (config === void 0) {
2807
- configuredExperimental = {};
2808
- return previous;
2809
- }
2810
- const next = {};
2811
- for (const [rawName, enabled] of Object.entries(config)) {
2812
- if (enabled === void 0) continue;
2813
- if (typeof enabled !== "boolean") throw new Error(`experimental.${rawName} must be a boolean when provided`);
2814
- if (!isExperimentalFeature(rawName)) throw new Error(`experimental.${rawName} is not a known experimental feature. Known features: ${EXPERIMENTAL_FEATURES.join(", ")}`);
2815
- next[rawName] = enabled;
2816
- }
2817
- configuredExperimental = next;
2818
- return previous;
2819
- }
2820
- /** Return a copy of the app-level experimental opt-ins configured by createApp(). */
2821
- function getExperimentalFeatures() {
2822
- return { ...configuredExperimental };
2823
- }
2824
- /** Return whether one experimental feature is enabled via createApp({ experimental }). */
2825
- function isExperimentalFeatureEnabled(feature) {
2826
- return configuredExperimental[feature] === true;
2827
- }
2828
2823
  // src/chat/identities/customization.ts
2829
2824
  /** Read the saved customization for one user. */
2830
2825
  async function readUserCustomization(userId) {
@@ -3288,14 +3283,7 @@ async function eventReviewItemInputs(messages) {
3288
3283
  return new Map(rendered.flatMap(([id, text]) => text ? [[id, text]] : []));
3289
3284
  }
3290
3285
  // src/chat/conversations/session-stop.ts
3291
- var session_stop_exports = /* @__PURE__ */ __exportAll({
3292
- getConversationStoppedAtMs: () => getConversationStoppedAtMs,
3293
- isSkippedAfterConversationStop: () => isSkippedAfterConversationStop,
3294
- isWatchEvent: () => isWatchEvent,
3295
- markConversationsStopped: () => markConversationsStopped,
3296
- resumeStoppedConversationTree: () => resumeStoppedConversationTree,
3297
- skipInputAfterConversationStop: () => skipInputAfterConversationStop
3298
- });
3286
+ var session_stop_exports = /* @__PURE__ */ __exportAll({ skipInputAfterConversationStop: () => skipInputAfterConversationStop });
3299
3287
  /** Skip reason on the Message that saves Events for a stopped Conversation. */
3300
3288
  const STOPPED_CONVERSATION_SKIP_REASON = "stopped conversation";
3301
3289
  /**
@@ -3428,4 +3416,4 @@ async function saveStoppedConversationEvents(conversationId, messages) {
3428
3416
  }
3429
3417
  }]);
3430
3418
  }
3431
- 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, conversationSubtree as at, isExperimentalFeatureEnabled as b, loadReviewItemInput as c, systemPromptHash as ct, buildPromptInput as d, AGENTS_REPLACEMENT_NOTICE as dt, resolveEventMentions as et, buildSteeringPiMessage as f, buildAgentsInstructionsMessage as ft, withoutSavedSteeringMessages as g, showsAgentsInstructions as gt, loadPromptTurnContext as h, renderAgentsInstructions as ht, resumeStoppedConversationTree as i, resetAutomatedTurnLimit as it, legacyWebMailboxMetadataSchema as j, sourceFromTurnInput as k, savedInputInstruction as l, JUNIOR_PERSONALITY as lt, instructionForInputs as m, readRepositoryInstructions as mt, isSkippedAfterConversationStop as n, admitAutomatedTurn as nt, skipInputAfterConversationStop as o, conversationSubtreeColumns as ot, instructionActorFor as p, findVisibleAgentsInstructions as pt, workspaceSnapshotFinishedEvent as q, markConversationsStopped as r, recordFinishedTurnForAutomatedLimit as rt, eventReviewItemInputs as s, buildDeploymentSystemPrompt as st, getConversationStoppedAtMs as t, renderSlackObjectCard as tt, assemblePrompt as u, AGENTS_REMOVAL_NOTICE as ut, saveUserCustomization as v, getEventBatchDelayMs as w, setExperimentalFeatures as x, getExperimentalFeatures as y, SLACK_EVENT_NAMESPACE as z };
3419
+ 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 };