@sentry/junior 0.297.0 → 0.299.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.
- package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
- package/dist/{state-DFnmLmfn.js → adapter-AgCNqqsG.js} +49 -133
- package/dist/{admin-tmGIw4KS.js → admin-1VwEXztm.js} +2 -2
- package/dist/{agent-runner-CneTquAE.js → agent-runner-Ciet8_nn.js} +1067 -1353
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +8 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +125 -43
- package/dist/{app-BJojZ7HL.d.ts → app--ky-Eu33.d.ts} +6 -4
- package/dist/app.d.ts +1 -1
- package/dist/app.js +126 -299
- package/dist/{automation-BrP6ImrC.js → automation-M3RFJUBf.js} +1 -1
- package/dist/{background-compaction-queue-CwfJy3Cd.js → background-compaction-queue-CnimvRdk.js} +4 -4
- package/dist/{briefs-uFTuhMqA.js → briefs-CwzvgdCa.js} +4 -4
- package/dist/{catalog-runtime-0kuQqYL4.js → catalog-runtime-DaBaHY7u.js} +1 -1
- package/dist/cli/chat.js +17 -17
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +5 -5
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +4 -4
- package/dist/{config-Dj9M_nqB.js → config-CAXIpWQb.js} +80 -6
- package/dist/{connections-B96JUM5o.js → connections-Dy0hPdUq.js} +6 -6
- package/dist/continue-in-slack-DIOjFj76.js +176 -0
- package/dist/{conversation-CvcBU1z2.js → conversation-fCWD9Az3.js} +73 -13
- package/dist/{conversation-feed-BSMlGZnS.js → conversation-feed-BPK8vkkZ.js} +88 -3
- package/dist/{conversation-privacy-DI29jbZV.js → conversation-privacy-DUgtRkf8.js} +1 -1
- package/dist/{conversation-turn-CZWBr091.js → conversation-turn-DkJB6yMF.js} +85 -68
- package/dist/{credential-sync-Blhx4_xf.js → credential-sync-RX24Y8aY.js} +18 -18
- package/dist/{db-CrtyFRz7.d.ts → db-B07FtU9g.d.ts} +1 -1
- package/dist/{db-Br0tfAo7.js → db-COYOGzYS.js} +171 -12
- package/dist/{executor-BMPipFVA.js → executor-BWmAgSyi.js} +40 -11
- package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
- package/dist/instrumentation.js +2 -2
- package/dist/lineage-D-5jm_oj.js +37 -0
- package/dist/{logging-CQjlDQYX.js → logging-DPLEa8Bn.js} +1 -1
- package/dist/media-BAHvgkok.js +85 -0
- package/dist/{message-BOZEIuxy.js → message-BIHR1yRk.js} +9 -10
- package/dist/model-input-BPZYH8Nd.js +82 -0
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +17 -9
- package/dist/{oauth-callback-server-V_DuMuNX.js → oauth-callback-server-R7qvSzFG.js} +2 -2
- package/dist/{plugins-HYh_JOdw.js → plugins-CBW2Prb_.js} +1 -1
- package/dist/{projection-B08mfi0u.js → projection-DEdP1q6f.js} +261 -36
- package/dist/{prompt-BlutWLNt.js → prompt-4M98h_tC.js} +4 -4
- package/dist/{registry-BDWgCJDf.js → registry-BTKmKM-r.js} +3 -3
- package/dist/{resolve-2Z_o_SsI.js → resolve-B8hXNVZ3.js} +3 -3
- package/dist/{result-CAujiaci.js → result-g-XAaOj6.js} +158 -69
- package/dist/{runner-D2Chc02N.js → runner-BlPSA5A8.js} +9 -9
- package/dist/{sandbox-egress-signals-CFoJduFj.js → sandbox-egress-signals-Pai-MzEY.js} +1 -1
- package/dist/{schema-Bqa5NbcP.js → schema-BNnY_trV.js} +47 -7
- package/dist/{schema-Ce2XCS7O.d.ts → schema-DbuWR-DN.d.ts} +663 -346
- package/dist/{service-account-C9kRQEb_.js → service-account-9OLNQMyz.js} +4 -4
- package/dist/{service-account-CERfXEVU.js → service-account-BYGZ08DQ.js} +3 -3
- package/dist/session-stop-2XJrcNCy.js +3356 -0
- package/dist/{skills-B0m1nZ_j.js → skills-DpBQoeHV.js} +3 -3
- package/dist/slack-conversation-unfurl-BcDIWo67.js +370 -0
- package/dist/spawn-09GssFod.js +73 -0
- package/dist/state-Cufq0_rH.js +132 -0
- package/dist/{user-input-request-CXNIov9n.js → statuses-B8mUfghF.js} +30 -25
- package/dist/{stop-BCH9VNGf.js → stop-U7iUrR1g.js} +6011 -5773
- package/dist/{store-B59rOYbS.js → store-BHiaHCQu.js} +24 -4
- package/dist/{store-m5bmdmsP.js → store-CSgUTMdv.js} +10 -10
- package/dist/{task-queue-N0kuCknH.js → task-queue-bMNq0clp.js} +4 -4
- package/dist/{task-runner-COOwR8qm.js → task-runner-B__rxwxU.js} +10 -10
- package/dist/{thread-context-Cd44z_W5.js → thread-context-d0ceWbVT.js} +18 -18
- package/dist/{turn-session-routing-BlCtVFRN.js → turn-session-routing-BVZHBFCF.js} +5 -5
- package/dist/turn-user-message-BEw7acTP.js +355 -0
- package/dist/users-BK3dbxZL.js +424 -0
- package/dist/{validation-Ba2OcUse.js → validation-BDVJjO2E.js} +1 -1
- package/dist/{version-KNDzIAh6.js → version-DQgZoQ3D.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-BPpuN2f9.js → viewer-CAWfFo29.js} +25 -54
- package/dist/{warmup-Bskrwmk1.js → warmup-9ySPacF9.js} +1137 -143
- package/dist/{worker-B1skZlit.js → worker-D8jJO-WO.js} +8 -7
- package/migrations/0104_code_change_draft.sql +1 -0
- package/migrations/0105_attachment_uploads.sql +14 -0
- package/migrations/0106_conversation_agent_config.sql +1 -0
- package/migrations/meta/0104_snapshot.json +4516 -0
- package/migrations/meta/0105_snapshot.json +4611 -0
- package/migrations/meta/0106_snapshot.json +4617 -0
- package/migrations/meta/_journal.json +21 -0
- package/package.json +4 -4
- package/dist/attempt-selection-ClP3MMPr.js +0 -61
- package/dist/locks-D-0h111u.js +0 -48
- package/dist/notification-gusCgdQ6.js +0 -1284
- package/dist/prompt-input-Dxn8cDC0.js +0 -1424
- package/dist/session-stop-B-I1rAS1.js +0 -181
- package/dist/spawn-CwMjRRtn.js +0 -80
- package/dist/turn-cancel-DDu8TOwt.js +0 -201
- package/dist/turn-user-message-ygLG3ylQ.js +0 -641
- package/dist/turn-wake-DmQec4AG.js +0 -161
- package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
|
@@ -1,1284 +0,0 @@
|
|
|
1
|
-
import { $i as escapeSlackMrkdwnText, $t as REPLY_TOOL_NAME, Bn as tagJson, Ei as ToolInputError, Ln as renderChildTag, Pn as escapeClosingTags, Qn as getPluginSlackConversationLink, Rn as renderTag, _i as verifyTimerWatchCredentialSubject, bi as getDashboardObjectIconLink, da as postSlackMessage, ea as formatSlackLink, fn as REPORT_BLOCKED_TOOL_NAME, jo as buildSentryConversationUrl, nr as getPlugins, sn as NO_REPLY_TOOL_NAME, ta as normalizeSlackReplyMarkdown, vi as JUNIOR_THREAD_STATE_TTL_MS, yi as getDashboardConversationLink, zn as renderUntrustedTag } from "./projection-B08mfi0u.js";
|
|
2
|
-
import { n as botConfig } from "./config-Dj9M_nqB.js";
|
|
3
|
-
import { h as logWarn, m as logInfo, p as logException } from "./logging-CQjlDQYX.js";
|
|
4
|
-
import { M as SYSTEM_IDENTITY_ID, a as getConversationStore } from "./db-Br0tfAo7.js";
|
|
5
|
-
import { h as credentialSubjectSchema } from "./registry-BDWgCJDf.js";
|
|
6
|
-
import { r as EVENT_AUTHOR_ID } from "./prompt-BlutWLNt.js";
|
|
7
|
-
import { a as getStateAdapter } from "./state-DFnmLmfn.js";
|
|
8
|
-
import { r as appendAndEnqueueInboundMessage } from "./store-B59rOYbS.js";
|
|
9
|
-
import { f as eventCatalogEntry, l as CORE_EVENT_NAMESPACE, p as eventGuidance } from "./turn-session-routing-BlCtVFRN.js";
|
|
10
|
-
import * as z from "zod";
|
|
11
|
-
import { agentEventKeys, eventMatchFieldsSchema, objectFactFields, objectPresentation, objectTypeSchema } from "@sentry/junior-plugin-api";
|
|
12
|
-
// src/chat/services/automated-turn-limit.ts
|
|
13
|
-
const AUTOMATED_TURN_LIMIT_PREFIX = "junior:automated_turn_limit:v1";
|
|
14
|
-
const AUTOMATED_TURN_LIMIT_LOCK_TTL_MS = 5e3;
|
|
15
|
-
const AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS = 2e3;
|
|
16
|
-
const AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS = 25;
|
|
17
|
-
/** Stored consecutive automated-turn count for one Conversation. */
|
|
18
|
-
const automatedTurnLimitStateSchema = z.object({
|
|
19
|
-
consecutiveAutomatedTurns: z.number().int().nonnegative(),
|
|
20
|
-
noticePostedAtMs: z.number().finite().nonnegative().optional(),
|
|
21
|
-
paused: z.boolean(),
|
|
22
|
-
updatedAtMs: z.number().finite().nonnegative()
|
|
23
|
-
}).strict();
|
|
24
|
-
function sleep(ms) {
|
|
25
|
-
return new Promise((resolve) => {
|
|
26
|
-
setTimeout(resolve, ms).unref?.();
|
|
27
|
-
});
|
|
28
|
-
}
|
|
29
|
-
function conversationKey(conversationId) {
|
|
30
|
-
return `${AUTOMATED_TURN_LIMIT_PREFIX}:conversation:${conversationId}`;
|
|
31
|
-
}
|
|
32
|
-
function lockKey(key) {
|
|
33
|
-
return `${key}:lock`;
|
|
34
|
-
}
|
|
35
|
-
function parseState(value) {
|
|
36
|
-
const parsed = automatedTurnLimitStateSchema.safeParse(value);
|
|
37
|
-
return parsed.success ? parsed.data : void 0;
|
|
38
|
-
}
|
|
39
|
-
async function acquireConversationLock(state, key, waitDeadlineMs = Date.now() + AUTOMATED_TURN_LIMIT_LOCK_WAIT_MS) {
|
|
40
|
-
while (true) {
|
|
41
|
-
const lock = await state.acquireLock(lockKey(key), AUTOMATED_TURN_LIMIT_LOCK_TTL_MS);
|
|
42
|
-
if (lock) return lock;
|
|
43
|
-
if (Date.now() >= waitDeadlineMs) throw new Error(`Could not acquire automated turn limit lock for ${key}`);
|
|
44
|
-
await sleep(AUTOMATED_TURN_LIMIT_LOCK_RETRY_MS);
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
async function withConversationLock(state, key, callback) {
|
|
48
|
-
const lock = await acquireConversationLock(state, key);
|
|
49
|
-
try {
|
|
50
|
-
return await callback();
|
|
51
|
-
} finally {
|
|
52
|
-
await state.releaseLock(lock);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
function emptyState(nowMs) {
|
|
56
|
-
return {
|
|
57
|
-
consecutiveAutomatedTurns: 0,
|
|
58
|
-
paused: false,
|
|
59
|
-
updatedAtMs: nowMs
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
/** True when this Source starts an automated Turn rather than a user Turn. */
|
|
63
|
-
function isAutomatedTurnSource(source) {
|
|
64
|
-
if (!source) return false;
|
|
65
|
-
return source.kind === "event" || source.kind === "event_automation" || source.kind === "scheduled_automation" || source.kind === "plugin_dispatch" || source.kind === "agent_invocation";
|
|
66
|
-
}
|
|
67
|
-
/** Plain notice when automatic updates stop until the user replies. */
|
|
68
|
-
function buildAutomatedTurnLimitResponse(args) {
|
|
69
|
-
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.`;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Allow one automated wake, or refuse once the consecutive-turn limit is full.
|
|
73
|
-
* If a prior pause never posted its notice, claim the notice slot so one caller
|
|
74
|
-
* posts it. Clear the claim if that post fails or is skipped.
|
|
75
|
-
*/
|
|
76
|
-
async function admitAutomatedTurn(args) {
|
|
77
|
-
if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
|
|
78
|
-
const state = args.state ?? getStateAdapter();
|
|
79
|
-
await state.connect();
|
|
80
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
81
|
-
const key = conversationKey(args.conversationId);
|
|
82
|
-
return await withConversationLock(state, key, async () => {
|
|
83
|
-
const current = parseState(await state.get(key)) ?? emptyState(nowMs);
|
|
84
|
-
if (current.paused || current.consecutiveAutomatedTurns >= args.maxTurns) {
|
|
85
|
-
const shouldPostNotice = current.noticePostedAtMs === void 0;
|
|
86
|
-
const next = {
|
|
87
|
-
consecutiveAutomatedTurns: Math.max(current.consecutiveAutomatedTurns, args.maxTurns),
|
|
88
|
-
paused: true,
|
|
89
|
-
updatedAtMs: nowMs,
|
|
90
|
-
...shouldPostNotice ? { noticePostedAtMs: nowMs } : current.noticePostedAtMs !== void 0 ? { noticePostedAtMs: current.noticePostedAtMs } : void 0
|
|
91
|
-
};
|
|
92
|
-
await state.set(key, next, JUNIOR_THREAD_STATE_TTL_MS);
|
|
93
|
-
return {
|
|
94
|
-
status: "paused",
|
|
95
|
-
consecutiveAutomatedTurns: next.consecutiveAutomatedTurns,
|
|
96
|
-
shouldPostNotice
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
return {
|
|
100
|
-
status: "allow",
|
|
101
|
-
consecutiveAutomatedTurns: current.consecutiveAutomatedTurns
|
|
102
|
-
};
|
|
103
|
-
});
|
|
104
|
-
}
|
|
105
|
-
/** Count one finished automated Turn toward the consecutive-turn limit. */
|
|
106
|
-
async function countAutomatedTurn(args) {
|
|
107
|
-
if (args.maxTurns < 1) throw new Error("Automated turn limit must be at least 1");
|
|
108
|
-
const state = args.state ?? getStateAdapter();
|
|
109
|
-
await state.connect();
|
|
110
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
111
|
-
const key = conversationKey(args.conversationId);
|
|
112
|
-
return await withConversationLock(state, key, async () => {
|
|
113
|
-
const current = parseState(await state.get(key)) ?? emptyState(nowMs);
|
|
114
|
-
const consecutiveAutomatedTurns = current.consecutiveAutomatedTurns + 1;
|
|
115
|
-
const paused = consecutiveAutomatedTurns >= args.maxTurns;
|
|
116
|
-
const shouldPostNotice = paused && current.noticePostedAtMs === void 0;
|
|
117
|
-
const next = {
|
|
118
|
-
consecutiveAutomatedTurns,
|
|
119
|
-
paused,
|
|
120
|
-
updatedAtMs: nowMs,
|
|
121
|
-
...shouldPostNotice ? { noticePostedAtMs: nowMs } : current.noticePostedAtMs !== void 0 ? { noticePostedAtMs: current.noticePostedAtMs } : void 0
|
|
122
|
-
};
|
|
123
|
-
await state.set(key, next, JUNIOR_THREAD_STATE_TTL_MS);
|
|
124
|
-
return {
|
|
125
|
-
consecutiveAutomatedTurns,
|
|
126
|
-
paused,
|
|
127
|
-
shouldPostNotice
|
|
128
|
-
};
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
/**
|
|
132
|
-
* Drop a failed notice claim so a later paused wake can post the notice.
|
|
133
|
-
* Keeps the pause and consecutive count.
|
|
134
|
-
*/
|
|
135
|
-
async function clearAutomatedTurnLimitNoticeClaim(args) {
|
|
136
|
-
const state = args.state ?? getStateAdapter();
|
|
137
|
-
await state.connect();
|
|
138
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
139
|
-
const key = conversationKey(args.conversationId);
|
|
140
|
-
await withConversationLock(state, key, async () => {
|
|
141
|
-
const current = parseState(await state.get(key));
|
|
142
|
-
if (!current || current.noticePostedAtMs === void 0) return;
|
|
143
|
-
const { noticePostedAtMs: _noticePostedAtMs, ...rest } = current;
|
|
144
|
-
await state.set(key, {
|
|
145
|
-
...rest,
|
|
146
|
-
updatedAtMs: nowMs
|
|
147
|
-
}, JUNIOR_THREAD_STATE_TTL_MS);
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
/** Clear the consecutive automated-turn count after a user-owned Turn. */
|
|
151
|
-
async function resetAutomatedTurnLimit(args) {
|
|
152
|
-
const state = args.state ?? getStateAdapter();
|
|
153
|
-
await state.connect();
|
|
154
|
-
const key = conversationKey(args.conversationId);
|
|
155
|
-
await withConversationLock(state, key, async () => {
|
|
156
|
-
await state.delete(key);
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Update consecutive automated-turn counts after one finished Turn.
|
|
161
|
-
*
|
|
162
|
-
* Automated Turns count on the Conversation. User Turns clear that count so
|
|
163
|
-
* later event wakes can run again.
|
|
164
|
-
*/
|
|
165
|
-
async function recordFinishedTurnForAutomatedLimit(args) {
|
|
166
|
-
const nowMs = args.nowMs ?? Date.now();
|
|
167
|
-
if (isAutomatedTurnSource(args.source)) return await countAutomatedTurn({
|
|
168
|
-
conversationId: args.conversationId,
|
|
169
|
-
maxTurns: args.maxTurns,
|
|
170
|
-
nowMs,
|
|
171
|
-
state: args.state
|
|
172
|
-
});
|
|
173
|
-
await resetAutomatedTurnLimit({
|
|
174
|
-
conversationId: args.conversationId,
|
|
175
|
-
nowMs,
|
|
176
|
-
state: args.state
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
// src/chat/slack/automation-card.ts
|
|
180
|
-
function preview(text, length) {
|
|
181
|
-
const compact = text.replace(/\s+/g, " ").trim();
|
|
182
|
-
return compact.length > length ? `${compact.slice(0, length - 1)}…` : compact;
|
|
183
|
-
}
|
|
184
|
-
/** Show an Automation as a native Work Object, not an operation receipt. */
|
|
185
|
-
function renderSlackAutomationCard(card) {
|
|
186
|
-
const title = preview(card.title, 160);
|
|
187
|
-
const iconUrl = getDashboardObjectIconLink("workflow");
|
|
188
|
-
const trigger = preview(card.trigger, 500);
|
|
189
|
-
const warning = card.warning ? preview(card.warning, 500) : null;
|
|
190
|
-
const text = [
|
|
191
|
-
"Automation",
|
|
192
|
-
card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
|
|
193
|
-
escapeSlackMrkdwnText(trigger),
|
|
194
|
-
warning ? escapeSlackMrkdwnText(warning) : null
|
|
195
|
-
].filter(Boolean).join("\n");
|
|
196
|
-
if (!card.url) return {
|
|
197
|
-
entity: null,
|
|
198
|
-
text
|
|
199
|
-
};
|
|
200
|
-
return {
|
|
201
|
-
text,
|
|
202
|
-
entity: {
|
|
203
|
-
entity_type: "slack#/entities/item",
|
|
204
|
-
external_ref: {
|
|
205
|
-
id: card.id,
|
|
206
|
-
type: "automation"
|
|
207
|
-
},
|
|
208
|
-
url: card.url,
|
|
209
|
-
entity_payload: {
|
|
210
|
-
attributes: {
|
|
211
|
-
title: { text: title },
|
|
212
|
-
display_type: "Automation",
|
|
213
|
-
product_icon: iconUrl ? {
|
|
214
|
-
url: iconUrl,
|
|
215
|
-
alt_text: "Automation"
|
|
216
|
-
} : void 0
|
|
217
|
-
},
|
|
218
|
-
custom_fields: [{
|
|
219
|
-
key: "trigger",
|
|
220
|
-
label: "When",
|
|
221
|
-
type: "string",
|
|
222
|
-
value: trigger,
|
|
223
|
-
long: true
|
|
224
|
-
}, ...warning ? [{
|
|
225
|
-
key: "warning",
|
|
226
|
-
label: "Needs attention",
|
|
227
|
-
type: "string",
|
|
228
|
-
value: warning,
|
|
229
|
-
long: true
|
|
230
|
-
}] : []]
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
// src/chat/slack/object-card.ts
|
|
236
|
-
function descriptionPreview(value) {
|
|
237
|
-
const text = value?.replace(/\r\n/g, "\n").trim() ?? "";
|
|
238
|
-
const preview = text.split("\n").slice(0, 6).join("\n").slice(0, 500);
|
|
239
|
-
return preview.length < text.length ? `${preview.slice(0, 499).trimEnd()}…` : preview;
|
|
240
|
-
}
|
|
241
|
-
/** Render a compact Task or Item preview, or the saved facts for its detail panel. */
|
|
242
|
-
function renderSlackObjectCard(card, conversationId, surface = "preview") {
|
|
243
|
-
if (card.objectType === "automation" && card.plugin === "junior") return renderSlackAutomationCard({
|
|
244
|
-
id: card.key,
|
|
245
|
-
title: card.title,
|
|
246
|
-
url: card.url,
|
|
247
|
-
trigger: card.trigger ?? "",
|
|
248
|
-
warning: card.warning ?? null
|
|
249
|
-
});
|
|
250
|
-
const presentation = objectPresentation(card);
|
|
251
|
-
const type = card.displayType ?? presentation.label;
|
|
252
|
-
const iconUrl = getDashboardObjectIconLink(presentation.icon);
|
|
253
|
-
const title = card.title.slice(0, 160);
|
|
254
|
-
const details = surface === "details";
|
|
255
|
-
const deployment = card.objectType === "deployment" || card.objectType === "item" && card.facts?.type === "deployment";
|
|
256
|
-
const calendarEvent = card.objectType === "calendar_event";
|
|
257
|
-
const status = details || deployment || calendarEvent ? card.status : void 0;
|
|
258
|
-
const warning = details || deployment ? card.warning : void 0;
|
|
259
|
-
const facts = objectFactFields(card.facts).filter((field) => details || calendarEvent || deployment && field.key === "environment");
|
|
260
|
-
const description = details ? card.description?.trim() ?? "" : calendarEvent ? "" : descriptionPreview(card.description);
|
|
261
|
-
const text = [
|
|
262
|
-
escapeSlackMrkdwnText(type),
|
|
263
|
-
card.url ? formatSlackLink(card.url, title) : escapeSlackMrkdwnText(title),
|
|
264
|
-
escapeSlackMrkdwnText(card.label),
|
|
265
|
-
status ? escapeSlackMrkdwnText(status) : null,
|
|
266
|
-
description ? escapeSlackMrkdwnText(description) : null,
|
|
267
|
-
warning ? escapeSlackMrkdwnText(`Needs attention: ${warning}`) : null,
|
|
268
|
-
...facts.map((field) => escapeSlackMrkdwnText(`${field.label}: ${field.value}`))
|
|
269
|
-
].filter(Boolean).join("\n");
|
|
270
|
-
if (!card.url) return {
|
|
271
|
-
entity: null,
|
|
272
|
-
text
|
|
273
|
-
};
|
|
274
|
-
const task = card.objectType === "task";
|
|
275
|
-
const attributes = {
|
|
276
|
-
title: { text: title },
|
|
277
|
-
display_id: card.label,
|
|
278
|
-
display_type: type,
|
|
279
|
-
product_icon: iconUrl ? {
|
|
280
|
-
url: iconUrl,
|
|
281
|
-
alt_text: `${type}${status ? `: ${status}` : ""}`
|
|
282
|
-
} : void 0,
|
|
283
|
-
product_name: card.plugin
|
|
284
|
-
};
|
|
285
|
-
const customFields = [
|
|
286
|
-
...description ? [{
|
|
287
|
-
key: "description",
|
|
288
|
-
label: "Description",
|
|
289
|
-
type: "string",
|
|
290
|
-
value: description,
|
|
291
|
-
long: true,
|
|
292
|
-
format: "markdown"
|
|
293
|
-
}] : [],
|
|
294
|
-
...facts.map((field) => ({
|
|
295
|
-
...field,
|
|
296
|
-
type: "string"
|
|
297
|
-
})),
|
|
298
|
-
...warning ? [{
|
|
299
|
-
key: "warning",
|
|
300
|
-
label: "Needs attention",
|
|
301
|
-
type: "string",
|
|
302
|
-
value: warning
|
|
303
|
-
}] : []
|
|
304
|
-
];
|
|
305
|
-
return {
|
|
306
|
-
text,
|
|
307
|
-
entity: {
|
|
308
|
-
...task ? {
|
|
309
|
-
entity_type: "slack#/entities/task",
|
|
310
|
-
entity_payload: {
|
|
311
|
-
attributes,
|
|
312
|
-
display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
|
|
313
|
-
fields: status ? { status: { value: status } } : void 0,
|
|
314
|
-
custom_fields: customFields
|
|
315
|
-
}
|
|
316
|
-
} : {
|
|
317
|
-
entity_type: "slack#/entities/item",
|
|
318
|
-
entity_payload: {
|
|
319
|
-
attributes,
|
|
320
|
-
display_order: [...status ? ["status"] : [], ...customFields.map((field) => field.key)],
|
|
321
|
-
custom_fields: [...status ? [{
|
|
322
|
-
key: "status",
|
|
323
|
-
label: "Status",
|
|
324
|
-
type: "string",
|
|
325
|
-
value: status
|
|
326
|
-
}] : [], ...customFields]
|
|
327
|
-
}
|
|
328
|
-
},
|
|
329
|
-
external_ref: {
|
|
330
|
-
id: Buffer.from(JSON.stringify([
|
|
331
|
-
conversationId,
|
|
332
|
-
card.plugin,
|
|
333
|
-
card.key
|
|
334
|
-
]), "utf8").toString("base64url"),
|
|
335
|
-
type: "annotation"
|
|
336
|
-
},
|
|
337
|
-
url: card.url
|
|
338
|
-
}
|
|
339
|
-
};
|
|
340
|
-
}
|
|
341
|
-
// src/chat/slack/cards.ts
|
|
342
|
-
/** Select the Slack object renderer for a built-in card. */
|
|
343
|
-
function renderSlackCard(card, conversationId) {
|
|
344
|
-
switch (card.kind) {
|
|
345
|
-
case "object": return renderSlackObjectCard(card, conversationId);
|
|
346
|
-
case "automation": return renderSlackAutomationCard(card);
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
// src/chat/slack/footer.ts
|
|
350
|
-
/** Render compact reply attribution for the Slack footer. */
|
|
351
|
-
function formatReplyAttribution(attribution) {
|
|
352
|
-
return attribution.detail ? `${attribution.label} · ${attribution.detail}` : attribution.label;
|
|
353
|
-
}
|
|
354
|
-
/**
|
|
355
|
-
* Build the compact conversation footer for visible Slack reply surfaces.
|
|
356
|
-
*
|
|
357
|
-
* Detailed turn metrics stay in the dashboard instead of Slack-visible copy.
|
|
358
|
-
*/
|
|
359
|
-
function buildSlackReplyFooter(args) {
|
|
360
|
-
const items = [];
|
|
361
|
-
const conversationId = args.conversationId?.trim();
|
|
362
|
-
if (conversationId) {
|
|
363
|
-
const idItem = {
|
|
364
|
-
label: "ID",
|
|
365
|
-
value: conversationId
|
|
366
|
-
};
|
|
367
|
-
const conversationUrl = getPluginSlackConversationLink(conversationId)?.url ?? getDashboardConversationLink(conversationId) ?? buildSentryConversationUrl(conversationId);
|
|
368
|
-
if (conversationUrl) idItem.url = conversationUrl;
|
|
369
|
-
items.push(idItem);
|
|
370
|
-
}
|
|
371
|
-
return items.length > 0 || args.replyAttribution ? {
|
|
372
|
-
...args.replyAttribution ? { attribution: args.replyAttribution } : void 0,
|
|
373
|
-
items
|
|
374
|
-
} : void 0;
|
|
375
|
-
}
|
|
376
|
-
/** Build Slack blocks for a reply chunk using the Slack-flavored markdown block for the body. */
|
|
377
|
-
function buildSlackReplyBlocks(text, footer) {
|
|
378
|
-
const blocks = text.trim() ? [{
|
|
379
|
-
type: "markdown",
|
|
380
|
-
text
|
|
381
|
-
}] : [];
|
|
382
|
-
if (footer && (footer.attribution || footer.items.length > 0)) {
|
|
383
|
-
const attributionElements = footer.attribution ? [{
|
|
384
|
-
type: "plain_text",
|
|
385
|
-
text: formatReplyAttribution(footer.attribution)
|
|
386
|
-
}] : [];
|
|
387
|
-
blocks.push({
|
|
388
|
-
type: "context",
|
|
389
|
-
elements: [...attributionElements, ...footer.items.map((item) => ({
|
|
390
|
-
type: "mrkdwn",
|
|
391
|
-
text: item.url ? `*${escapeSlackMrkdwnText(item.label)}:* ${formatSlackLink(item.url, item.value)}` : `*${escapeSlackMrkdwnText(item.label)}:* ${escapeSlackMrkdwnText(item.value)}`
|
|
392
|
-
}))]
|
|
393
|
-
});
|
|
394
|
-
}
|
|
395
|
-
return blocks.length ? blocks : void 0;
|
|
396
|
-
}
|
|
397
|
-
// src/chat/slack/output.ts
|
|
398
|
-
const MAX_INLINE_CHARS = 4e3;
|
|
399
|
-
function getFenceContinuation(text) {
|
|
400
|
-
let open;
|
|
401
|
-
for (const line of text.split("\n")) {
|
|
402
|
-
const trimmed = line.trimStart();
|
|
403
|
-
const openerMatch = trimmed.match(/^(`{3,}|~{3,})(.*)$/);
|
|
404
|
-
if (!openerMatch?.[1]) continue;
|
|
405
|
-
if (!open) {
|
|
406
|
-
open = {
|
|
407
|
-
fence: openerMatch[1],
|
|
408
|
-
openerLine: trimmed
|
|
409
|
-
};
|
|
410
|
-
continue;
|
|
411
|
-
}
|
|
412
|
-
if (new RegExp(`^${open.fence}\\s*$`).test(trimmed)) open = void 0;
|
|
413
|
-
}
|
|
414
|
-
if (!open) return null;
|
|
415
|
-
return {
|
|
416
|
-
closeSuffix: text.endsWith("\n") ? open.fence : `\n${open.fence}`,
|
|
417
|
-
reopenPrefix: `${open.openerLine}\n`
|
|
418
|
-
};
|
|
419
|
-
}
|
|
420
|
-
function findSplitIndex(text, maxChars) {
|
|
421
|
-
const bounded = text.slice(0, maxChars);
|
|
422
|
-
const newlineIndex = bounded.lastIndexOf("\n");
|
|
423
|
-
if (newlineIndex > 0) return newlineIndex;
|
|
424
|
-
const spaceIndex = bounded.lastIndexOf(" ");
|
|
425
|
-
if (spaceIndex > 0) return spaceIndex;
|
|
426
|
-
return maxChars;
|
|
427
|
-
}
|
|
428
|
-
function takePrefix(text, maxChars) {
|
|
429
|
-
const prefix = text.slice(0, findSplitIndex(text, maxChars)).trimEnd() || text.slice(0, maxChars);
|
|
430
|
-
return {
|
|
431
|
-
prefix,
|
|
432
|
-
rest: text.slice(prefix.length).trimStart()
|
|
433
|
-
};
|
|
434
|
-
}
|
|
435
|
-
/** Take one post that fits the budget, closing a code fence it leaves open. */
|
|
436
|
-
function takeChunk(text) {
|
|
437
|
-
let { prefix, rest } = takePrefix(text, MAX_INLINE_CHARS);
|
|
438
|
-
let carryover = getFenceContinuation(prefix);
|
|
439
|
-
if (!carryover) return {
|
|
440
|
-
chunk: prefix,
|
|
441
|
-
rest
|
|
442
|
-
};
|
|
443
|
-
({prefix, rest} = takePrefix(text, MAX_INLINE_CHARS - carryover.closeSuffix.length));
|
|
444
|
-
carryover = getFenceContinuation(prefix);
|
|
445
|
-
if (!carryover || !rest) return {
|
|
446
|
-
chunk: prefix,
|
|
447
|
-
rest
|
|
448
|
-
};
|
|
449
|
-
return {
|
|
450
|
-
chunk: `${prefix}${carryover.closeSuffix}`,
|
|
451
|
-
rest: `${carryover.reopenPrefix}${rest}`
|
|
452
|
-
};
|
|
453
|
-
}
|
|
454
|
-
/** Split a normalized Slack reply into thread posts that fit Slack limits. */
|
|
455
|
-
function splitSlackReplyText(text) {
|
|
456
|
-
const chunks = [];
|
|
457
|
-
let remaining = normalizeSlackReplyMarkdown(text);
|
|
458
|
-
while (remaining.length > MAX_INLINE_CHARS) {
|
|
459
|
-
const { chunk, rest } = takeChunk(remaining);
|
|
460
|
-
chunks.push(chunk);
|
|
461
|
-
remaining = rest;
|
|
462
|
-
}
|
|
463
|
-
if (remaining) chunks.push(remaining);
|
|
464
|
-
return chunks;
|
|
465
|
-
}
|
|
466
|
-
// src/chat/slack/reply.ts
|
|
467
|
-
/**
|
|
468
|
-
* Resolve where a Turn posts in Slack.
|
|
469
|
-
*
|
|
470
|
-
* The channel is always the Destination channel. The thread comes from the
|
|
471
|
-
* Turn Source, then the Conversation Location, then the Destination, and each
|
|
472
|
-
* one counts only when it names that channel. Do not derive the target from
|
|
473
|
-
* the Conversation id: an Automation or Watch Conversation can own a Slack
|
|
474
|
-
* thread, and its id is not a Slack thread id.
|
|
475
|
-
*/
|
|
476
|
-
function resolveSlackReplyTarget(args) {
|
|
477
|
-
const { channelId } = args.destination;
|
|
478
|
-
const sourceThreadTs = args.source?.kind === "slack" && args.source.channelId === channelId ? args.source.threadTs : void 0;
|
|
479
|
-
const locationThreadTs = args.location?.provider === "slack" && args.location.channelId === channelId ? args.location.threadTs : void 0;
|
|
480
|
-
const threadTs = sourceThreadTs ?? locationThreadTs ?? args.destination.threadTs;
|
|
481
|
-
return {
|
|
482
|
-
channelId,
|
|
483
|
-
...threadTs ? { threadTs } : void 0
|
|
484
|
-
};
|
|
485
|
-
}
|
|
486
|
-
/**
|
|
487
|
-
* Send one destination-visible Slack reply.
|
|
488
|
-
*
|
|
489
|
-
* Chunks oversized text, builds compact attribution and conversation footer
|
|
490
|
-
* context, and posts through the shared Slack outbound boundary.
|
|
491
|
-
*/
|
|
492
|
-
async function sendSlackReply(args) {
|
|
493
|
-
const posts = splitSlackReplyText(args.text).map((text) => ({
|
|
494
|
-
text,
|
|
495
|
-
cards: []
|
|
496
|
-
}));
|
|
497
|
-
const cards = (args.cards ?? []).map((card) => renderSlackCard(card, args.conversationId));
|
|
498
|
-
for (let index = 0; index < cards.length; index += 5) {
|
|
499
|
-
const group = cards.slice(index, index + 5);
|
|
500
|
-
const lastPost = posts.at(-1);
|
|
501
|
-
if (index === 0 && lastPost) lastPost.cards = group;
|
|
502
|
-
else posts.push({
|
|
503
|
-
text: "",
|
|
504
|
-
cards: group
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
const footer = buildSlackReplyFooter({
|
|
508
|
-
conversationId: args.conversationId,
|
|
509
|
-
replyAttribution: args.replyAttribution
|
|
510
|
-
});
|
|
511
|
-
const messageTs = [];
|
|
512
|
-
let threadTs = args.threadTs;
|
|
513
|
-
for (const [index, post] of posts.entries()) {
|
|
514
|
-
const { text, cards } = post;
|
|
515
|
-
const isFinalChunk = index === posts.length - 1;
|
|
516
|
-
const blocks = buildSlackReplyBlocks(text, void 0) ?? [];
|
|
517
|
-
for (const card of cards) if (!card.entity) blocks.push({
|
|
518
|
-
type: "section",
|
|
519
|
-
text: {
|
|
520
|
-
type: "mrkdwn",
|
|
521
|
-
text: card.text
|
|
522
|
-
}
|
|
523
|
-
});
|
|
524
|
-
if (isFinalChunk || !text.trim()) blocks.push(...buildSlackReplyBlocks("", footer) ?? []);
|
|
525
|
-
const entities = cards.flatMap((card) => card.entity ? [card.entity] : []);
|
|
526
|
-
const accessibleText = [text, ...cards.map((card) => card.text)].filter(Boolean).join("\n\n");
|
|
527
|
-
const fallbackText = isFinalChunk && args.replyAttribution ? `${accessibleText}\n\n${escapeSlackMrkdwnText(formatReplyAttribution(args.replyAttribution))}` : accessibleText;
|
|
528
|
-
const response = await postSlackMessage({
|
|
529
|
-
channelId: args.channelId,
|
|
530
|
-
threadTs,
|
|
531
|
-
text: fallbackText,
|
|
532
|
-
...blocks.length ? { blocks } : void 0,
|
|
533
|
-
...entities.length ? { entities } : void 0
|
|
534
|
-
});
|
|
535
|
-
if (response.ts) {
|
|
536
|
-
messageTs.push(response.ts);
|
|
537
|
-
threadTs ??= response.ts;
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
return messageTs;
|
|
541
|
-
}
|
|
542
|
-
// src/chat/slack/automated-turn-limit-notice.ts
|
|
543
|
-
/**
|
|
544
|
-
* Pause notice for the consecutive automated-turn limit.
|
|
545
|
-
*
|
|
546
|
-
* Best-effort: a failed post must not fail the Turn or re-enable event wakes.
|
|
547
|
-
* The consecutive-turn limit claims the notice slot before this post. Clear that
|
|
548
|
-
* claim when the post fails or is skipped so a later paused wake can try again.
|
|
549
|
-
*/
|
|
550
|
-
async function releaseFailedNoticeClaim(args) {
|
|
551
|
-
try {
|
|
552
|
-
await clearAutomatedTurnLimitNoticeClaim(args);
|
|
553
|
-
} catch (error) {
|
|
554
|
-
logException(error, "automated_turn_limit.notice_claim_clear_failed");
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
/** Post the pause notice for one Conversation Location when known. */
|
|
558
|
-
async function postAutomatedTurnLimitNoticeForConversation(args) {
|
|
559
|
-
try {
|
|
560
|
-
const conversation = await getConversationStore().get({ conversationId: args.conversationId });
|
|
561
|
-
const location = conversation?.parentConversationId ? void 0 : conversation?.location;
|
|
562
|
-
if (!location || location.provider !== "slack") {
|
|
563
|
-
logWarn("automated_turn_limit.notice_skipped", {
|
|
564
|
-
conversationId: args.conversationId,
|
|
565
|
-
"app.automated_turn_limit.reason": location ? "unsupported_location" : "missing_location"
|
|
566
|
-
});
|
|
567
|
-
await releaseFailedNoticeClaim({
|
|
568
|
-
conversationId: args.conversationId,
|
|
569
|
-
nowMs: args.nowMs
|
|
570
|
-
});
|
|
571
|
-
return false;
|
|
572
|
-
}
|
|
573
|
-
await sendSlackReply({
|
|
574
|
-
...resolveSlackReplyTarget({
|
|
575
|
-
destination: location,
|
|
576
|
-
location,
|
|
577
|
-
source: args.source
|
|
578
|
-
}),
|
|
579
|
-
conversationId: args.conversationId,
|
|
580
|
-
text: buildAutomatedTurnLimitResponse({ maxTurns: args.maxTurns })
|
|
581
|
-
});
|
|
582
|
-
return true;
|
|
583
|
-
} catch (error) {
|
|
584
|
-
logException(error, "automated_turn_limit.notice_failed", { conversationId: args.conversationId });
|
|
585
|
-
await releaseFailedNoticeClaim({
|
|
586
|
-
conversationId: args.conversationId,
|
|
587
|
-
nowMs: args.nowMs
|
|
588
|
-
});
|
|
589
|
-
return false;
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
/** Post the pause notice after a finished Turn hits the limit. */
|
|
593
|
-
async function maybePostAutomatedTurnLimitNotice(args) {
|
|
594
|
-
if (!args.update?.shouldPostNotice) return;
|
|
595
|
-
await postAutomatedTurnLimitNoticeForConversation({
|
|
596
|
-
conversationId: args.conversationId,
|
|
597
|
-
maxTurns: args.maxTurns,
|
|
598
|
-
nowMs: args.nowMs,
|
|
599
|
-
source: args.source
|
|
600
|
-
});
|
|
601
|
-
}
|
|
602
|
-
// src/chat/task-input.ts
|
|
603
|
-
/**
|
|
604
|
-
* Shared agent input for tasks: one `<task>` input tag. A task can come from
|
|
605
|
-
* a schedule, an event, or a watch. Call sites supply facts; this module owns
|
|
606
|
-
* layout and the reply contract. Unit snapshots in
|
|
607
|
-
* `tests/unit/chat/task-input.test.ts` own the exact text. Event data stays in
|
|
608
|
-
* its own child tags, and the outcome rule is always last.
|
|
609
|
-
*/
|
|
610
|
-
/**
|
|
611
|
-
* Shared closing lines. Automations pass outcomes and end with an answer
|
|
612
|
-
* tool. Watches follow the Conversation's reply rules. A Watch reply goes
|
|
613
|
-
* only to the Conversation, so a question asked in the provider must also get
|
|
614
|
-
* its answer there. Watch instructions often say to stay silent, so this rule
|
|
615
|
-
* sits in the contract, not in plugin guidance.
|
|
616
|
-
*/
|
|
617
|
-
function replyContractLines(outcomes) {
|
|
618
|
-
if (!outcomes) return [
|
|
619
|
-
"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.",
|
|
620
|
-
"When you reply, follow any reply format in the instructions.",
|
|
621
|
-
`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.`
|
|
622
|
-
];
|
|
623
|
-
return [`End with \`${REPLY_TOOL_NAME}\`, \`${NO_REPLY_TOOL_NAME}\`, or \`${REPORT_BLOCKED_TOOL_NAME}\`.`];
|
|
624
|
-
}
|
|
625
|
-
function oneLine(value) {
|
|
626
|
-
return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
|
|
627
|
-
}
|
|
628
|
-
function clip(value, maxLength) {
|
|
629
|
-
return maxLength === void 0 ? value : value.slice(0, maxLength);
|
|
630
|
-
}
|
|
631
|
-
const CREATOR_REFERENCE = /\bthe Automation creator\b/gi;
|
|
632
|
-
/**
|
|
633
|
-
* Write the creator mention where the instructions say "the Automation
|
|
634
|
-
* creator", so the run does not have to swap it in.
|
|
635
|
-
*/
|
|
636
|
-
function mentionCreator(instructions, creator) {
|
|
637
|
-
return instructions.replace(CREATOR_REFERENCE, () => creator);
|
|
638
|
-
}
|
|
639
|
-
function quoted(values) {
|
|
640
|
-
return values.map((value) => `"${value}"`).join(" or ");
|
|
641
|
-
}
|
|
642
|
-
/**
|
|
643
|
-
* Render each linked person once. A doer in `<people>` gets a note in that
|
|
644
|
-
* list. Other doers get a `<done-by>` tag. Without one entry per person, the
|
|
645
|
-
* agent can mention a person and then name them again by handle as if they
|
|
646
|
-
* were someone else. The "you" rule covers doers outside `<people>` too,
|
|
647
|
-
* because instructions can still ask to mention them, such as a requester who
|
|
648
|
-
* reviews their own pull request. A child agent replies to its parent, not to
|
|
649
|
-
* the person, so it writes the mention instead of the handle. That carries
|
|
650
|
-
* who the person is up each level to the agent that replies to them.
|
|
651
|
-
*/
|
|
652
|
-
function peopleTags(people, doers) {
|
|
653
|
-
const label = (doer) => `${doer.mention} (${[doer.did, ...doer.handles.length > 0 ? [`called ${quoted(doer.handles)} in the Event data`] : []].join("; ")})`;
|
|
654
|
-
const doerByMention = new Map(doers.map((doer) => [doer.mention, doer]));
|
|
655
|
-
const involved = people.map((person) => {
|
|
656
|
-
const doer = doerByMention.get(person);
|
|
657
|
-
return doer ? label(doer) : person;
|
|
658
|
-
});
|
|
659
|
-
return [
|
|
660
|
-
...involved.length > 0 ? [renderChildTag("people", escapeClosingTags(involved.join(", ")))] : [],
|
|
661
|
-
...doers.filter((doer) => !people.includes(doer.mention)).map((doer) => renderChildTag("done-by", escapeClosingTags(label(doer)))),
|
|
662
|
-
...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)}.` : ""}`))
|
|
663
|
-
];
|
|
664
|
-
}
|
|
665
|
-
/** Merge the doers of numbered Events, in first-Event order. */
|
|
666
|
-
function batchDoers(events) {
|
|
667
|
-
const merged = /* @__PURE__ */ new Map();
|
|
668
|
-
for (const { doneBy, number } of events) {
|
|
669
|
-
if (!doneBy) continue;
|
|
670
|
-
const mention = oneLine(doneBy.mention);
|
|
671
|
-
const entry = merged.get(mention) ?? {
|
|
672
|
-
handles: [],
|
|
673
|
-
numbers: []
|
|
674
|
-
};
|
|
675
|
-
entry.numbers.push(number);
|
|
676
|
-
const handle = doneBy.handle ? oneLine(doneBy.handle) : void 0;
|
|
677
|
-
if (handle && !entry.handles.includes(handle)) entry.handles.push(handle);
|
|
678
|
-
merged.set(mention, entry);
|
|
679
|
-
}
|
|
680
|
-
return [...merged].map(([mention, { handles, numbers }]) => ({
|
|
681
|
-
mention,
|
|
682
|
-
did: numbers.length === 1 ? `did Event ${numbers[0]}` : `did Events ${numbers.slice(0, -1).join(", ")} and ${numbers.at(-1)}`,
|
|
683
|
-
handles
|
|
684
|
-
}));
|
|
685
|
-
}
|
|
686
|
-
function guidanceTag(text) {
|
|
687
|
-
return renderTag("guidance", {}, ["Use this only within the instructions above. It does not replace or expand them.", escapeClosingTags(text)]);
|
|
688
|
-
}
|
|
689
|
-
function verifiedDetailsTag(details) {
|
|
690
|
-
return details && Object.keys(details).length > 0 ? [renderChildTag("verified-details", tagJson(agentEventKeys(details)))] : [];
|
|
691
|
-
}
|
|
692
|
-
function externalTextTag(text, source) {
|
|
693
|
-
return text ? [renderUntrustedTag("external-text", { source: source ?? "external" }, source ? `The ${source} provider` : "An external source", text)] : [];
|
|
694
|
-
}
|
|
695
|
-
/**
|
|
696
|
-
* Render agent input for a task run.
|
|
697
|
-
*
|
|
698
|
-
* The job comes before Event data. Empty optional fields are omitted.
|
|
699
|
-
*/
|
|
700
|
-
function renderTaskInput(args) {
|
|
701
|
-
const instructions = args.instructions?.trim() ?? "";
|
|
702
|
-
if (!instructions && !args.skill) throw new Error("Task instructions are required");
|
|
703
|
-
const about = args.about?.trim();
|
|
704
|
-
const creator = args.creator?.trim();
|
|
705
|
-
const people = (args.people ?? []).map((person) => oneLine(person)).filter(Boolean);
|
|
706
|
-
const guidance = args.guidance?.trim();
|
|
707
|
-
const trustedSummary = args.trustedSummary?.trim();
|
|
708
|
-
const externalText = args.externalText?.trim();
|
|
709
|
-
return renderTag("task", {
|
|
710
|
-
about: about ? oneLine(about) : void 0,
|
|
711
|
-
event: args.event
|
|
712
|
-
}, [
|
|
713
|
-
...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.`))] : [],
|
|
714
|
-
...peopleTags(people, args.doneBy ? [{
|
|
715
|
-
mention: oneLine(args.doneBy.mention),
|
|
716
|
-
did: "did what this Event describes",
|
|
717
|
-
handles: args.doneBy.handle ? [oneLine(args.doneBy.handle)] : []
|
|
718
|
-
}] : []),
|
|
719
|
-
...args.skill ? [instructions ? `Run the ${args.skill} skill. The instructions below add context for this run.` : `Run the ${args.skill} skill.`] : [],
|
|
720
|
-
...instructions ? [renderChildTag("instructions", escapeClosingTags(creator ? mentionCreator(instructions, oneLine(creator)) : instructions))] : [],
|
|
721
|
-
...guidance ? [guidanceTag(guidance)] : [],
|
|
722
|
-
...trustedSummary ? [renderChildTag("summary", escapeClosingTags(clip(trustedSummary, args.trustedSummaryMaxLength)))] : [],
|
|
723
|
-
...verifiedDetailsTag(args.verifiedDetails),
|
|
724
|
-
...externalTextTag(externalText && clip(externalText, args.externalTextMaxLength), args.source),
|
|
725
|
-
...replyContractLines(args.outcomes)
|
|
726
|
-
]);
|
|
727
|
-
}
|
|
728
|
-
function eventTag(event, index) {
|
|
729
|
-
const trustedSummary = event.trustedSummary?.trim();
|
|
730
|
-
return renderTag("event", {
|
|
731
|
-
index,
|
|
732
|
-
type: event.eventType
|
|
733
|
-
}, [
|
|
734
|
-
...trustedSummary ? [renderChildTag("summary", escapeClosingTags(trustedSummary))] : [],
|
|
735
|
-
...verifiedDetailsTag(event.verifiedDetails),
|
|
736
|
-
...externalTextTag(event.externalText?.trim(), event.source)
|
|
737
|
-
]);
|
|
738
|
-
}
|
|
739
|
-
/**
|
|
740
|
-
* Render one `<task>` for several Watch Events that arrived together.
|
|
741
|
-
*
|
|
742
|
-
* Each `<watch>` group states its instructions once, then lists its Events.
|
|
743
|
-
* Child tags match `renderTaskInput`. The outcome rule appears once, at the
|
|
744
|
-
* end.
|
|
745
|
-
*/
|
|
746
|
-
function renderTaskBatchInput(args) {
|
|
747
|
-
const total = args.groups.reduce((count, group) => count + group.events.length, 0);
|
|
748
|
-
if (total === 0) throw new Error("Task batch requires at least one Event");
|
|
749
|
-
const body = [`You received ${total} ${total === 1 ? "event" : "events"}.`];
|
|
750
|
-
let number = 0;
|
|
751
|
-
for (const group of args.groups) {
|
|
752
|
-
const instructions = group.instructions.trim();
|
|
753
|
-
if (!instructions) throw new Error("Task instructions are required");
|
|
754
|
-
const about = group.about?.trim();
|
|
755
|
-
const people = group.people.map((person) => oneLine(person)).filter(Boolean);
|
|
756
|
-
const numbered = group.events.map((event, index) => ({
|
|
757
|
-
...event,
|
|
758
|
-
number: number + index + 1
|
|
759
|
-
}));
|
|
760
|
-
number += group.events.length;
|
|
761
|
-
const guidance = /* @__PURE__ */ new Map();
|
|
762
|
-
for (const event of group.events) {
|
|
763
|
-
const text = event.guidance?.trim();
|
|
764
|
-
if (text && !guidance.has(event.eventType)) guidance.set(event.eventType, text);
|
|
765
|
-
}
|
|
766
|
-
body.push(renderTag("watch", { about: about ? oneLine(about) : void 0 }, [
|
|
767
|
-
...peopleTags(people, batchDoers(numbered)),
|
|
768
|
-
renderChildTag("instructions", escapeClosingTags(instructions)),
|
|
769
|
-
...guidance.size > 0 ? [guidanceTag([...guidance].map(([eventType, text]) => `- ${eventType}: ${text}`).join("\n"))] : [],
|
|
770
|
-
...numbered.map((event) => eventTag(event, event.number))
|
|
771
|
-
]));
|
|
772
|
-
}
|
|
773
|
-
return renderTag("task", {}, [...body, ...replyContractLines(void 0)]);
|
|
774
|
-
}
|
|
775
|
-
// src/chat/sandbox/snapshot/events.ts
|
|
776
|
-
const WORKSPACE_SNAPSHOT_NAMESPACE = CORE_EVENT_NAMESPACE;
|
|
777
|
-
const WORKSPACE_SNAPSHOT_RESOURCE_TYPE = "workspace_snapshot";
|
|
778
|
-
const WORKSPACE_SNAPSHOT_READY_EVENT = "workspace_snapshot.ready";
|
|
779
|
-
const WORKSPACE_SNAPSHOT_FAILED_EVENT = "workspace_snapshot.failed";
|
|
780
|
-
/**
|
|
781
|
-
* Core catalog entry for Workspace snapshot ready and failed events.
|
|
782
|
-
*
|
|
783
|
-
* Uses the same registration shape as plugins so search, guidance, and tool
|
|
784
|
-
* schemas treat these events like any other resource type. Snapshot finish
|
|
785
|
-
* does not run event-automation ingest, so only watches can use these events.
|
|
786
|
-
*/
|
|
787
|
-
function workspaceSnapshotEvents() {
|
|
788
|
-
return {
|
|
789
|
-
resourceTypes: [{
|
|
790
|
-
type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE,
|
|
791
|
-
supportedEvents: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
|
|
792
|
-
suggestedEvents: []
|
|
793
|
-
}],
|
|
794
|
-
events: {
|
|
795
|
-
[WORKSPACE_SNAPSHOT_READY_EVENT]: {
|
|
796
|
-
reach: "resource",
|
|
797
|
-
guidance: "Call switchWorkspace again with the same Workspace name. Do not create another watch when switchWorkspace already returned a subscription."
|
|
798
|
-
},
|
|
799
|
-
[WORKSPACE_SNAPSHOT_FAILED_EVENT]: {
|
|
800
|
-
reach: "resource",
|
|
801
|
-
guidance: "Report the snapshot failure. Do not keep waiting for this Workspace unless the user asks to retry."
|
|
802
|
-
}
|
|
803
|
-
},
|
|
804
|
-
limits: { [WORKSPACE_SNAPSHOT_RESOURCE_TYPE]: { automation: false } }
|
|
805
|
-
};
|
|
806
|
-
}
|
|
807
|
-
/** Describe the events that report when a snapshot build ends. */
|
|
808
|
-
function workspaceSnapshotWatch(input) {
|
|
809
|
-
return {
|
|
810
|
-
identifier: input.workspaceId,
|
|
811
|
-
label: `Workspace ${input.workspaceName} snapshot`,
|
|
812
|
-
namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
|
|
813
|
-
supported_events: [WORKSPACE_SNAPSHOT_READY_EVENT, WORKSPACE_SNAPSHOT_FAILED_EVENT],
|
|
814
|
-
suggested_events: [],
|
|
815
|
-
type: WORKSPACE_SNAPSHOT_RESOURCE_TYPE
|
|
816
|
-
};
|
|
817
|
-
}
|
|
818
|
-
/** Report that a Workspace snapshot build is ready or failed. */
|
|
819
|
-
function workspaceSnapshotFinishedEvent(input) {
|
|
820
|
-
const occurredAtMs = input.occurredAtMs ?? Date.now();
|
|
821
|
-
const eventType = input.status === "ready" ? WORKSPACE_SNAPSHOT_READY_EVENT : WORKSPACE_SNAPSHOT_FAILED_EVENT;
|
|
822
|
-
const trustedSummary = input.status === "ready" ? "Workspace snapshot is ready." : "Workspace snapshot build failed.";
|
|
823
|
-
const event = {
|
|
824
|
-
eventKey: `${WORKSPACE_SNAPSHOT_NAMESPACE}:${input.workspaceId}:${input.resultId}:${input.status}`,
|
|
825
|
-
eventType,
|
|
826
|
-
identifier: input.workspaceId,
|
|
827
|
-
namespace: WORKSPACE_SNAPSHOT_NAMESPACE,
|
|
828
|
-
occurredAtMs,
|
|
829
|
-
terminal: true,
|
|
830
|
-
trustedSummary,
|
|
831
|
-
data: {
|
|
832
|
-
workspaceId: input.workspaceId,
|
|
833
|
-
status: input.status
|
|
834
|
-
}
|
|
835
|
-
};
|
|
836
|
-
if (input.status === "failed" && input.error) event.untrustedText = input.error;
|
|
837
|
-
return event;
|
|
838
|
-
}
|
|
839
|
-
// src/chat/slack/channel-message-events.ts
|
|
840
|
-
/**
|
|
841
|
-
* Slack channel-message Events for Event automations.
|
|
842
|
-
*
|
|
843
|
-
* Core publishes these Events from Slack ingress, so the `slack` namespace is
|
|
844
|
-
* core owned, like `junior`. Anyone in the channel writes the Event text, so an
|
|
845
|
-
* automation can watch only its own channel and always uses system credentials.
|
|
846
|
-
*/
|
|
847
|
-
/** Core-owned event namespace for Slack Events. Not a plugin publisher. */
|
|
848
|
-
const SLACK_EVENT_NAMESPACE = "slack";
|
|
849
|
-
/** The trigger identifier that names the channel of the automation. */
|
|
850
|
-
const SLACK_CURRENT_CHANNEL_IDENTIFIER = "current_channel";
|
|
851
|
-
const CHANNEL_RESOURCE_TYPE = "channel";
|
|
852
|
-
const MESSAGE_POSTED_EVENT = "message.posted";
|
|
853
|
-
const CHANNEL_ID_PATTERN = /^[CG][A-Z0-9]{2,}$/;
|
|
854
|
-
const CHANNEL_LOCATION = "channel";
|
|
855
|
-
const THREAD_LOCATION = "thread";
|
|
856
|
-
const CHANNEL_MESSAGE_MATCH_FIELDS = eventMatchFieldsSchema.parse({
|
|
857
|
-
channelId: {
|
|
858
|
-
kind: "string",
|
|
859
|
-
description: "Slack channel ID of the message. It is always the channel where the automation posts.",
|
|
860
|
-
events: [MESSAGE_POSTED_EVENT]
|
|
861
|
-
},
|
|
862
|
-
userId: {
|
|
863
|
-
kind: "string",
|
|
864
|
-
description: "Slack user ID of the message author. Required to run on bot posts, such as alert bots."
|
|
865
|
-
},
|
|
866
|
-
location: {
|
|
867
|
-
kind: "string",
|
|
868
|
-
enum: [CHANNEL_LOCATION, THREAD_LOCATION],
|
|
869
|
-
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."
|
|
870
|
-
}
|
|
871
|
-
});
|
|
872
|
-
/**
|
|
873
|
-
* Event registration for new Slack channel messages and thread replies. Only
|
|
874
|
-
* event automations can use it, so watchEvents rejects it.
|
|
875
|
-
*/
|
|
876
|
-
function slackChannelMessageEvents() {
|
|
877
|
-
return {
|
|
878
|
-
resourceTypes: [{
|
|
879
|
-
type: CHANNEL_RESOURCE_TYPE,
|
|
880
|
-
identifier: {
|
|
881
|
-
format: `"${SLACK_CURRENT_CHANNEL_IDENTIFIER}" for the channel where the automation is created`,
|
|
882
|
-
pattern: String.raw`^(?:current_channel|[CG][A-Z0-9]{2,})$`
|
|
883
|
-
},
|
|
884
|
-
supportedEvents: [MESSAGE_POSTED_EVENT],
|
|
885
|
-
suggestedEvents: [],
|
|
886
|
-
matchFields: CHANNEL_MESSAGE_MATCH_FIELDS
|
|
887
|
-
}],
|
|
888
|
-
events: { [MESSAGE_POSTED_EVENT]: {
|
|
889
|
-
reach: { anyOf: ["channelId"] },
|
|
890
|
-
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. 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."
|
|
891
|
-
} },
|
|
892
|
-
limits: { [CHANNEL_RESOURCE_TYPE]: {
|
|
893
|
-
watch: false,
|
|
894
|
-
watchUnavailableMessage: "Slack channel messages can trigger only an event automation in that channel. Use createAutomation with an event trigger."
|
|
895
|
-
} }
|
|
896
|
-
};
|
|
897
|
-
}
|
|
898
|
-
/**
|
|
899
|
-
* Set the `channelId` filter of a Slack channel-message trigger to the
|
|
900
|
-
* channel where the automation posts. A trigger that names another channel,
|
|
901
|
-
* or a saved trigger with an identifier, stays as it is for
|
|
902
|
-
* `requireSlackChannelMessageScope` to check.
|
|
903
|
-
*/
|
|
904
|
-
function slackChannelMessageTrigger(trigger, channelId) {
|
|
905
|
-
if (trigger.namespace !== "slack") return trigger;
|
|
906
|
-
if (trigger.identifier != null || trigger.match?.channelId !== void 0) return trigger;
|
|
907
|
-
return {
|
|
908
|
-
...trigger,
|
|
909
|
-
match: {
|
|
910
|
-
...trigger.match,
|
|
911
|
-
channelId
|
|
912
|
-
}
|
|
913
|
-
};
|
|
914
|
-
}
|
|
915
|
-
/**
|
|
916
|
-
* Bind a Slack channel-message automation to its own channel.
|
|
917
|
-
*
|
|
918
|
-
* The trigger names the channel with a `channelId` filter. A saved trigger
|
|
919
|
-
* can name it with an identifier instead, where `current_channel` means the
|
|
920
|
-
* destination channel. Reject other channels, so private channel text cannot
|
|
921
|
-
* reach another channel.
|
|
922
|
-
*/
|
|
923
|
-
function requireSlackChannelMessageScope(automation) {
|
|
924
|
-
if (automation.trigger.namespace !== "slack") return automation;
|
|
925
|
-
const channelId = automation.destination.channelId;
|
|
926
|
-
if (!CHANNEL_ID_PATTERN.test(channelId)) throw new ToolInputError("A Slack channel-message automation works only in a channel, not in a DM.");
|
|
927
|
-
const { identifier, match } = automation.trigger;
|
|
928
|
-
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.");
|
|
929
|
-
return {
|
|
930
|
-
...automation,
|
|
931
|
-
credentialMode: "system",
|
|
932
|
-
trigger: {
|
|
933
|
-
...automation.trigger,
|
|
934
|
-
...identifier === void 0 ? void 0 : { identifier: channelId }
|
|
935
|
-
}
|
|
936
|
-
};
|
|
937
|
-
}
|
|
938
|
-
/**
|
|
939
|
-
* Build the Event for one new channel message or thread reply, or nothing.
|
|
940
|
-
*
|
|
941
|
-
* Slackbot posts do not count. Bot posts are marked with `postedByBot`, so
|
|
942
|
-
* only automations that name the bot can run on them. Thread replies carry
|
|
943
|
-
* the `thread` location, so only automations that name it can run on them.
|
|
944
|
-
*/
|
|
945
|
-
function slackChannelMessageEvent(input) {
|
|
946
|
-
if (input.userId === "USLACKBOT") return void 0;
|
|
947
|
-
if (!CHANNEL_ID_PATTERN.test(input.channelId)) return void 0;
|
|
948
|
-
const postedByBot = Boolean(input.botId || input.subtype === "bot_message");
|
|
949
|
-
const threadTs = input.threadTs && input.threadTs !== input.ts ? input.threadTs : void 0;
|
|
950
|
-
return {
|
|
951
|
-
eventKey: `${input.channelId}:${input.ts}`,
|
|
952
|
-
eventType: MESSAGE_POSTED_EVENT,
|
|
953
|
-
identifier: input.channelId,
|
|
954
|
-
occurredAtMs: Math.floor(Number(input.ts) * 1e3),
|
|
955
|
-
trustedSummary: `${postedByBot ? "The bot " : ""}<@${input.userId}> posted a new ${threadTs ? `thread reply under message ${threadTs}` : "message"} in <#${input.channelId}>.`,
|
|
956
|
-
data: {
|
|
957
|
-
channelId: input.channelId,
|
|
958
|
-
location: threadTs ? THREAD_LOCATION : CHANNEL_LOCATION,
|
|
959
|
-
messageTs: input.ts,
|
|
960
|
-
...threadTs ? { threadTs } : void 0,
|
|
961
|
-
userId: input.userId,
|
|
962
|
-
...postedByBot ? { postedByBot: true } : void 0
|
|
963
|
-
},
|
|
964
|
-
...input.text?.trim() ? { untrustedText: input.text } : void 0
|
|
965
|
-
};
|
|
966
|
-
}
|
|
967
|
-
/**
|
|
968
|
-
* Decide whether a channel-message Event may run one automation.
|
|
969
|
-
*
|
|
970
|
-
* A message runs only automations that post in its own channel, so private
|
|
971
|
-
* channel text cannot reach another channel. The trigger already names that
|
|
972
|
-
* channel, and this check keeps the rule when it does not.
|
|
973
|
-
* A bot post runs only automations whose match names its author in `userId`.
|
|
974
|
-
* Bots can post often and would use up the run limit of every other
|
|
975
|
-
* automation in the channel. A thread reply runs only automations whose
|
|
976
|
-
* match names the `thread` location, so existing automations stay top-level.
|
|
977
|
-
*/
|
|
978
|
-
function slackChannelMessageRunsAutomation(event, automation) {
|
|
979
|
-
if (event.namespace !== "slack") return true;
|
|
980
|
-
if (event.data?.channelId !== automation.destination.channelId) return false;
|
|
981
|
-
if (event.data?.location === THREAD_LOCATION && ![automation.trigger.match?.location].flat().includes(THREAD_LOCATION)) return false;
|
|
982
|
-
if (event.data?.postedByBot !== true) return true;
|
|
983
|
-
return automation.trigger.match?.userId !== void 0;
|
|
984
|
-
}
|
|
985
|
-
/** Return the source message thread for a channel-message run. */
|
|
986
|
-
function slackChannelMessageReplyThreadTs(event) {
|
|
987
|
-
if (event.namespace !== "slack") return void 0;
|
|
988
|
-
const messageTs = event.data?.threadTs ?? event.data?.messageTs;
|
|
989
|
-
return typeof messageTs === "string" ? messageTs : void 0;
|
|
990
|
-
}
|
|
991
|
-
// src/chat/events/runtime-catalog.ts
|
|
992
|
-
/**
|
|
993
|
-
* Enabled event registrations for search, guidance, and tool schemas.
|
|
994
|
-
*
|
|
995
|
-
* Includes core Workspace snapshot events under the `junior` namespace, Slack
|
|
996
|
-
* channel-message events under the `slack` namespace, plus every enabled plugin
|
|
997
|
-
* registration. Plugins may not use the `junior` or `slack` namespaces.
|
|
998
|
-
*/
|
|
999
|
-
function getEventCatalog() {
|
|
1000
|
-
const snapshot = workspaceSnapshotEvents();
|
|
1001
|
-
const catalog = {
|
|
1002
|
-
[CORE_EVENT_NAMESPACE]: eventCatalogEntry({
|
|
1003
|
-
displayName: botConfig.userName,
|
|
1004
|
-
resourceTypes: [...snapshot.resourceTypes, {
|
|
1005
|
-
type: "timer",
|
|
1006
|
-
supportedEvents: ["timer.fired"],
|
|
1007
|
-
suggestedEvents: []
|
|
1008
|
-
}],
|
|
1009
|
-
events: {
|
|
1010
|
-
...snapshot.events,
|
|
1011
|
-
"timer.fired": { reach: "resource" }
|
|
1012
|
-
},
|
|
1013
|
-
limits: {
|
|
1014
|
-
...snapshot.limits,
|
|
1015
|
-
timer: {
|
|
1016
|
-
automation: false,
|
|
1017
|
-
watch: false,
|
|
1018
|
-
watchUnavailableMessage: "Use watchTimer to create a timer Watch."
|
|
1019
|
-
}
|
|
1020
|
-
}
|
|
1021
|
-
}),
|
|
1022
|
-
[SLACK_EVENT_NAMESPACE]: eventCatalogEntry({
|
|
1023
|
-
...slackChannelMessageEvents(),
|
|
1024
|
-
displayName: "Slack"
|
|
1025
|
-
})
|
|
1026
|
-
};
|
|
1027
|
-
for (const plugin of getPlugins()) {
|
|
1028
|
-
const registration = plugin.events;
|
|
1029
|
-
if (!registration || registration.isEnabled?.() === false) continue;
|
|
1030
|
-
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`);
|
|
1031
|
-
catalog[plugin.manifest.name] = eventCatalogEntry({
|
|
1032
|
-
...registration,
|
|
1033
|
-
displayName: plugin.manifest.displayName
|
|
1034
|
-
});
|
|
1035
|
-
}
|
|
1036
|
-
return catalog;
|
|
1037
|
-
}
|
|
1038
|
-
// src/chat/events/notification.ts
|
|
1039
|
-
const EVENT_WAIT_MS = 3e4;
|
|
1040
|
-
const eventTaskFactsSchema = z.object({
|
|
1041
|
-
about: z.string().optional(),
|
|
1042
|
-
instructions: z.string().min(1),
|
|
1043
|
-
guidance: z.string().optional(),
|
|
1044
|
-
people: z.array(z.string()).optional(),
|
|
1045
|
-
trustedSummary: z.string().optional(),
|
|
1046
|
-
verifiedDetails: z.record(z.string(), z.unknown()).optional(),
|
|
1047
|
-
externalText: z.string().optional(),
|
|
1048
|
-
doneBy: z.object({
|
|
1049
|
-
mention: z.string(),
|
|
1050
|
-
handle: z.string().optional()
|
|
1051
|
-
}).optional()
|
|
1052
|
-
});
|
|
1053
|
-
/**
|
|
1054
|
-
* Collect the task facts for one subscribed Event.
|
|
1055
|
-
*
|
|
1056
|
-
* Keep this short: facts the model cannot reconstruct, plus a one-line handling
|
|
1057
|
-
* contract. Stable delivery rules live in runtime and docs, not this prompt.
|
|
1058
|
-
*/
|
|
1059
|
-
function eventTaskFacts(subscription, event, people = [], doneBy) {
|
|
1060
|
-
const guidance = [eventGuidance(getEventCatalog(), event.namespace, event.eventType), subscription.guidance?.[event.eventType]].filter((text) => Boolean(text?.trim())).join(" ");
|
|
1061
|
-
return {
|
|
1062
|
-
about: subscription.label,
|
|
1063
|
-
instructions: subscription.intent,
|
|
1064
|
-
...guidance ? { guidance } : void 0,
|
|
1065
|
-
...people.length > 0 ? { people: [...people] } : void 0,
|
|
1066
|
-
trustedSummary: event.trustedSummary,
|
|
1067
|
-
...event.data ? { verifiedDetails: event.data } : void 0,
|
|
1068
|
-
...event.untrustedText ? { externalText: event.untrustedText } : void 0,
|
|
1069
|
-
...doneBy ? { doneBy } : void 0
|
|
1070
|
-
};
|
|
1071
|
-
}
|
|
1072
|
-
/** Whether mailbox metadata is a plain event wake. */
|
|
1073
|
-
function isEventMailboxMetadata(value) {
|
|
1074
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1075
|
-
const record = value;
|
|
1076
|
-
if (record.kind !== "event") return false;
|
|
1077
|
-
const event = record.event;
|
|
1078
|
-
if (!event || typeof event !== "object" || Array.isArray(event)) return false;
|
|
1079
|
-
const fields = event;
|
|
1080
|
-
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");
|
|
1081
|
-
}
|
|
1082
|
-
/**
|
|
1083
|
-
* Return the timer creator subject when every event in the batch carries a
|
|
1084
|
-
* valid subject for its own Watch and the same user.
|
|
1085
|
-
*/
|
|
1086
|
-
function timerWatchCredentialSubject(conversationId, messages) {
|
|
1087
|
-
let shared;
|
|
1088
|
-
for (const message of messages) {
|
|
1089
|
-
const metadata = message.input.metadata;
|
|
1090
|
-
if (!isEventMailboxMetadata(metadata)) return void 0;
|
|
1091
|
-
const parsed = credentialSubjectSchema.safeParse(metadata.credentialSubject);
|
|
1092
|
-
if (!parsed.success || !metadata.event.subscriptionId || !verifyTimerWatchCredentialSubject({
|
|
1093
|
-
conversationId,
|
|
1094
|
-
subject: parsed.data,
|
|
1095
|
-
watchId: metadata.event.subscriptionId
|
|
1096
|
-
}) || shared && shared.userId !== parsed.data.userId) return;
|
|
1097
|
-
shared ??= parsed.data;
|
|
1098
|
-
}
|
|
1099
|
-
return shared;
|
|
1100
|
-
}
|
|
1101
|
-
/**
|
|
1102
|
-
* Read the saved Watch task facts from one Event mailbox entry. Entries
|
|
1103
|
-
* without a Watch or saved facts, such as child agent results and input queued
|
|
1104
|
-
* before facts were saved, return undefined and keep their own text.
|
|
1105
|
-
*/
|
|
1106
|
-
function readEventTaskFacts(message) {
|
|
1107
|
-
const metadata = message.input.metadata;
|
|
1108
|
-
if (!isEventMailboxMetadata(metadata)) return void 0;
|
|
1109
|
-
const watchId = metadata.event.subscriptionId;
|
|
1110
|
-
if (!watchId) return void 0;
|
|
1111
|
-
const parsed = eventTaskFactsSchema.safeParse(metadata.task);
|
|
1112
|
-
return parsed.success ? {
|
|
1113
|
-
facts: parsed.data,
|
|
1114
|
-
metadata,
|
|
1115
|
-
watchId
|
|
1116
|
-
} : void 0;
|
|
1117
|
-
}
|
|
1118
|
-
/**
|
|
1119
|
-
* Write the agent inputs for an Event batch, one prompt content part each.
|
|
1120
|
-
*
|
|
1121
|
-
* One Event keeps its own text. Several Watch Events become one `<task>`
|
|
1122
|
-
* with one group per Watch, so shared instructions appear once. Entries
|
|
1123
|
-
* without task facts, such as child agent results, keep their own text as
|
|
1124
|
-
* their own inputs after the task. `rendered` replaces the text of an entry
|
|
1125
|
-
* by inbound message id, such as a person change to a Review item.
|
|
1126
|
-
*/
|
|
1127
|
-
function renderEventBatchInputs(messages, rendered = /* @__PURE__ */ new Map()) {
|
|
1128
|
-
const groups = /* @__PURE__ */ new Map();
|
|
1129
|
-
const others = [];
|
|
1130
|
-
for (const message of messages) {
|
|
1131
|
-
const saved = readEventTaskFacts(message);
|
|
1132
|
-
if (!saved) {
|
|
1133
|
-
others.push(message);
|
|
1134
|
-
continue;
|
|
1135
|
-
}
|
|
1136
|
-
const { facts, metadata, watchId } = saved;
|
|
1137
|
-
let group = groups.get(watchId);
|
|
1138
|
-
if (!group) {
|
|
1139
|
-
group = {
|
|
1140
|
-
about: facts.about,
|
|
1141
|
-
instructions: facts.instructions,
|
|
1142
|
-
people: [],
|
|
1143
|
-
events: []
|
|
1144
|
-
};
|
|
1145
|
-
groups.set(watchId, group);
|
|
1146
|
-
}
|
|
1147
|
-
for (const person of facts.people ?? []) if (!group.people.includes(person)) group.people.push(person);
|
|
1148
|
-
group.events.push({
|
|
1149
|
-
eventType: metadata.event.eventType,
|
|
1150
|
-
guidance: facts.guidance,
|
|
1151
|
-
source: metadata.event.namespace,
|
|
1152
|
-
trustedSummary: facts.trustedSummary,
|
|
1153
|
-
verifiedDetails: facts.verifiedDetails,
|
|
1154
|
-
externalText: facts.externalText,
|
|
1155
|
-
doneBy: facts.doneBy
|
|
1156
|
-
});
|
|
1157
|
-
}
|
|
1158
|
-
const ownText = (message) => rendered.get(message.inboundMessageId) ?? message.input.text.trim();
|
|
1159
|
-
if (messages.length - others.length < 2) return messages.map(ownText).filter(Boolean);
|
|
1160
|
-
return [renderTaskBatchInput({ groups: [...groups.values()] }), ...others.map(ownText).filter(Boolean)];
|
|
1161
|
-
}
|
|
1162
|
-
/** Return the conversation message entry for one Event input. */
|
|
1163
|
-
function messageEvent(message) {
|
|
1164
|
-
const metadata = message.input.metadata;
|
|
1165
|
-
if (!isEventMailboxMetadata(metadata)) return [];
|
|
1166
|
-
const label = readEventTaskFacts(message)?.facts.about;
|
|
1167
|
-
return [{
|
|
1168
|
-
eventType: metadata.event.eventType,
|
|
1169
|
-
...label ? { label } : void 0,
|
|
1170
|
-
...metadata.event.objectType ? { objectType: metadata.event.objectType } : void 0,
|
|
1171
|
-
...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0
|
|
1172
|
-
}];
|
|
1173
|
-
}
|
|
1174
|
-
/**
|
|
1175
|
-
* Return the saved Message fields for the Event inputs of one Turn.
|
|
1176
|
-
*
|
|
1177
|
-
* A person change to a Review item is not one of the Message's own Events:
|
|
1178
|
-
* its record goes to `reviewItemChanges`, and the dashboard shows it as a
|
|
1179
|
-
* change row. The Message's own Event is its first Watch Event, the
|
|
1180
|
-
* kind the task message counts, or else its first other input, such as an
|
|
1181
|
-
* agent result. `events` lists the Watch Events when several arrived. When
|
|
1182
|
-
* changes share the Message with one own Event, `events` lists that Event, so
|
|
1183
|
-
* a reader can tell it from a Message that only records changes.
|
|
1184
|
-
*/
|
|
1185
|
-
function eventBatchMessageMeta(messages) {
|
|
1186
|
-
const reviewItemChanges = messages.flatMap((message) => message.input.reviewItemChange ? [message.input.reviewItemChange] : []);
|
|
1187
|
-
const own = messages.filter((message) => !message.input.reviewItemChange);
|
|
1188
|
-
const watched = own.filter((message) => readEventTaskFacts(message));
|
|
1189
|
-
const primary = watched[0] ?? own[0];
|
|
1190
|
-
const metadata = (primary ?? messages[0])?.input.metadata;
|
|
1191
|
-
if (!isEventMailboxMetadata(metadata)) return {};
|
|
1192
|
-
const events = watched.length > 1 ? watched.flatMap(messageEvent) : reviewItemChanges.length && primary ? messageEvent(primary) : [];
|
|
1193
|
-
return {
|
|
1194
|
-
eventType: metadata.event.eventType,
|
|
1195
|
-
eventNamespace: metadata.event.namespace,
|
|
1196
|
-
eventObjectType: metadata.event.objectType,
|
|
1197
|
-
...metadata.event.trustedSummary ? { trustedSummary: metadata.event.trustedSummary } : void 0,
|
|
1198
|
-
...events.length ? { events } : void 0,
|
|
1199
|
-
...reviewItemChanges.length ? { reviewItemChanges } : void 0
|
|
1200
|
-
};
|
|
1201
|
-
}
|
|
1202
|
-
/** Build plain conversation mailbox input for one matched watch. */
|
|
1203
|
-
function createEventInboundMessage(input) {
|
|
1204
|
-
const metadata = {
|
|
1205
|
-
kind: "event",
|
|
1206
|
-
...input.task ? { task: input.task } : void 0,
|
|
1207
|
-
...input.subscription.credentialSubject ? { credentialSubject: input.subscription.credentialSubject } : void 0,
|
|
1208
|
-
event: {
|
|
1209
|
-
eventKey: input.event.eventKey,
|
|
1210
|
-
eventType: input.event.eventType,
|
|
1211
|
-
namespace: input.event.namespace,
|
|
1212
|
-
identifier: input.event.identifier,
|
|
1213
|
-
subscriptionId: input.subscription.id,
|
|
1214
|
-
trustedSummary: input.event.trustedSummary,
|
|
1215
|
-
objectType: input.event.objectType
|
|
1216
|
-
}
|
|
1217
|
-
};
|
|
1218
|
-
return {
|
|
1219
|
-
conversationId: input.subscription.conversationId,
|
|
1220
|
-
createdAtMs: input.event.occurredAtMs,
|
|
1221
|
-
inboundMessageId: `event:${input.subscription.id}:${input.event.eventKey}`,
|
|
1222
|
-
delivery: "defer",
|
|
1223
|
-
source: "event",
|
|
1224
|
-
receivedAtMs: input.receivedAtMs ?? Date.now(),
|
|
1225
|
-
input: {
|
|
1226
|
-
text: input.text,
|
|
1227
|
-
authorId: EVENT_AUTHOR_ID,
|
|
1228
|
-
authorIdentityId: SYSTEM_IDENTITY_ID,
|
|
1229
|
-
metadata
|
|
1230
|
-
}
|
|
1231
|
-
};
|
|
1232
|
-
}
|
|
1233
|
-
/**
|
|
1234
|
-
* Enqueue a event as normal conversation mailbox input.
|
|
1235
|
-
*
|
|
1236
|
-
* The watch only names the conversation. Destination stays on the conversation
|
|
1237
|
-
* and is applied when the worker runs. After too many automated Turns with no
|
|
1238
|
-
* user Turn, later wakes stay quiet until a user message clears the pause.
|
|
1239
|
-
*/
|
|
1240
|
-
async function enqueueEventNotification(args) {
|
|
1241
|
-
const maxTurns = botConfig.maxConsecutiveAutomatedTurns;
|
|
1242
|
-
const decision = await admitAutomatedTurn({
|
|
1243
|
-
conversationId: args.subscription.conversationId,
|
|
1244
|
-
maxTurns,
|
|
1245
|
-
nowMs: args.event.occurredAtMs,
|
|
1246
|
-
state: args.state
|
|
1247
|
-
});
|
|
1248
|
-
if (decision.status === "paused") {
|
|
1249
|
-
logInfo("events.automated_turn_limit.paused", {
|
|
1250
|
-
conversationId: args.subscription.conversationId,
|
|
1251
|
-
"app.automated_turn_limit.consecutive": decision.consecutiveAutomatedTurns,
|
|
1252
|
-
"app.automated_turn_limit.max": maxTurns,
|
|
1253
|
-
"app.event.event_type": args.event.eventType,
|
|
1254
|
-
"app.event.namespace": args.event.namespace
|
|
1255
|
-
});
|
|
1256
|
-
if (decision.shouldPostNotice) await postAutomatedTurnLimitNoticeForConversation({
|
|
1257
|
-
conversationId: args.subscription.conversationId,
|
|
1258
|
-
maxTurns,
|
|
1259
|
-
nowMs: args.event.occurredAtMs
|
|
1260
|
-
});
|
|
1261
|
-
return { status: "duplicate" };
|
|
1262
|
-
}
|
|
1263
|
-
const task = eventTaskFacts(args.subscription, args.event, args.people, args.doneBy);
|
|
1264
|
-
return await appendAndEnqueueInboundMessage({
|
|
1265
|
-
message: createEventInboundMessage({
|
|
1266
|
-
event: args.event,
|
|
1267
|
-
subscription: {
|
|
1268
|
-
conversationId: args.subscription.conversationId,
|
|
1269
|
-
credentialSubject: args.subscription.credentialSubject,
|
|
1270
|
-
id: args.subscription.id
|
|
1271
|
-
},
|
|
1272
|
-
task,
|
|
1273
|
-
text: renderTaskInput({
|
|
1274
|
-
...task,
|
|
1275
|
-
event: args.event.eventType,
|
|
1276
|
-
source: args.event.namespace
|
|
1277
|
-
})
|
|
1278
|
-
}),
|
|
1279
|
-
queue: args.queue,
|
|
1280
|
-
queueDelayMs: EVENT_WAIT_MS,
|
|
1281
|
-
state: args.state
|
|
1282
|
-
});
|
|
1283
|
-
}
|
|
1284
|
-
export { renderSlackObjectCard as C, resetAutomatedTurnLimit as E, sendSlackReply as S, recordFinishedTurnForAutomatedLimit as T, workspaceSnapshotWatch as _, renderEventBatchInputs as a, postAutomatedTurnLimitNoticeForConversation as b, SLACK_EVENT_NAMESPACE as c, slackChannelMessageReplyThreadTs as d, slackChannelMessageRunsAutomation as f, workspaceSnapshotFinishedEvent as g, WORKSPACE_SNAPSHOT_READY_EVENT as h, isEventMailboxMetadata as i, requireSlackChannelMessageScope as l, WORKSPACE_SNAPSHOT_FAILED_EVENT as m, enqueueEventNotification as n, timerWatchCredentialSubject as o, slackChannelMessageTrigger as p, eventBatchMessageMeta as r, getEventCatalog as s, EVENT_WAIT_MS as t, slackChannelMessageEvent as u, renderTaskInput as v, admitAutomatedTurn as w, resolveSlackReplyTarget as x, maybePostAutomatedTurnLimitNotice as y };
|