Multiplayer agent harness for work.
Slack: typed codes and fields instead of string matching (regex burndown: slack) (#2446)
Regan Bell0e0ab72e1e9c
diff --git a/src/api/app-turn.ts b/src/api/app-turn.tsindex 752e1a0ab..b63ae7136 100644--- a/src/api/app-turn.ts+++ b/src/api/app-turn.ts@@ -116,7 +116,11 @@ export function createTurnMethods(await deps.identity.refresh();const actor: Principal = deps.identity.resolve(req.actor);if (!deps.identity.isInternal(actor)) {- return { status: "refused", reason: "internal-only: non-internal principals cannot interact" };+ return {+ status: "refused",+ refusalKind: "internal_only",+ reason: "internal-only: non-internal principals cannot interact",+ };}let projectAudience: Principal[] | undefined;let projectName: string | undefined;diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.tsindex e8c0f83e8..fdf1470dd 100644--- a/src/api/slack-core-client.ts+++ b/src/api/slack-core-client.ts@@ -131,7 +131,7 @@ export interface SlackCoreClient {threadTs?: string;text?: string;senderEmail?: string;- isDirectMessage?: boolean;+ isDirectMessage: boolean;}): Promise<void>;}diff --git a/src/connectors/emoji-upload-service.ts b/src/connectors/emoji-upload-service.tsindex 9fb80f4ae..84e860c08 100644--- a/src/connectors/emoji-upload-service.ts+++ b/src/connectors/emoji-upload-service.ts@@ -1,5 +1,6 @@import type { BrowserSessionStore } from "./browser-session-store.ts";import { errMessage, swallowAs } from "../util/errors.ts";+import { SLACK_AUTH_ERRORS } from "../slack/payloads.ts";const EMOJI_NAME_RE = /^[a-z0-9_'+-]{1,100}$/;@@ -56,13 +57,12 @@ const EMOJI_UPLOAD_NO_SESSION =export const EMOJI_UPLOAD_SESSION_EXPIRED ="The Slack session for the emoji uploader has expired — an operator needs to sign in to Slack again to refresh it.";-const AUTH_ERRORS = new Set(["not_authed", "invalid_auth", "token_expired", "token_revoked", "account_inactive"]);const PERMISSION_ERRORS = new Set(["no_permission", "missing_scope", "restricted_action", "user_is_restricted"]);const TOO_BIG_ERRORS = new Set(["resized_but_still_too_large", "error_too_big", "too_large"]);function humanizeEmojiError(err: string | undefined): string {if (!err) return "the emoji upload failed.";- if (AUTH_ERRORS.has(err)) return EMOJI_UPLOAD_SESSION_EXPIRED;+ if (SLACK_AUTH_ERRORS.has(err)) return EMOJI_UPLOAD_SESSION_EXPIRED;if (PERMISSION_ERRORS.has(err)) return "the uploader account isn't allowed to add custom emoji in this workspace.";if (TOO_BIG_ERRORS.has(err))return "the image is too large — use a smaller square PNG or GIF (Slack's limit is 128×128 and 128KB).";diff --git a/src/core/approval-store.ts b/src/core/approval-store.tsindex 22539b804..7c204008a 100644--- a/src/core/approval-store.ts+++ b/src/core/approval-store.ts@@ -13,12 +13,6 @@ export function approvalDeliveryRecipient(actor: { externalId?: string } | undefreturn id && !id.startsWith("system:") ? id : undefined;}-function dmThreadTs(request: NonNullable<PendingApprovalRecord["request"]>): string | undefined {- if (request.conversation?.kind !== "dm" || !request.deliveryTarget) return undefined;- const [channel, threadTs] = request.deliveryTarget.split(":");- return channel?.startsWith("D") && threadTs ? threadTs : undefined;-}-export function createApprovalStore(backing: DurableMap<PendingApprovalRecord>,deliveries: Pick<DeliveryStore, "enqueue">,@@ -27,7 +21,7 @@ export function createApprovalStore(if (record.request?.surface !== "slack") return;const actorId = approvalDeliveryRecipient(record.request.actor);if (!actorId) return;- const threadTs = dmThreadTs(record.request);+ const threadTs = record.request.conversation?.kind === "dm" ? record.request.slackSource?.replyThreadTs : undefined;await deliveries.enqueue({destination: {...principalDestination(actorId, actorId),diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex 94738e9c4..9b395b025 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -571,7 +571,11 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const turnTimezone = isValidCapabilityTimezone(input.timezone) ? input.timezone : undefined;if (!deps.identity.isInternal(actor)) {- return { status: "refused", reason: "internal-only: non-internal principals cannot interact" };+ return {+ status: "refused",+ refusalKind: "internal_only",+ reason: "internal-only: non-internal principals cannot interact",+ };}const delegatedSession = conversation.threadRef.startsWith("agent:main:subagent:")? await deps.sessions.getByThread(conversation.threadRef)@@ -674,6 +678,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (!externalAllowed) {return {status: "refused",+ refusalKind: "internal_only",reason: "internal-only: shared audience includes a non-internal participant",};}diff --git a/src/loops/ingress.ts b/src/loops/ingress.tsindex ca8b85027..3bb0b7a46 100644--- a/src/loops/ingress.ts+++ b/src/loops/ingress.ts@@ -11,6 +11,7 @@ import { hashId } from "../util/crypto.ts";import { errMessage, swallow } from "../util/errors.ts";import { isObj } from "./sources/adapter.ts";import { slackConversationRef } from "./sources/slack.ts";+import { isDirectChannelType } from "../slack/payloads.ts";import { createGmailPushClient, verifyGmailPush, type GmailCursor, type GmailPushConfig } from "./gmail-push.ts";export interface LoopIngress {@@ -320,10 +321,11 @@ export function createLoopIngress(deps: LoopIngressDeps) {const at = Number(event.ts) * 1000;if (!Number.isFinite(at) || at <= 0) return { status: 400, body: "Invalid Slack timestamp" };const threadTs = typeof event.thread_ts === "string" ? event.thread_ts : undefined;+ const isDirectMessage = isDirectChannelType(event.channel_type);entry = {loopId: source.loopId,source: "slack",- dedupeKey: slackConversationRef(event.channel, event.ts, threadTs),+ dedupeKey: slackConversationRef(event.channel, event.ts, threadTs, isDirectMessage),summary: event.text.slice(0, 500),sourceAt: at,sourcePayload: {@@ -332,7 +334,7 @@ export function createLoopIngress(deps: LoopIngressDeps) {from: event.user,snippet: event.text.slice(0, 10_000),receivedAt: at,- slack: { channelId: event.channel, ts: event.ts, ...(threadTs ? { threadTs } : {}) },+ slack: { channelId: event.channel, ts: event.ts, isDirectMessage, ...(threadTs ? { threadTs } : {}) },},};} else {diff --git a/src/loops/sources/slack.ts b/src/loops/sources/slack.tsindex 14ddffa35..87e1f133c 100644--- a/src/loops/sources/slack.ts+++ b/src/loops/sources/slack.ts@@ -60,8 +60,8 @@ function metaOf(item: LoopItem): SlackMeta | undefined {export function slackConversationRef(channelId: string,ts: string,- threadTs?: string,- isDirectMessage = channelId.startsWith("D"),+ threadTs: string | undefined,+ isDirectMessage: boolean,): string {return isDirectMessage && !threadTs ? channelId : `${channelId}:${threadTs ?? ts}`;}@@ -69,9 +69,7 @@ export function slackConversationRef(export function slackReplyThreadTs(item: LoopItem): string | undefined {const slack = metaOf(item);if (!slack) return undefined;- if (slack.threadTs) return slack.threadTs;- const dm = slack.isDirectMessage ?? slack.channelId.startsWith("D");- return dm ? undefined : slack.ts;+ return slack.threadTs ?? (slack.isDirectMessage ? undefined : slack.ts);}function itemReactions(item: LoopItem): string[] {@@ -179,7 +177,8 @@ export const slackAdapter: LoopSourceAdapter = {const rawKey = clip(raw.sourceKey ?? raw.dedupeKey, 300);if (!rawKey) return { error: "sourceKey required" };const slack = parseSlackMeta(raw.slack);- if (!slack) return { error: "slack items need slack.channelId and slack.ts" };+ if (!slack || slack.isDirectMessage === undefined)+ return { error: "slack items need slack.channelId, slack.ts and slack.isDirectMessage" };const dedupeKey = slackConversationRef(slack.channelId, slack.ts, slack.threadTs, slack.isDirectMessage);const draft = raw.draft === undefined ? undefined : parseReplyDraft(raw.draft);if (draft === null) return { error: "draft needs a string body" };@@ -195,11 +194,8 @@ export const slackAdapter: LoopSourceAdapter = {matchesEvent(item, conversationRef) {const slack = metaOf(item);if (!slack) return false;- return (- slackConversationRef(slack.channelId, slack.ts, slack.threadTs, slack.isDirectMessage) === conversationRef ||- (!slack.threadTs &&- (slack.isDirectMessage ?? slack.channelId.startsWith("D")) &&- conversationRef === `${slack.channelId}:${slack.ts}`)+ return (slack.isDirectMessage ? [true, false] : [false]).some(+ (dm) => slackConversationRef(slack.channelId, slack.ts, slack.threadTs, dm) === conversationRef,);},parseProposal(raw) {diff --git a/src/slack/approvals.ts b/src/slack/approvals.tsindex 063dad192..ba150fca1 100644--- a/src/slack/approvals.ts+++ b/src/slack/approvals.ts@@ -10,7 +10,6 @@ import {createApprovalRegistry,createThreadTracker,inlineCode,- isBoundaryRefusal,recoveredApprovalContext,resolveReactionTargets,slackReplyArgs,@@ -401,7 +400,7 @@ export function createApprovals(deps: {return;}- const failLink = isBoundaryRefusal(result.reason) ? null : (result.adminUrl ?? null);+ const failLink = result.refusalKind === "internal_only" ? null : (result.adminUrl ?? null);const failDetail = failLink ? ` Full error: ${failLink}` : "";await updateSlackMessage(client,diff --git a/src/slack/attachments.ts b/src/slack/attachments.tsindex 536f9aa63..badcc5daf 100644--- a/src/slack/attachments.ts+++ b/src/slack/attachments.ts@@ -217,12 +217,9 @@ export async function uploadAttachments(}export function uploadFailureNote(err: unknown): string {- const e = err as { data?: { needed?: string }; message?: string };+ const e = err as { data?: { needed?: string } };const code = slackErrorCode(err) ?? "";- const msg = e?.message ?? String(err);- const isPermission =- code === "missing_scope" || code === "not_allowed_token_type" || code === "access_denied" || /scope/i.test(msg);- if (isPermission) {+ if (code === "missing_scope" || code === "not_allowed_token_type" || code === "access_denied") {const needed = e?.data?.needed ?? "files:write";return `⚠️ I couldn't attach the file(s) — check my upload permission (${needed}).`;}diff --git a/src/slack/events.ts b/src/slack/events.tsindex a9a83a60b..494beb954 100644--- a/src/slack/events.ts+++ b/src/slack/events.ts@@ -9,7 +9,13 @@ import {type SurfaceHeaderClient,shouldProcessMessage,} from "./lib.ts";-import { parseEventId, parseLifecycleEvent, parseMessageEvent, parseReactionEvent } from "./payloads.ts";+import {+ isDirectChannelType,+ parseEventId,+ parseLifecycleEvent,+ parseMessageEvent,+ parseReactionEvent,+} from "./payloads.ts";import type { AckGate } from "./deferred-ack.ts";import { messageWithForwardedContent } from "./forwards.ts";import type { BotIdentity, Directory } from "./directory.ts";@@ -64,7 +70,7 @@ export function registerSlackEvents(threadTs?: string;text?: string;senderSlackId?: string;- isDirectMessage?: boolean;+ isDirectMessage: boolean;},) => void;},@@ -201,6 +207,7 @@ export function registerSlackEvents(deps.inboxMessage?.(client, {channel: m.channel,ts: m.ts,+ isDirectMessage: isDirectChannelType(m.channel_type),...(m.thread_ts ? { threadTs: m.thread_ts } : {}),...(typeof m.text === "string" && m.text ? { text: m.text } : {}),...(m.user ? { senderSlackId: m.user } : {}),diff --git a/src/slack/index.ts b/src/slack/index.tsindex e3d3b1a0f..7d1d2fa88 100644--- a/src/slack/index.ts+++ b/src/slack/index.ts@@ -385,7 +385,7 @@ export async function startSlackPlugin(threadTs?: string;text?: string;senderSlackId?: string;- isDirectMessage?: boolean;+ isDirectMessage: boolean;},): void => {void (async () => {@@ -401,7 +401,7 @@ export async function startSlackPlugin(await core.inboxSlackMessage({channel: msg.channel,ts: msg.ts,- ...(msg.isDirectMessage !== undefined ? { isDirectMessage: msg.isDirectMessage } : {}),+ isDirectMessage: msg.isDirectMessage,...(msg.threadTs ? { threadTs: msg.threadTs } : {}),...(msg.text ? { text: msg.text } : {}),...(senderEmail ? { senderEmail } : {}),diff --git a/src/slack/lib.ts b/src/slack/lib.tsindex 1dd612ef1..d9b4c7a9a 100644--- a/src/slack/lib.ts+++ b/src/slack/lib.ts@@ -1,4 +1,4 @@-export { isBoundaryRefusal, refusalDelivery, postThenAckRunDelivery, refusalNote } from "./refusals.ts";+export { refusalDelivery, postThenAckRunDelivery, refusalNote } from "./refusals.ts";export { inlineCode, clip, sleep } from "./util.ts";export { safeChunks } from "./safe-cut.ts";export {diff --git a/src/slack/payloads.ts b/src/slack/payloads.tsindex af0ce636b..845ccfd7e 100644--- a/src/slack/payloads.ts+++ b/src/slack/payloads.ts@@ -197,6 +197,18 @@ export function parseChannelPage(res: unknown): Array<{ id?: string; is_member?:return Array.isArray(channels) ? channels : [];}+export const SLACK_AUTH_ERRORS: ReadonlySet<string> = new Set([+ "not_authed",+ "invalid_auth",+ "token_expired",+ "token_revoked",+ "account_inactive",+]);++export function isDirectChannelType(channelType: unknown): boolean {+ return channelType === "im" || channelType === "mpim";+}+export function slackErrorCode(err: unknown): string | undefined {return str(rec(rec(err)?.data)?.error);}diff --git a/src/slack/refusals.ts b/src/slack/refusals.tsindex aad519c05..69f1e5af2 100644--- a/src/slack/refusals.ts+++ b/src/slack/refusals.ts@@ -1,10 +1,6 @@import type { TurnResult } from "../types.ts";import { standaloneFailureText, userFacingFailureClause } from "../core/failure-copy.ts";-export function isBoundaryRefusal(reason: string | undefined): boolean {- return (reason ?? "").startsWith("internal-only");-}-export function refusalDelivery(result: { refusalKind?: TurnResult["refusalKind"] },unprompted: boolean,@@ -31,14 +27,14 @@ export function refusalNote(result: { status?: string; reason?: string; adminUrl?: string; refusalKind?: TurnResult["refusalKind"] },kind: "dm" | "channel",): string {- const standalone = standaloneFailureText(result);- if (standalone) return standalone;- const reason = result.reason ?? "refused";- if (isBoundaryRefusal(reason)) {+ if (result.refusalKind === "internal_only") {+ const reason = result.reason ?? "refused";return kind === "dm"? `I can't respond just now — ${reason}.`: `I can't respond here — ${reason}. Try a DM or a fully-internal channel.`;}+ const standalone = standaloneFailureText(result);+ if (standalone) return standalone;const clause = userFacingFailureClause(result);const detail = result.adminUrl ? ` Full error: ${result.adminUrl}` : "";return kind === "dm"diff --git a/src/slack/surface-context.ts b/src/slack/surface-context.tsindex 7586d31cd..3dcd459d8 100644--- a/src/slack/surface-context.ts+++ b/src/slack/surface-context.ts@@ -14,7 +14,7 @@ import {oversizeMsg,parseDeliveryTarget,} from "./lib.ts";-import { type SlackHistoryMessage, parseMessageList, slackErrorCode } from "./payloads.ts";+import { SLACK_AUTH_ERRORS, type SlackHistoryMessage, parseMessageList, slackErrorCode } from "./payloads.ts";import type { SlackCoreClient, SurfaceContextRequest } from "../api/slack-core-client.ts";import type { Directory } from "./directory.ts";import {@@ -67,12 +67,11 @@ export function createSurfaceContextFulfiller(deps: {.filter((m) => m.ts);await post(buildContextWindow(shaped, { count }));} catch (err) {- const msg = (err as Error).message;- if (viewerToken && /invalid_auth|token_revoked|account_inactive|token_expired/.test(msg)) {+ if (viewerToken && SLACK_AUTH_ERRORS.has(slackErrorCode(err) ?? "")) {await post({ messages: [], liveSearch: "unconnected" });return;}- await post({ error: `Slack search failed: ${msg}` });+ await post({ error: `Slack search failed: ${(err as Error).message}` });}}diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.tsindex a42684d17..ee5cabc7f 100644--- a/src/slack/turn-handler.ts+++ b/src/slack/turn-handler.ts@@ -513,6 +513,7 @@ export function createTurnHandler(deps: {...(deps.externalAccess? { externalPolicyNamespace: externalSlackNamespace(ids.ownTeamId, deps.externalAccess) }: {}),+ ...(replyThreadTs ? { replyThreadTs } : {}),},}: {}),diff --git a/src/surfaces/slack-installation.ts b/src/surfaces/slack-installation.tsindex 5fa66d3ec..1b8b20abb 100644--- a/src/surfaces/slack-installation.ts+++ b/src/surfaces/slack-installation.ts@@ -1,5 +1,6 @@import type { DurableMap } from "../persistence/durable-map.ts";import { decryptSecret, deriveConnectorKey, encryptSecret } from "../connectors/connector-client-store.ts";+import { SLACK_AUTH_ERRORS } from "../slack/payloads.ts";interface ActiveSlackInstallation {serviceBlocked?: boolean;@@ -312,7 +313,7 @@ export async function validateSlackInstallation(}const payload = (await response.json()) as SlackValidationResponse;if (!response.ok || !payload.ok) {- if (["invalid_auth", "token_revoked", "not_authed", "account_inactive"].includes(payload.error ?? ""))+ if (SLACK_AUTH_ERRORS.has(payload.error ?? ""))throw new Error(`${label} was rejected by Slack. Copy a current token from the same installed Slack app and try again.`,);diff --git a/src/types.ts b/src/types.tsindex 955e9cb17..a229d71ea 100644--- a/src/types.ts+++ b/src/types.ts@@ -654,7 +654,13 @@ export interface ClientToolResult {export interface TurnRequest {desktopClientId?: string;- slackSource?: { accountId: string; teamId: string; userId: string; externalPolicyNamespace?: string };+ slackSource?: {+ accountId: string;+ teamId: string;+ userId: string;+ externalPolicyNamespace?: string;+ replyThreadTs?: string;+ };externalSlack?: {accountId: string;teamId: string;@@ -794,7 +800,7 @@ export interface TurnResult {reply?: string;reactions?: string[];reason?: string;- refusalKind?: "security_quarantine" | "session_busy" | "model_budget" | "approval_denied";+ refusalKind?: "security_quarantine" | "session_busy" | "model_budget" | "approval_denied" | "internal_only";adminUrl?: string;runId?: string;steered?: true;diff --git a/test/approval-store.test.ts b/test/approval-store.test.tsindex 6f11df2e1..3443cd50e 100644--- a/test/approval-store.test.ts+++ b/test/approval-store.test.ts@@ -98,7 +98,7 @@ test("approvals requested from a Slack DM thread are delivered into that thread"const deliveries = createDeliveryStore();const approvals = createApprovalStore(createMemoryMap<PendingApprovalRecord>(), deliveries);const approval = record(threadRef);- approval.request!.deliveryTarget = "D1:1700.1";+ approval.request!.slackSource = { accountId: "default", teamId: "T1", userId: "U1", replyThreadTs: "1700.1" };await approvals.put("A1", approval);const [delivery] = await deliveries.pending("principal");assert.equal(delivery?.destination.threadTs, "1700.1");@@ -107,7 +107,7 @@ test("approvals requested from a Slack DM thread are delivered into that thread"const approvals = createApprovalStore(createMemoryMap<PendingApprovalRecord>(), deliveries);const channel = record("channel:C1:1700.2");channel.request!.conversation = { kind: "channel", threadRef: "channel:C1:1700.2" } as never;- channel.request!.deliveryTarget = "C1:1700.2";+ channel.request!.slackSource = { accountId: "default", teamId: "T1", userId: "U1", replyThreadTs: "1700.2" };await approvals.put("A2", channel);assert.equal((await deliveries.pending("principal"))[0]?.destination.threadTs, undefined);});diff --git a/test/inbox-realtime.test.ts b/test/inbox-realtime.test.tsindex 819eadf58..36ef93f37 100644--- a/test/inbox-realtime.test.ts+++ b/test/inbox-realtime.test.ts@@ -20,7 +20,7 @@ function slackEntry(over: Partial<IngestEntryInput> = {}): IngestEntryInput {title: "DM with Mark",from: "Mark",snippet: "any update?",- slack: { channelId: "D123", ts: "1000.100" },+ slack: { channelId: "D123", ts: "1000.100", isDirectMessage: true },},sourceAt: 1_000_100,...over,@@ -194,11 +194,11 @@ test("someone else's gmail reply bumps the card for a redraft", async () => {});test("slack conversation refs key DMs by channel and channel asks by thread root", () => {- assert.equal(slackConversationRef("D123", "100.1"), "D123");- assert.equal(slackConversationRef("G77", "100.1", "100.1"), "G77:100.1");+ assert.equal(slackConversationRef("D123", "100.1", undefined, true), "D123");+ assert.equal(slackConversationRef("G77", "100.1", "100.1", true), "G77:100.1");assert.equal(slackConversationRef("C77", "100.1", undefined, true), "C77");- assert.equal(slackConversationRef("C9", "200.2"), "C9:200.2");- assert.equal(slackConversationRef("C9", "200.2", "100.1"), "C9:100.1");+ assert.equal(slackConversationRef("D9", "200.2", undefined, false), "D9:200.2");+ assert.equal(slackConversationRef("C9", "200.2", "100.1", false), "C9:100.1");});test("ledger mutations emit change events", async () => {@@ -216,7 +216,7 @@ test("ledger mutations emit change events", async () => {});test("private-channel mentions stay anchored to their thread, not the channel tail", () => {- assert.equal(slackConversationRef("GPRIVATE", "200.2", "100.1"), "GPRIVATE:100.1");+ assert.equal(slackConversationRef("GPRIVATE", "200.2", "100.1", false), "GPRIVATE:100.1");});test("an old own reply cannot close a newer unanswered message", async () => {diff --git a/test/loop-ingress.test.ts b/test/loop-ingress.test.tsindex 46fb90183..65dc1e008 100644--- a/test/loop-ingress.test.ts+++ b/test/loop-ingress.test.ts@@ -133,6 +133,7 @@ test("Slack validates signatures, challenge, workspace, channels, bot exclusionchannel: "C123",user: "U123",text: "Please review",+ channel_type: "channel",ts: "1750000000.001",thread_ts: "1740000000.001",},@@ -151,6 +152,12 @@ test("Slack validates signatures, challenge, workspace, channels, bot exclusionassert.equal(items.length, 1);assert.equal(items[0]?.sourceKey, "C123:1740000000.001");assert.equal(items[0]?.source, "slack");+ assert.deepEqual(items[0]?.sourcePayload?.slack, {+ channelId: "C123",+ ts: "1750000000.001",+ isDirectMessage: false,+ threadTs: "1740000000.001",+ });assert.equal(items[0]?.sourcePayload?.context, undefined);assert.equal(items[0]?.sourcePayload?.snippet, event.event.text);});diff --git a/test/loop-item-routes.test.ts b/test/loop-item-routes.test.tsindex e8de0ee38..aaa80ce5b 100644--- a/test/loop-item-routes.test.ts+++ b/test/loop-item-routes.test.ts@@ -177,7 +177,7 @@ const ITEM = {snippet: "can you review my launch post?",receivedAt: 1234,draft: { body: "Looking now — back to you within the hour." },- slack: { channelId: "C1", ts: "1.2" },+ slack: { channelId: "C1", ts: "1.2", isDirectMessage: false },};async function inboxLoop(w: World): Promise<Loop> {@@ -347,7 +347,7 @@ test("listing returns the ledger view with per-state counts and filters", asyncassert.equal(body.items.length, 1);assert.equal(body.items[0]!.state, "held");assert.equal(body.items[0]!.dedupeKey, "C1:1.2");- assert.deepEqual(body.items[0]!.sourcePayload.slack, { channelId: "C1", ts: "1.2" });+ assert.deepEqual(body.items[0]!.sourcePayload.slack, { channelId: "C1", ts: "1.2", isDirectMessage: false });assert.deepEqual(body.counts, { held: 1 });const heldOnly = await call(w, { method: "GET", path: `/v1/loops/${loop.id}/items?state=held` });assert.equal((heldOnly.body as { items: unknown[] }).items.length, 1);@@ -769,7 +769,11 @@ test("a person's own typed mention stays live, while a capability caller's is di});assert.equal(human.status, 200, JSON.stringify(human.body));assert.equal((w.sent.at(-1)!.body as { text: string }).text, "Heads up <!channel>");- const second = await seed(w, { ...ITEM, sourceKey: "t2", slack: { channelId: "C1", ts: "9.9" } });+ const second = await seed(w, {+ ...ITEM,+ sourceKey: "t2",+ slack: { channelId: "C1", ts: "9.9", isDirectMessage: false },+ });const agent = await call(w, {method: "POST",path: `/v1/loops/${second.loop.id}/items/${second.item.id}/action`,@@ -918,7 +922,7 @@ test("Slack thread keys reuse a legacy item's identity, edits, and replied water...ITEM,sourceKey: "D1:1.0",receivedAt: 2000,- slack: { channelId: "D1", ts: "2.0", threadTs: "1.0" },+ slack: { channelId: "D1", ts: "2.0", threadTs: "1.0", isDirectMessage: true },draft: { body: "Agent replacement" },},],@@ -1135,7 +1139,7 @@ test("only a person overrides triage, and archiving a whole group resolves its mawait call(w, {method: "POST",path: `/v1/loops/${loop.id}/items`,- body: { items: [{ ...ITEM, sourceKey: "C2:1.3", slack: { channelId: "C2", ts: "1.3" } }] },+ body: { items: [{ ...ITEM, sourceKey: "C2:1.3", slack: { channelId: "C2", ts: "1.3", isDirectMessage: false } }] },});await w.loops.store.update(loop.id, {triage: { prioritize: { enabled: true }, consolidate: { enabled: true } },diff --git a/test/loop-source-send.test.ts b/test/loop-source-send.test.tsindex 43a88cde0..68a2f2ad2 100644--- a/test/loop-source-send.test.ts+++ b/test/loop-source-send.test.ts@@ -146,10 +146,22 @@ test("a missing connector reads as not_connected, not an exception", async () =>if (!slackResult.ok) assert.equal(slackResult.reason, "not_connected");});-test("slack replies thread on channel messages and stay inline in DMs", () => {+test("slack replies thread on channel messages and stay inline in DMs and group DMs", () => {assert.equal(slackReplyThreadTs(slackItem), "111.222");- assert.equal(slackReplyThreadTs(item("slack", { slack: { channelId: "D9", ts: "3.4" } })), undefined);- assert.equal(slackReplyThreadTs(item("slack", { slack: { channelId: "D9", ts: "3.4", threadTs: "1.2" } })), "1.2");+ assert.equal(+ slackReplyThreadTs(item("slack", { slack: { channelId: "G9", ts: "3.4", isDirectMessage: true } })),+ undefined,+ );+ assert.equal(+ slackReplyThreadTs(item("slack", { slack: { channelId: "D9", ts: "3.4", isDirectMessage: false } })),+ "3.4",+ );+ assert.equal(+ slackReplyThreadTs(+ item("slack", { slack: { channelId: "D9", ts: "3.4", threadTs: "1.2", isDirectMessage: true } }),+ ),+ "1.2",+ );});test("slack send posts as the user through the slack client", async () => {@@ -268,7 +280,7 @@ test("adapters reject items missing the fields their send path needs", () => {);assert.deepEqual(slackAdapter.parse({ source: "slack", sourceKey: "k", title: "t", from: "f", snippet: "s", receivedAt: 1 }),- { error: "slack items need slack.channelId and slack.ts" },+ { error: "slack items need slack.channelId, slack.ts and slack.isDirectMessage" },);assert.deepEqual(slackAdapter.parse({ source: "slack", title: "t" }), { error: "from required" });});diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.tsindex a7a01371b..1c44a455d 100644--- a/test/orchestrator.test.ts+++ b/test/orchestrator.test.ts@@ -450,6 +450,7 @@ test("a guest actor is refused (internal-only, input side)", async () => {text: "hi",});assert.equal(res.status, "refused");+ assert.equal(res.refusalKind, "internal_only");assert.match(res.reason ?? "", /internal-only/);});@@ -467,6 +468,7 @@ test("a channel with a non-internal audience member is refused (internal-only, otext: "hello channel",});assert.equal(res.status, "refused");+ assert.equal(res.refusalKind, "internal_only");assert.match(res.reason ?? "", /internal-only/);});diff --git a/test/slack-adapter-conversation-keys.test.ts b/test/slack-adapter-conversation-keys.test.tsindex 3a81d110b..db72fd7f4 100644--- a/test/slack-adapter-conversation-keys.test.ts+++ b/test/slack-adapter-conversation-keys.test.ts@@ -19,26 +19,31 @@ test("DMs and group DMs dedupe on the channel alone — one card per conversatioconst parsed = slackAdapter.parse(raw());assert.ok(!("error" in parsed));assert.equal(parsed.dedupeKey, "G555");- const dm = slackAdapter.parse(raw({ slack: { channelId: "D42", ts: "9.9" } }));+ const dm = slackAdapter.parse(raw({ slack: { channelId: "D42", ts: "9.9", isDirectMessage: true } }));assert.ok(!("error" in dm));assert.equal(dm.dedupeKey, "D42");});test("channel asks dedupe per thread", () => {- const threaded = slackAdapter.parse(raw({ slack: { channelId: "C7", ts: "300.3", threadTs: "100.1" } }));+ const threaded = slackAdapter.parse(+ raw({ slack: { channelId: "C7", ts: "300.3", threadTs: "100.1", isDirectMessage: false } }),+ );assert.ok(!("error" in threaded));assert.equal(threaded.dedupeKey, "C7:100.1");- const topLevel = slackAdapter.parse(raw({ slack: { channelId: "C7", ts: "300.3" } }));+ const topLevel = slackAdapter.parse(raw({ slack: { channelId: "C7", ts: "300.3", isDirectMessage: false } }));assert.ok(!("error" in topLevel));assert.equal(topLevel.dedupeKey, "C7:300.3");});-test("G-prefixed private channels are not mistaken for group DMs", () => {- for (const isDirectMessage of [undefined, false]) {- const parsed = slackAdapter.parse(raw({ slack: { channelId: "G555", ts: "1000.100", isDirectMessage } }));+test("conversation kind comes from isDirectMessage, never the channel id prefix", () => {+ for (const channelId of ["G555", "D555"]) {+ const parsed = slackAdapter.parse(raw({ slack: { channelId, ts: "1000.100", isDirectMessage: false } }));assert.ok(!("error" in parsed));- assert.equal(parsed.dedupeKey, "G555:1000.100");+ assert.equal(parsed.dedupeKey, `${channelId}:1000.100`);}+ assert.deepEqual(slackAdapter.parse(raw({ slack: { channelId: "D555", ts: "1000.100" } })), {+ error: "slack items need slack.channelId, slack.ts and slack.isDirectMessage",+ });});test("explicit DM threads remain separate from the unthreaded conversation", () => {@@ -69,3 +74,18 @@ test("probablyResolved and image URLs survive parsing", () => {const context = payload.context as Array<Record<string, unknown>>;assert.deepEqual(context[0]!.images, ["https://files.slack.com/b.png"]);});++test("only DM items match the bare-channel ref; channel and unflagged items match their message ref", () => {+ const stored = (isDirectMessage?: boolean) =>+ ({+ sourcePayload: {+ slack: { channelId: "G555", ts: "1.1", ...(isDirectMessage === undefined ? {} : { isDirectMessage }) },+ },+ }) as never;+ for (const isDirectMessage of [false, undefined]) {+ assert.equal(slackAdapter.matchesEvent(stored(isDirectMessage), "G555"), false);+ assert.equal(slackAdapter.matchesEvent(stored(isDirectMessage), "G555:1.1"), true);+ }+ assert.equal(slackAdapter.matchesEvent(stored(true), "G555"), true);+ assert.equal(slackAdapter.matchesEvent(stored(true), "G555:1.1"), true);+});diff --git a/test/slack-attachments.test.ts b/test/slack-attachments.test.tsindex 2cc82cfa7..9526a3fa5 100644--- a/test/slack-attachments.test.ts+++ b/test/slack-attachments.test.ts@@ -355,4 +355,10 @@ test("uploadFailureNote blames files:write only for permission-class errors", ()});assert.doesNotMatch(note, /files:write/);assert.match(note, /invalid_arguments/);+ const scopeWording = uploadFailureNote({+ data: { error: "invalid_blocks" },+ message: "An API error occurred: invalid_blocks (scope of the block is wrong)",+ });+ assert.doesNotMatch(scopeWording, /files:write/);+ assert.doesNotMatch(uploadFailureNote(new Error("missing scope files:write")), /upload permission/);});diff --git a/test/slack-index.integration.test.ts b/test/slack-index.integration.test.tsindex 2038365ab..1fe71b3ac 100644--- a/test/slack-index.integration.test.ts+++ b/test/slack-index.integration.test.ts@@ -612,6 +612,7 @@ test("a DM becomes one scoped live turn and one Slack reply", async () => {assert.match(f.core.turns[0].redeliveryKey, /^slack:[^:]+:D1:100\.1$/);assert.equal(f.core.turns[0].conversation.audience[0].externalId, "U1");assert.equal(f.core.turns[0].deliveryTarget, "D1");+ assert.equal(f.core.turns[0].slackSource.replyThreadTs, undefined);assert.equal(f.core.turns[0].liveActor, true);assert.equal(f.core.turns[0].triggerTs, "100.1");assert.equal(f.core.turns[0].gatewayContext.botHandle, "qmbot");@@ -1232,6 +1233,25 @@ test("a blocked-thread result without approval details tells only the sender ins}});+test("a DM thread reply carries its reply thread as a typed Slack source field", async () => {+ const f = await fixture();+ try {+ await f.app.emitMessage({+ channel: "D1",+ channel_type: "im",+ user: "U1",+ text: "and this?",+ ts: "100.2",+ thread_ts: "100.1",+ });+ assert.equal(f.core.turns.length, 1);+ assert.equal(f.core.turns[0].conversation.kind, "dm");+ assert.equal(f.core.turns[0].slackSource.replyThreadTs, "100.1");+ } finally {+ await f.stop();+ }+});+test("an internal channel mention carries the complete audience and thread context", async () => {const f = await fixture();try {diff --git a/test/slack-live-search-auth.test.ts b/test/slack-live-search-auth.test.tsnew file mode 100644index 000000000..e2887077b--- /dev/null+++ b/test/slack-live-search-auth.test.ts@@ -0,0 +1,57 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";+import { createSurfaceContextFulfiller } from "../src/slack/surface-context.ts";++async function searchWith(error: string, viewerToken?: string): Promise<unknown> {+ const server = createServer((_req, res) => {+ res.setHeader("content-type", "application/json");+ res.end(JSON.stringify({ ok: false, error }));+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const fulfilled: unknown[] = [];+ try {+ const f = createSurfaceContextFulfiller({+ core: { fulfillContextRequest: async (_id: string, outcome: unknown) => void fulfilled.push(outcome) } as never,+ directory: {} as never,+ serializer: {} as never,+ botToken: "xoxb-test",+ userToken: "xoxp-install",+ clientOptions: {+ slackApiUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/`,+ retryConfig: { retries: 0 },+ },+ });+ await f.fulfillSurfaceContext(+ {},+ {+ id: "r1",+ source: "slack",+ createdAt: Date.now(),+ status: "pending",+ query: { count: 5, searchAll: "launch", ...(viewerToken ? { viewerToken } : {}) },+ },+ );+ } finally {+ server.close();+ }+ return fulfilled[0];+}++test("a viewer token Slack rejects by auth error code reads as an unconnected live search", async () => {+ for (const code of ["invalid_auth", "token_revoked", "token_expired", "account_inactive", "not_authed"]) {+ assert.deepEqual(await searchWith(code, "xoxp-viewer"), {+ result: { messages: [], liveSearch: "unconnected" },+ });+ }+});++test("other Slack errors, or an auth error on the install token, surface as search failures", async () => {+ assert.deepEqual(await searchWith("ratelimited_by_policy", "xoxp-viewer"), {+ error: "Slack search failed: An API error occurred: ratelimited_by_policy",+ });+ assert.deepEqual(await searchWith("invalid_auth"), {+ error: "Slack search failed: An API error occurred: invalid_auth",+ });+});diff --git a/test/slack-mirror-ingestion.test.ts b/test/slack-mirror-ingestion.test.tsindex d1e789187..53640def6 100644--- a/test/slack-mirror-ingestion.test.ts+++ b/test/slack-mirror-ingestion.test.ts@@ -158,6 +158,24 @@ test("hidden messages never enter context or dispatch", async () => {assert.deepEqual(f.inbox, []);});+test("inbox events take DM-ness from Slack's channel_type, not the channel id", async () => {+ const f = fixture();+ for (const [channel, channel_type] of [+ ["D1", "channel"],+ ["G1", "mpim"],+ ["C1", "im"],+ ])+ await f.fire({ type: "message", channel, channel_type, user: "U1", ts: "5.000001", text: "hi" });+ assert.deepEqual(+ f.inbox.map(([, msg]) => [msg.channel, msg.isDirectMessage]),+ [+ ["D1", false],+ ["G1", true],+ ["C1", true],+ ],+ );+});+test("a system-message edit arriving first is already handled", async () => {const f = fixture();await f.fire({diff --git a/test/slack-refusals.test.ts b/test/slack-refusals.test.tsindex 64abaa6cc..6636e1e41 100644--- a/test/slack-refusals.test.ts+++ b/test/slack-refusals.test.ts@@ -1,6 +1,6 @@import { test } from "node:test";import assert from "node:assert/strict";-import { refusalNote, refusalDelivery, postThenAckRunDelivery, isBoundaryRefusal } from "../src/slack/lib.ts";+import { refusalNote, refusalDelivery, postThenAckRunDelivery } from "../src/slack/lib.ts";import { SESSION_BUSY_USER_TEXT } from "../src/core/failure-copy.ts";const ADMIN_URL = "https://portal.example.com/admin/?view=history&session=s-1";@@ -14,10 +14,18 @@ test("refusalNote: a failure renders the core-supplied admin link and drops thetest("refusalNote: a boundary (internal-only) refusal keeps the DM/internal steer and never links", () => {const note = refusalNote(- { reason: "internal-only: shared audience includes a non-internal participant", adminUrl: ADMIN_URL },+ {+ status: "refused",+ refusalKind: "internal_only",+ reason: "internal-only: shared audience includes a non-internal participant",+ adminUrl: ADMIN_URL,+ },"channel",);- assert.match(note, /fully-internal channel/);+ assert.equal(+ note,+ "I can't respond here — internal-only: shared audience includes a non-internal participant. Try a DM or a fully-internal channel.",+ );assert.doesNotMatch(note, /Full error/, "boundary refusals have nothing to debug in admin");});@@ -106,8 +114,12 @@ test("postThenAckRunDelivery: releases recovery when the Slack post fails", asynassert.deepEqual(calls, ["post", "release"]);});-test("isBoundaryRefusal: only internal-only reasons are boundary refusals", () => {- assert.ok(isBoundaryRefusal("internal-only: non-internal principals cannot interact"));- assert.equal(isBoundaryRefusal("An unknown error occurred"), false);- assert.equal(isBoundaryRefusal(undefined), false);+test("refusalNote: boundary copy follows the typed refusal kind, not the reason wording", () => {+ const dm = refusalNote(+ { status: "refused", refusalKind: "internal_only", reason: "guests cannot use this", adminUrl: ADMIN_URL },+ "dm",+ );+ assert.equal(dm, "I can't respond just now — guests cannot use this.");+ const untyped = refusalNote({ status: "refused", reason: "internal-only lookalike", adminUrl: ADMIN_URL }, "dm");+ assert.match(untyped, /Full error/);});