Skip to content

Commit dbc2356

Browse files
sjf-oasjf
andauthored
feat(slack): make presence event guidance configurable (#123875)
* feat(slack): make presence event guidance configurable * chore(config): regenerate channel metadata * fix(slack): keep presence prompt SDK compatible * chore(config): refresh config baseline * fix(slack): cap presence event prompts * chore(config): refresh Slack prompt metadata * fix(slack): bound queued presence wake prompts * fix(slack): inherit presence prompt for named accounts * fix(slack): keep prompt limit at config boundary --------- Co-authored-by: Sarah Fortune <[email protected]>
1 parent 50f656f commit dbc2356

12 files changed

Lines changed: 188 additions & 28 deletions
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"core": 2312,
3-
"channel": 3575,
3+
"channel": 3580,
44
"plugin": 3997
55
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
617f7a9ff716a0d79aaaf779905c37e4470d647459f13ceb14791d9cbb4df747 config-baseline.json
2-
3a5d877e6697388e8b61e5a9e539a1fad7113118453276fe24fb6772abaeae97 config-baseline.core.json
3-
1144184911193a239dd0e6415335a2a95771af27c4b1f5974e64851d6b2ed65d config-baseline.channel.json
4-
250f573a93619d8a2f554028288af84551e572ef8bfdc820a43024572b55175a config-baseline.plugin.json
1+
6eb922009d94d4b8fc655a628659f2d22cbcdd38d3328de582339882010fe0f2 config-baseline.json
2+
cabdc50413431567332b4a39ce3b7eb3cafb1e7dfe87dc42030f2c413ca17358 config-baseline.core.json
3+
1a18ca1f2c5970a1af9b3b6748fc62fdb2e83a4ec524b8de84f7ccd019159e9c config-baseline.channel.json
4+
4b39b54a95764ce438d74e2bbeb2f4c2e813f3dfeaa91befbcff01dba46296a2 config-baseline.plugin.json

‎docs/channels/slack.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1906,7 +1906,10 @@ Slack does not send presence changes through the Events API or Socket Mode. Open
19061906
{
19071907
channels: {
19081908
slack: {
1909-
presenceEvents: { mode: "auto" },
1909+
presenceEvents: {
1910+
mode: "auto",
1911+
prompt: "Do not send a greeting. Stay silent.",
1912+
},
19101913
channels: {
19111914
C0123456789: { presenceEvents: { mode: "on" } },
19121915
C0987654321: { presenceEvents: { mode: "off" } },
@@ -1924,6 +1927,8 @@ OpenClaw polls at most 45 unique workspace-user pairs per minute per Slack accou
19241927

19251928
The event includes `observed_away_at_ms`, `observed_active_at_ms`, and `observed_away_duration_ms`. The duration is the elapsed time between the first sampled `away` state in the current monitor run and the later sampled `active` state. It is not exact time away because presence can change between polls, and the observation starts fresh after the monitor restarts or the target expires. The event records what Slack reported, not whether the person was at their keyboard; Slack can mark someone away automatically or manually, and `users.getPresence` does not distinguish those cases for another user.
19261929

1930+
`presenceEvents.prompt` replaces the default greeting guidance after the event facts. The account-level value applies by default, and `channels.<channel-id>.presenceEvents.prompt` can override it for one channel. The custom value is included verbatim and is limited to 20,000 characters, matching the default per-file `AGENTS.md` bootstrap limit. Set it to an empty string to omit event-specific guidance and let workspace instructions such as `AGENTS.md` decide how to handle the event. The presence facts are always included.
1931+
19271932
The bot token needs `users:read`, which is already included in the recommended manifest. Enterprise Grid org-wide installs create a workspace-scoped polling client only after an authorized event identifies that workspace; presence state, cooldowns, and delivery targets remain partitioned by workspace.
19281933

19291934
## Configuration reference
@@ -1937,7 +1942,7 @@ Primary reference: [Configuration reference - Slack](/gateway/config-channels#sl
19371942
- compatibility toggle: `dangerouslyAllowNameMatching` (break-glass; keep off unless needed)
19381943
- channel access: `groupPolicy`, `channels.*`, `channels.*.users`, `channels.*.requireMention`, `implicitMentions.*`
19391944
- threading/history: `replyToMode`, `replyToModeByChatType`, `thread.*`, `historyLimit`, `dmHistoryLimit`, `dms.*.historyLimit`
1940-
- presence wakes: `presenceEvents.mode`, `channels.*.presenceEvents.mode` (`off|auto|on`; default `off`)
1945+
- presence wakes: `presenceEvents.mode`, `presenceEvents.prompt`, `channels.*.presenceEvents.*` (`off|auto|on`; default `off`)
19411946
- delivery: `textChunkLimit`, `streaming.chunkMode`, `mediaMaxMb`, `streaming`, `streaming.nativeTransport`, `streaming.preview.toolProgress`
19421947
- unfurls: `unfurlLinks` (default: `false`), `unfurlMedia` for `chat.postMessage` link/media preview control; set `unfurlLinks: true` to opt back into link previews
19431948
- ops/features: `configWrites`, `commands.native`, `slashCommand.*`, `actions.*`, `userToken`, `userTokenReadOnly`

‎extensions/slack/src/accounts.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,36 @@ describe("resolveSlackAccount allowFrom precedence", () => {
282282
});
283283
});
284284

285+
it("inherits the top-level presence prompt when an account overrides only the mode", () => {
286+
const resolved = resolveSlackAccount({
287+
cfg: {
288+
channels: {
289+
slack: {
290+
presenceEvents: {
291+
mode: "auto",
292+
prompt: "Use the account owner's workspace guidance.",
293+
},
294+
accounts: {
295+
work: {
296+
botToken: "xoxb-work",
297+
appToken: "xapp-work",
298+
presenceEvents: {
299+
mode: "on",
300+
},
301+
},
302+
},
303+
},
304+
},
305+
},
306+
accountId: "work",
307+
});
308+
309+
expect(resolved.config.presenceEvents).toEqual({
310+
mode: "on",
311+
prompt: "Use the account owner's workspace guidance.",
312+
});
313+
});
314+
285315
it("merges canonical account streaming over top-level defaults field-by-field", () => {
286316
const resolved = resolveSlackAccount({
287317
cfg: {

‎extensions/slack/src/accounts.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ const {
6565
resolveDefaultAccountId,
6666
resolveAccountConfig: resolveMergedSlackAccountConfig,
6767
} = createAccountListHelpers<SlackAccountConfig>("slack", {
68-
nestedObjectKeys: ["botLoopProtection", "relay"],
68+
nestedObjectKeys: ["botLoopProtection", "presenceEvents", "relay"],
6969
hasImplicitDefaultAccount: (cfg) => {
7070
const slack = cfg.channels?.slack;
7171
if (slack?.postAs === "user") {

‎extensions/slack/src/config-schema.test.ts‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,32 @@ describe("slack config schema", () => {
157157
if (absent.success) {
158158
expect(absent.data.presenceEvents).toBeUndefined();
159159
}
160-
expectSlackConfigValid({ presenceEvents: { mode: "auto" } });
160+
expectSlackConfigValid({ presenceEvents: { mode: "auto", prompt: "Do not greet." } });
161161
expectSlackConfigValid({
162-
accounts: { ops: { presenceEvents: { mode: "on" } } },
163-
channels: { C123: { presenceEvents: { mode: "off" } } },
162+
accounts: { ops: { presenceEvents: { mode: "on", prompt: "Account guidance" } } },
163+
channels: { C123: { presenceEvents: { mode: "off", prompt: "" } } },
164164
});
165165
expectSlackConfigIssue({ presenceEvents: { mode: "enabled" } }, "presenceEvents.mode");
166+
expectSlackConfigIssue({ presenceEvents: { prompt: false } }, "presenceEvents.prompt");
167+
});
168+
169+
it("caps presence event prompts at the AGENTS.md bootstrap limit", () => {
170+
const maxPrompt = "x".repeat(20_000);
171+
const oversizedPrompt = `${maxPrompt}x`;
172+
173+
expectSlackConfigValid({ presenceEvents: { prompt: maxPrompt } });
174+
expectSlackConfigIssue(
175+
{ presenceEvents: { prompt: oversizedPrompt } },
176+
"presenceEvents.prompt",
177+
);
178+
expectSlackConfigIssue(
179+
{ accounts: { ops: { presenceEvents: { prompt: oversizedPrompt } } } },
180+
"accounts.ops.presenceEvents.prompt",
181+
);
182+
expectSlackConfigIssue(
183+
{ channels: { C123: { presenceEvents: { prompt: oversizedPrompt } } } },
184+
"channels.C123.presenceEvents.prompt",
185+
);
166186
});
167187

168188
it("accepts historyLimit overrides per account", () => {

‎extensions/slack/src/config-schema.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ import { z } from "zod";
2222
import { slackChannelConfigUiHints } from "./config-ui-hints.js";
2323

2424
const SecretInputSchema = buildSecretInputSchema();
25+
// Match the default per-file AGENTS.md bootstrap budget so one presence wake
26+
// cannot inject more operator guidance than a normal workspace instruction file.
27+
const SLACK_PRESENCE_EVENT_PROMPT_MAX_CHARS = 20_000;
2528

2629
const SlackStreamingProgressSchema = ChannelStreamingProgressSchema.extend({
2730
nativeTaskCards: z.boolean().optional(),
@@ -41,6 +44,7 @@ const SlackDmSchema = z
4144
const SlackPresenceEventsSchema = z
4245
.object({
4346
mode: z.enum(["off", "auto", "on"]).optional(),
47+
prompt: z.string().max(SLACK_PRESENCE_EVENT_PROMPT_MAX_CHARS).optional(),
4448
})
4549
.strict();
4650

‎extensions/slack/src/config-ui-hints.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,18 @@ export const slackChannelConfigUiHints = {
107107
label: "Slack Presence Event Mode",
108108
help: '"off" disables polling; "auto" covers DMs, MPIMs, and recent threads with up to 8 observed people; "on" also covers larger threads and top-level channels.',
109109
},
110+
"presenceEvents.prompt": {
111+
label: "Slack Presence Event Prompt",
112+
help: "Replace the default greeting guidance appended after presence facts. Use an empty string to omit event-specific guidance and let workspace instructions such as AGENTS.md govern behavior. Maximum: 20,000 characters.",
113+
},
110114
"channels.*.presenceEvents.mode": {
111115
label: "Slack Channel Presence Event Mode",
112116
help: 'Override presence events for one Slack channel. Use "on" to include large threads or top-level channel sessions.',
113117
},
118+
"channels.*.presenceEvents.prompt": {
119+
label: "Slack Channel Presence Event Prompt",
120+
help: "Override the account-level presence-event prompt for one Slack channel. Maximum: 20,000 characters.",
121+
},
114122
"execApprovals.enabled": {
115123
label: "Slack Exec Approvals Enabled",
116124
help: 'Controls Slack native exec approvals for this account: unset or "auto" enables DM-first native approvals when approvers can be resolved, true forces native approvals on, and false disables them.',

‎extensions/slack/src/monitor/presence-monitor.test.ts‎

Lines changed: 77 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ function createPrepared(params: {
4040
channelType?: "im" | "mpim" | "channel" | "group";
4141
threadId?: string;
4242
mode?: "off" | "auto" | "on";
43+
prompt?: string;
4344
sessionKey?: string;
4445
}): PreparedSlackMessage {
4546
const channelId = params.channelId ?? "D123";
@@ -57,13 +58,17 @@ function createPrepared(params: {
5758
accountId: "default",
5859
sessionKey: params.sessionKey ?? `agent:main:slack:channel:${channelId}`,
5960
},
60-
channelConfig: params.mode
61-
? {
62-
allowed: true,
63-
requireMention: false,
64-
presenceEvents: { mode: params.mode },
65-
}
66-
: null,
61+
channelConfig:
62+
params.mode || params.prompt !== undefined
63+
? {
64+
allowed: true,
65+
requireMention: false,
66+
presenceEvents: {
67+
...(params.mode ? { mode: params.mode } : {}),
68+
...(params.prompt !== undefined ? { prompt: params.prompt } : {}),
69+
},
70+
}
71+
: null,
6772
ctxPayload: {
6873
MessageThreadId: params.threadId,
6974
},
@@ -83,6 +88,71 @@ describe("Slack presence monitor", () => {
8388
).toBe(true);
8489
});
8590

91+
it("replaces only the default guidance with a configured prompt", async () => {
92+
let now = 2_000;
93+
const getPresence = vi
94+
.fn()
95+
.mockResolvedValueOnce({ presence: "away" })
96+
.mockResolvedValueOnce({ presence: "active" });
97+
const enqueue = vi.fn((..._args: unknown[]) => true);
98+
const monitor = createSlackPresenceMonitor({
99+
accountId: "default",
100+
accountConfig: { mode: "auto", prompt: "Account guidance" },
101+
client: { getPresence } as never,
102+
cooldownStore: createCooldownStore(),
103+
enqueue,
104+
wake: vi.fn(),
105+
nowMs: () => now,
106+
});
107+
monitor.observe(
108+
createPrepared({ userId: "U123", mode: "auto", prompt: "Do not send a greeting." }),
109+
);
110+
111+
await monitor.pollOnce();
112+
now = 7_500;
113+
await monitor.pollOnce();
114+
115+
expect(enqueue.mock.calls[0]?.[0]).toBe(
116+
[
117+
"Slack presence event:",
118+
'A human participant became active on Slack after being observed away: user_id="U123" channel_id="D123".',
119+
"observed_away_at_ms=2000 observed_active_at_ms=7500 observed_away_duration_ms=5500",
120+
"Do not send a greeting.",
121+
].join("\n"),
122+
);
123+
});
124+
125+
it("allows empty prompt guidance so workspace instructions govern the event", async () => {
126+
let now = 2_000;
127+
const getPresence = vi
128+
.fn()
129+
.mockResolvedValueOnce({ presence: "away" })
130+
.mockResolvedValueOnce({ presence: "active" });
131+
const enqueue = vi.fn((..._args: unknown[]) => true);
132+
const monitor = createSlackPresenceMonitor({
133+
accountId: "default",
134+
accountConfig: { mode: "auto", prompt: "Account guidance" },
135+
client: { getPresence } as never,
136+
cooldownStore: createCooldownStore(),
137+
enqueue,
138+
wake: vi.fn(),
139+
nowMs: () => now,
140+
});
141+
monitor.observe(createPrepared({ userId: "U123", mode: "auto", prompt: "" }));
142+
143+
await monitor.pollOnce();
144+
now = 7_500;
145+
await monitor.pollOnce();
146+
147+
expect(enqueue.mock.calls[0]?.[0]).toBe(
148+
[
149+
"Slack presence event:",
150+
'A human participant became active on Slack after being observed away: user_id="U123" channel_id="D123".',
151+
"observed_away_at_ms=2000 observed_active_at_ms=7500 observed_away_duration_ms=5500",
152+
].join("\n"),
153+
);
154+
});
155+
86156
it("seeds the first sample and wakes only on away-to-active", async () => {
87157
let now = 1_000;
88158
const getPresence = vi

‎extensions/slack/src/monitor/presence-monitor.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,22 @@ const SLACK_PRESENCE_AUTO_MAX_PARTICIPANTS = 8;
1515
const SLACK_PRESENCE_TARGET_TTL_MS = 24 * 60 * 60 * 1000;
1616
const SLACK_PRESENCE_MAX_POLLS_PER_INTERVAL = 45;
1717
const SLACK_PRESENCE_MAX_TARGETS = 2_000;
18+
const DEFAULT_SLACK_PRESENCE_EVENT_PROMPT = [
19+
"Before greeting, retrieve relevant memory and wiki context for this immutable user_id, including a known timezone when available. Use their local time; if their timezone is unknown, do not guess.",
20+
"Send at most one short, natural greeting in this Slack conversation. Do not reveal private memory. If no greeting is appropriate, stay silent.",
21+
];
1822

19-
type SlackPresenceEventsConfig = NonNullable<SlackAccountConfig["presenceEvents"]>;
23+
type SlackPresenceEventsConfig = NonNullable<SlackAccountConfig["presenceEvents"]> & {
24+
prompt?: string;
25+
};
2026
type SlackPresenceEventsMode = NonNullable<SlackPresenceEventsConfig["mode"]>;
2127
type PresenceObservation = { presence: "active" } | { presence: "away"; firstObservedAtMs: number };
2228

2329
type PresenceTarget = {
2430
key: string;
2531
teamId?: string;
2632
mode: Exclude<SlackPresenceEventsMode, "off">;
33+
prompt: string | undefined;
2734
channelId: string;
2835
threadId?: string;
2936
to: string;
@@ -51,6 +58,13 @@ function resolveMode(
5158
return channelConfig?.mode ?? accountConfig?.mode ?? "off";
5259
}
5360

61+
function resolvePrompt(
62+
channelConfig: SlackPresenceEventsConfig | undefined,
63+
accountConfig: SlackPresenceEventsConfig | undefined,
64+
): string | undefined {
65+
return channelConfig?.prompt ?? accountConfig?.prompt;
66+
}
67+
5468
export function hasSlackPresenceEventsEnabled(params: {
5569
account?: SlackPresenceEventsConfig;
5670
channels?: Record<string, { presenceEvents?: SlackPresenceEventsConfig } | undefined>;
@@ -80,12 +94,17 @@ function formatSlackPresenceEvent(
8094
): string {
8195
const { observedAwayAtMs, observedActiveAtMs } = awayObservation;
8296
const observedAwayDurationMs = Math.max(0, observedActiveAtMs - observedAwayAtMs);
97+
const promptLines =
98+
target.prompt === undefined
99+
? DEFAULT_SLACK_PRESENCE_EVENT_PROMPT
100+
: target.prompt.length > 0
101+
? [target.prompt]
102+
: [];
83103
const lines = [
84104
"Slack presence event:",
85105
`A human participant became active on Slack after being observed away: user_id=${JSON.stringify(userId)}${target.teamId ? ` team_id=${JSON.stringify(target.teamId)}` : ""} channel_id=${JSON.stringify(target.channelId)}${target.threadId ? ` thread_ts=${JSON.stringify(target.threadId)}` : ""}.`,
86106
`observed_away_at_ms=${observedAwayAtMs} observed_active_at_ms=${observedActiveAtMs} observed_away_duration_ms=${observedAwayDurationMs}`,
87-
"Before greeting, retrieve relevant memory and wiki context for this immutable user_id, including a known timezone when available. Use their local time; if their timezone is unknown, do not guess.",
88-
"Send at most one short, natural greeting in this Slack conversation. Do not reveal private memory. If no greeting is appropriate, stay silent.",
107+
...promptLines,
89108
];
90109
return lines.join("\n");
91110
}
@@ -128,6 +147,7 @@ function resolveObservedTarget(params: {
128147
key: `${teamId ? `team:${teamId}:` : ""}${channelId}${targetSuffix}`,
129148
...(teamId ? { teamId } : {}),
130149
mode,
150+
prompt: resolvePrompt(prepared.channelConfig?.presenceEvents, params.accountConfig),
131151
channelId,
132152
threadId,
133153
to: formatSlackTarget({
@@ -215,6 +235,7 @@ export function createSlackPresenceMonitor(params: {
215235
const current = targets.get(observed.key);
216236
if (current) {
217237
current.mode = observed.mode;
238+
current.prompt = observed.prompt;
218239
current.sessionKey = observed.sessionKey;
219240
current.agentId = observed.agentId;
220241
current.to = observed.to;

0 commit comments

Comments
 (0)