Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ Then invite the app to the channel and pair in that channel/thread with `relay p
| create delegation task (opt-in shared rooms) | `/delegate <machine\|#capability> <goal>` | `relay delegate <machine\|#capability> <goal>` | `/relay delegate <machine\|#capability> <goal>` |
| control delegation task | `/task@<bot_username> <claim\|decline\|cancel\|status\|history> [task-id]` (or `/task <claim\|decline\|cancel\|status\|history> [task-id]` in private/other clients) | `relay task <claim\|decline\|cancel\|status\|history> [task-id]` | `/relay task <claim\|decline\|cancel\|status\|history> [task-id]` |

`quiet`, `normal`, `verbose`, and `completion-only` are valid progress modes. Progress mode controls non-terminal progress noise: quiet suppresses progress updates, completion-only sends final results plus safe compaction notifications, normal sends coalesced milestone progress, and verbose additionally includes safe visible model/tool snapshots at a shorter interval. Progress updates are deduplicated/coalesced, and Telegram live progress is edited in place where possible instead of posting every raw Pi stream event. Terminal notifications still deliver the final assistant answer when it fits safe platform limits, splitting by paragraphs within platform limits and falling back to a Markdown document when an adapter supports files and the output is too large for a reasonable chat burst.
`quiet`, `normal`, `verbose`, and `completion-only` are valid progress modes. Progress mode controls non-terminal progress noise: quiet suppresses progress updates, completion-only sends final results plus safe compaction notifications, normal sends coalesced milestone progress, and verbose additionally includes safe visible model/tool snapshots at a shorter interval. Progress updates are deduplicated/coalesced, and supported messengers update the same live progress message in place where possible instead of posting every raw Pi stream event. Terminal notifications still deliver the final assistant answer when it fits safe platform limits, splitting by paragraphs within platform limits and falling back to a Markdown document when an adapter supports files and the output is too large for a reasonable chat burst.

Remote `/disconnect` is scoped to the requesting chat/conversation only: it revokes that Telegram, Discord, or Slack binding and suppresses future session output/buttons there, without disconnecting other messengers that remain paired to the same Pi session. Local `/relay disconnect` is broader and disconnects the current session from all paired messenger bindings.

Expand Down
28 changes: 27 additions & 1 deletion extensions/relay/adapters/discord/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
ChannelInboundFile,
ChannelInboundHandler,
ChannelInboundMessage,
ChannelLiveProgressRef,
ChannelOutboundFile,
ChannelOutboundPayload,
ChannelRouteAddress,
Expand All @@ -21,13 +22,24 @@ import { DEFAULT_CONVERTIBLE_INBOUND_IMAGE_MIME_TYPES, acceptedInboundImageForma
export interface DiscordApiOperations {
connect?(handler: (event: DiscordGatewayEvent) => Promise<void>): Promise<void>;
disconnect?(): Promise<void>;
sendMessage(payload: DiscordSendMessagePayload): Promise<void>;
sendMessage(payload: DiscordSendMessagePayload): Promise<DiscordSendMessageResult | void>;
editMessage?: (payload: DiscordEditMessagePayload) => Promise<void>;
sendFile(payload: DiscordSendFilePayload): Promise<void>;
sendTyping(channelId: string): Promise<void>;
answerInteraction(interactionId: string, interactionToken: string | undefined, options?: { text?: string; alert?: boolean }): Promise<void>;
downloadFile?(url: string): Promise<Uint8Array>;
}

export interface DiscordSendMessageResult {
messageId?: string;
}

export interface DiscordEditMessagePayload {
channelId: string;
messageId: string;
content: string;
}

export interface DiscordGatewayEvent {
type: "message" | "interaction";
payload: DiscordMessagePayload | DiscordInteractionPayload;
Expand Down Expand Up @@ -166,6 +178,20 @@ export class DiscordChannelAdapter implements ChannelAdapter {
await this.sendDocument(address, file, options);
}

async sendLiveProgress(address: ChannelRouteAddress, text: string): Promise<ChannelLiveProgressRef | undefined> {
const result = await this.api.sendMessage({ channelId: address.conversationId, content: escapeDiscordPlainText(text) });
return result && typeof result === "object" && typeof result.messageId === "string" && result.messageId.length > 0
? { messageId: result.messageId }
: undefined;
}

async updateLiveProgress(address: ChannelRouteAddress, ref: ChannelLiveProgressRef, text: string): Promise<void> {
if (!this.api.editMessage) {
throw new Error("Discord message updates are not supported by this adapter configuration.");
}
await this.api.editMessage({ channelId: address.conversationId, messageId: ref.messageId, content: escapeDiscordPlainText(text) });
}

async sendActivity(address: ChannelRouteAddress, _activity: "typing" | "uploading" | "recording" = "typing"): Promise<void> {
await this.api.sendTyping(address.conversationId);
}
Expand Down
30 changes: 27 additions & 3 deletions extensions/relay/adapters/discord/live-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import type {
DiscordButtonComponent,
DiscordGatewayEvent,
DiscordInteractionPayload,
DiscordEditMessagePayload,
DiscordMessagePayload,
DiscordSendFilePayload,
DiscordSendMessagePayload,
DiscordSendMessageResult,
} from "./adapter.js";
import { redactSecrets } from "../../config/setup.js";
import type { DiscordRelayConfig } from "../../core/types.js";
Expand Down Expand Up @@ -119,12 +121,23 @@ export class DiscordLiveOperations implements DiscordApiOperations {
this.client.destroy();
}

async sendMessage(payload: DiscordSendMessagePayload): Promise<void> {
async sendMessage(payload: DiscordSendMessagePayload): Promise<DiscordSendMessageResult> {
const channel = await this.fetchTextChannel(payload.channelId);
const options: MessageCreateOptions = { content: payload.content || " ", allowedMentions: { parse: [] } };
const components = discordActionRows(payload.components ?? []);
if (components.length > 0) options.components = components;
await channel.send(options);
const message = await channel.send(options);
return message?.id ? { messageId: message.id } : {};
}

async editMessage(payload: DiscordEditMessagePayload): Promise<void> {
const channel = await this.fetchTextChannel(payload.channelId);
const fetchableMessages = channel.messages;
if (!fetchableMessages?.fetch) {
throw new Error(`Discord channel ${payload.channelId} does not support message fetching for edits.`);
}
const message = await fetchableMessages.fetch(payload.messageId);
await message.edit({ content: payload.content || " ", allowedMentions: { parse: [] } });
}

async sendFile(payload: DiscordSendFilePayload): Promise<void> {
Expand Down Expand Up @@ -314,8 +327,19 @@ function discordButtonStyle(style: DiscordButtonComponent["style"]): ButtonStyle
}

interface SendableDiscordTextChannel {
send(options: MessageCreateOptions): Promise<unknown>;
send(options: MessageCreateOptions): Promise<DiscordSentMessageLike>;
sendTyping(): Promise<unknown>;
messages?: {
fetch(messageId: string): Promise<DiscordEditableMessageLike>;
};
}

interface DiscordSentMessageLike {
id?: string;
}
Comment thread
zikolach marked this conversation as resolved.

interface DiscordEditableMessageLike {
edit(options: { content: string; allowedMentions: { parse: [] } }): Promise<unknown>;
}

interface DiscordApplicationCommandManagerLike {
Expand Down
30 changes: 27 additions & 3 deletions extensions/relay/adapters/discord/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { delegationTaskActionButtons, parseDelegationInvocation, renderDelegatio
import { formatFullOutput, formatLatestImageEmptyMessage, formatRelayRecentActivity, formatRelayStatusForRoute, formatSessionSelectorError, formatSummaryOutput } from "../../formatting/presenters.js";
import { formatSessionList, resolveSessionSelector, resolveSessionTargetArgs, type SessionListEntry } from "../../core/session-selection.js";
import { displayProgressMode, formatProgressUpdate, normalizeProgressMode, progressIntervalMsFor, progressModeFor, shouldSendProgressActivity } from "../../notifications/progress.js";
import { deliverLiveProgress, type LiveProgressDeliveryState } from "../../notifications/progress-delivery.js";
import { sendFinalOutputWithFallback } from "../../core/final-output.js";
import { formatRelayLifecycleNotification, type RelayLifecycleEventKind } from "../../notifications/lifecycle.js";
import { abortRouteSafely, compactRouteSafely, deliverRoutePrompt, latestRouteImagesSafely, probeRouteAvailability, routeActionDisplayMessage, routeIdleState, routeImageByPathSafely, routeModelState, routeSkillCommandsSafely, routeWorkspaceRootSafely, unavailableRouteMessage } from "../../core/route-actions.js";
Expand Down Expand Up @@ -73,7 +74,7 @@ export class DiscordRuntime {
private readonly activeSessionByConversationUser = new Map<string, string>();
private readonly recentBindingBySessionKey = new Map<string, ChannelPersistedBindingRecord>();
private readonly typingStates = new Map<string, { address: ChannelRouteAddress; timer?: ReturnType<typeof setTimeout> }>();
private readonly progressStates = new Map<string, { lastEventId?: string; pending: ProgressActivityEntry[]; lastSentAt?: number; timer?: ReturnType<typeof setTimeout> }>();
private readonly progressStates = new Map<string, LiveProgressDeliveryState>();
private readonly invalidPairingAttempts = new Map<string, { count: number; resetAt: number }>();
private readonly activeDelegationTaskBySessionKey = new Map<string, string>();
private started = false;
Expand Down Expand Up @@ -1508,9 +1509,32 @@ export class DiscordRuntime {
}
if (!this.adapter) return;
const text = formatProgressUpdate(pending, this.config, { header: false });
if (!text) return;
if (!text || !this.adapter) return;
state.lastSentAt = Date.now();
await this.adapter.sendText(bindingAddress(binding), text);
const address = bindingAddress(binding);
const adapter: {
sendText: DiscordChannelAdapter["sendText"];
sendLiveProgress?: DiscordChannelAdapter["sendLiveProgress"];
updateLiveProgress?: DiscordChannelAdapter["updateLiveProgress"];
} = this.adapter;
const sendLiveProgress = adapter.sendLiveProgress
? async (nextText: string) => {
const ref = await adapter.sendLiveProgress?.(address, nextText);
return ref?.messageId;
}
: undefined;
const updateLiveProgress = state.liveMessageRef && adapter.updateLiveProgress
? (ref: string, nextText: string) => adapter.updateLiveProgress?.(address, { messageId: ref }, nextText) ?? Promise.reject(new Error("Discord live progress updates are unavailable."))
: undefined;
await deliverLiveProgress(
state,
text,
{
sendLiveProgress,
updateLiveProgress,
sendProgressSnapshot: (nextText) => adapter.sendText(address, nextText),
},
);
}

private startTypingActivity(route: SessionRoute, address: ChannelRouteAddress): void {
Expand Down
27 changes: 26 additions & 1 deletion extensions/relay/adapters/slack/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
ChannelInboundFile,
ChannelInboundHandler,
ChannelInboundMessage,
ChannelLiveProgressRef,
ChannelOutboundFile,
ChannelOutboundPayload,
ChannelRouteAddress,
Expand All @@ -23,7 +24,8 @@ export interface SlackApiOperations {
startSocketMode?(handler: (event: SlackEnvelope) => Promise<void>): Promise<void>;
stopSocketMode?(): Promise<void>;
authTest?(): Promise<SlackAuthTestResult>;
postMessage(payload: SlackPostMessagePayload): Promise<void>;
postMessage(payload: SlackPostMessagePayload): Promise<SlackPostMessageResult | void>;
updateMessage?(payload: SlackUpdateMessagePayload): Promise<void>;
uploadFile(payload: SlackUploadFilePayload): Promise<void>;
addReaction?(payload: SlackReactionPayload): Promise<void>;
removeReaction?(payload: SlackReactionPayload): Promise<void>;
Expand All @@ -32,6 +34,17 @@ export interface SlackApiOperations {
downloadFile?(url: string): Promise<Uint8Array>;
}

export interface SlackPostMessageResult {
ts?: string;
}

export interface SlackUpdateMessagePayload {
channel: string;
ts: string;
text: string;
blocks?: SlackBlock[];
}

export interface SlackReactionPayload {
channel: string;
timestamp: string;
Expand Down Expand Up @@ -217,6 +230,18 @@ export class SlackChannelAdapter implements ChannelAdapter {
if (options?.buttons) await this.sendButtonPrompt(address, options.buttons);
}

async sendLiveProgress(address: ChannelRouteAddress, text: string): Promise<ChannelLiveProgressRef | undefined> {
const result = await this.api.postMessage({ channel: address.conversationId, text, threadTs: slackThreadTs(address) });
return typeof result === "object" && result?.ts ? { messageId: result.ts } : undefined;
}

async updateLiveProgress(address: ChannelRouteAddress, ref: ChannelLiveProgressRef, text: string): Promise<void> {
if (!this.api.updateMessage) {
throw new Error("Slack message updates are not supported by this adapter configuration.");
}
await this.api.updateMessage({ channel: address.conversationId, ts: ref.messageId, text });
}

async sendImage(address: ChannelRouteAddress, file: ChannelOutboundFile, options?: { caption?: string; buttons?: ChannelButtonLayout }): Promise<void> {
assertCanSendOutboundFile(this, file, "image");
await this.sendDocument(address, file, options);
Expand Down
22 changes: 19 additions & 3 deletions extensions/relay/adapters/slack/live-client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { appendFileSync } from "node:fs";
import type { SlackApiOperations, SlackAuthTestResult, SlackEnvelope, SlackPostEphemeralPayload, SlackPostMessagePayload, SlackReactionPayload, SlackUploadFilePayload } from "./adapter.js";
import type {
SlackApiOperations,
SlackAuthTestResult,
SlackEnvelope,
SlackPostEphemeralPayload,
SlackPostMessagePayload,
SlackPostMessageResult,
SlackReactionPayload,
SlackUpdateMessagePayload,
SlackUploadFilePayload,
} from "./adapter.js";
import { redactSecrets } from "../../config/setup.js";
import type { SlackRelayConfig } from "../../core/types.js";

Expand Down Expand Up @@ -87,8 +97,14 @@ export class SlackLiveOperations implements SlackApiOperations {
};
}

async postMessage(payload: SlackPostMessagePayload): Promise<void> {
await this.callSlackApi("chat.postMessage", this.botToken, { channel: payload.channel, text: payload.text, thread_ts: payload.threadTs, blocks: payload.blocks ? slackBlocks(payload.blocks) : undefined });
async postMessage(payload: SlackPostMessagePayload): Promise<SlackPostMessageResult> {
const response = await this.callSlackApi("chat.postMessage", this.botToken, { channel: payload.channel, text: payload.text, thread_ts: payload.threadTs, blocks: payload.blocks ? slackBlocks(payload.blocks) : undefined });
const ts = stringField(response, "ts");
return ts ? { ts } : {};
}

async updateMessage(payload: SlackUpdateMessagePayload): Promise<void> {
await this.callSlackApi("chat.update", this.botToken, { channel: payload.channel, ts: payload.ts, text: payload.text, blocks: payload.blocks ? slackBlocks(payload.blocks) : undefined });
}

async uploadFile(payload: SlackUploadFilePayload): Promise<void> {
Expand Down
28 changes: 26 additions & 2 deletions extensions/relay/adapters/slack/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { delegationTaskActionButtons, parseDelegationInvocation, renderDelegatio
import { formatFullOutput, formatLatestImageEmptyMessage, formatRelayRecentActivity, formatRelayStatusForRoute, formatSessionSelectorError, formatSummaryOutput, sessionEntryForRoute } from "../../formatting/presenters.js";
import { formatSessionList, resolveSessionSelector, resolveSessionTargetArgs, type SessionListEntry } from "../../core/session-selection.js";
import { displayProgressMode, formatProgressUpdate, normalizeProgressMode, progressIntervalMsFor, progressModeFor, shouldSendProgressActivity } from "../../notifications/progress.js";
import { deliverLiveProgress, type LiveProgressDeliveryState } from "../../notifications/progress-delivery.js";
import { sendFinalOutputWithFallback } from "../../core/final-output.js";
import { deliverWorkspaceFileToRequester, formatRequesterFileDeliveryResult, parseRemoteSendFileArgs, type RelayFileDeliveryRequester } from "../../core/requester-file-delivery.js";
import { abortRouteSafely, compactRouteSafely, deliverRoutePrompt, latestRouteImagesSafely, probeRouteAvailability, routeActionDisplayMessage, routeIdleState, routeImageByPathSafely, routeModelState, routeSkillCommandsSafely, routeWorkspaceRootSafely, unavailableRouteMessage } from "../../core/route-actions.js";
Expand Down Expand Up @@ -82,7 +83,7 @@ export class SlackRuntime {
private readonly seenEventKeys = new Map<string, number>();
private readonly consumedResponseUrls = new Map<string, number>();
private readonly thinkingReactions = new Map<string, { channel: string; timestamp: string; name: string }>();
private readonly progressStates = new Map<string, { lastEventId?: string; pending: NonNullable<SessionRoute["notification"]["recentActivity"]>; timer?: ReturnType<typeof setTimeout>; lastSentAt?: number }>();
private readonly progressStates = new Map<string, LiveProgressDeliveryState>();
private readonly activeDelegationTaskBySessionKey = new Map<string, string>();
private botIdentity?: SlackAuthTestResult;
private started = false;
Expand Down Expand Up @@ -1541,7 +1542,30 @@ export class SlackRuntime {
const text = formatProgressUpdate(pending, this.config, { header: false });
if (!text || !this.adapter) return;
state.lastSentAt = Date.now();
await this.adapter.sendText(bindingAddress(binding), text);
const address = bindingAddress(binding);
const adapter: {
sendText: SlackChannelAdapter["sendText"];
sendLiveProgress?: SlackChannelAdapter["sendLiveProgress"];
updateLiveProgress?: SlackChannelAdapter["updateLiveProgress"];
} = this.adapter;
const sendLiveProgress = adapter.sendLiveProgress
? async (nextText: string) => {
const ref = await adapter.sendLiveProgress?.(address, nextText);
return ref?.messageId;
}
: undefined;
const updateLiveProgress = state.liveMessageRef && adapter.updateLiveProgress
? (ref: string, nextText: string) => adapter.updateLiveProgress?.(address, { messageId: ref }, nextText) ?? Promise.reject(new Error("Slack live progress updates are unavailable."))
: undefined;
await deliverLiveProgress(
state,
text,
{
sendLiveProgress,
updateLiveProgress,
sendProgressSnapshot: (nextText) => adapter.sendText(address, nextText),
},
);
}

private async startThinkingReaction(route: SessionRoute, message: ChannelInboundMessage): Promise<void> {
Expand Down
Loading