Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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 and completion-only suppress progress updates, normal sends standard progress, and verbose sends more frequent progress. 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 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.

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
96 changes: 93 additions & 3 deletions extensions/relay/adapters/discord/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ import { completeDiscordPairing } from "../channel-pairing.js";
import { DiscordChannelAdapter, discordMentionsSharedRoomAddressing, discordPairingCommand, discordRelayPairingCommand, isDiscordIdentityAllowed, type DiscordApiOperations } from "./adapter.js";
import { createDiscordLiveOperations } from "./live-client.js";
import { TunnelStateStore } from "../../state/tunnel-store.js";
import type { ChannelPersistedBindingRecord, LatestTurnImage, PairingApprovalDecision, ProgressMode, SessionRoute, TelegramTunnelConfig } from "../../core/types.js";
import type { ChannelPersistedBindingRecord, LatestTurnImage, PairingApprovalDecision, ProgressActivityEntry, ProgressMode, SessionRoute, TelegramTunnelConfig } from "../../core/types.js";
import { commandAllowsWhilePaused, normalizeAliasArg, parseRemoteCommandInvocation, buildHelpText } from "../../commands/remote.js";
import { delegationTaskActionButtons, parseDelegationInvocation, renderDelegationTaskCard } from "../../commands/delegation.js";
import { formatFullOutput, formatLatestImageEmptyMessage, formatRelayRecentActivity, formatRelayStatusForRoute, formatSessionSelectorError, formatSummaryOutput } from "../../formatting/presenters.js";
import { formatSessionList, resolveSessionSelector, resolveSessionTargetArgs, type SessionListEntry } from "../../core/session-selection.js";
import { displayProgressMode, normalizeProgressMode, progressModeFor } from "../../notifications/progress.js";
import { displayProgressMode, formatProgressUpdate, normalizeProgressMode, progressIntervalMsFor, progressModeFor, shouldSendProgressActivity } from "../../notifications/progress.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";
import { statusSnapshotForRoute } from "../../core/relay-core.js";
import { authorityOutcomeAllowsDelivery, bindingAuthorityDiagnostic, resolveChannelBindingAuthority } from "../../core/binding-authority.js";
import { authorityOutcomeAllowsDelivery, bindingAuthorityDiagnostic, channelDestinationKey, resolveChannelBindingAuthority } from "../../core/binding-authority.js";
import { redactSecrets } from "../../config/setup.js";
import { buildImagePromptContent, modelSupportsImages, summarizeTextDeterministically } from "../../core/utils.js";
import { prepareInboundImagePromptContent } from "../../media/index.js";
Expand Down Expand Up @@ -73,6 +73,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 invalidPairingAttempts = new Map<string, { count: number; resetAt: number }>();
private readonly activeDelegationTaskBySessionKey = new Map<string, string>();
private started = false;
Expand Down Expand Up @@ -121,6 +122,7 @@ export class DiscordRuntime {
async stop(): Promise<void> {
this.started = false;
this.clearAllTypingActivity();
this.clearAllProgressStates();
await this.adapter?.stopPolling?.();
}

Expand All @@ -131,10 +133,12 @@ export class DiscordRuntime {
this.ownedBindingSessionKeys.add(route.sessionKey);
this.recentBindingBySessionKey.set(route.sessionKey, binding);
}
this.syncProgressDelivery(route);
}

async unregisterRoute(sessionKey: string): Promise<void> {
this.stopTypingActivity(sessionKey);
this.clearProgressStateBySessionKey(sessionKey);
this.routes.delete(sessionKey);
this.ownedBindingSessionKeys.delete(sessionKey);
this.recentBindingBySessionKey.delete(sessionKey);
Expand Down Expand Up @@ -1423,6 +1427,92 @@ export class DiscordRuntime {
this.invalidPairingAttempts.set(key, { ...current, count: current.count + 1 });
}

private progressKey(route: SessionRoute): string | undefined {
const binding = this.recentBindingBySessionKey.get(route.sessionKey);
return binding ? channelDestinationKey({ channel: DISCORD_CHANNEL, instanceId: this.instanceId, sessionKey: route.sessionKey, conversationId: binding.conversationId, userId: binding.userId }) : undefined;
}

private clearAllProgressStates(): void {
for (const state of this.progressStates.values()) {
if (state.timer) clearTimeout(state.timer);
}
this.progressStates.clear();
}

private clearProgressStateByKey(key: string): void {
const state = this.progressStates.get(key);
if (state?.timer) clearTimeout(state.timer);
this.progressStates.delete(key);
}

private clearProgressStateBySessionKey(sessionKey: string): void {
const prefix = `${DISCORD_CHANNEL}:${this.instanceId}:${sessionKey}:`;
for (const [key] of this.progressStates) {
if (key.startsWith(prefix)) this.clearProgressStateByKey(key);
}
}

private clearProgressState(route: SessionRoute): void {
const key = this.progressKey(route);
if (key) this.clearProgressStateByKey(key);
else this.clearProgressStateBySessionKey(route.sessionKey);
}

private syncProgressDelivery(route: SessionRoute): void {
const event = route.notification.progressEvent;
const binding = this.recentBindingBySessionKey.get(route.sessionKey);
const key = this.progressKey(route);
const deliverableEvent = event && (route.notification.lastStatus === "running" || event.kind === "compaction");
if (!key || !event || !deliverableEvent || !binding || binding.paused) {
if (route.notification.lastStatus && isTerminalStatus(route.notification.lastStatus)) this.clearProgressState(route);
return;
}
const mode = progressModeFor({ progressMode: channelProgressMode(binding) }, this.config);
if (!shouldSendProgressActivity(mode, event)) return;
let state = this.progressStates.get(key);
if (!state) {
state = { pending: [] };
this.progressStates.set(key, state);
}
if (state.lastEventId === event.id) return;
state.lastEventId = event.id;
state.pending.push(event);
if (state.timer) return;
const interval = progressIntervalMsFor(mode, this.config);
const elapsed = state.lastSentAt ? Date.now() - state.lastSentAt : interval;
const delay = Math.max(0, interval - elapsed);
state.timer = setTimeout(() => {
void this.flushProgress(route.sessionKey, binding, key).catch((error: unknown) => {
this.lastError = safeDiscordRuntimeError(error);
});
}, delay);
unrefTimer(state.timer);
}

private async flushProgress(sessionKey: string, expectedBinding: ChannelPersistedBindingRecord, key: string): Promise<void> {
const state = this.progressStates.get(key);
if (!state) return;
state.timer = undefined;
state.lastSentAt = Date.now();
const route = this.routes.get(sessionKey);
const binding = route ? await this.activeBindingForRoute(route, { includePaused: true, address: bindingAddress(expectedBinding) }) : undefined;
if (!route || !binding || binding.conversationId !== expectedBinding.conversationId || binding.userId !== expectedBinding.userId || binding.paused) {
this.clearProgressStateByKey(key);
return;
}
const mode = progressModeFor({ progressMode: channelProgressMode(binding) }, this.config);
const pending = state.pending.splice(0).filter((entry) => (route.notification.lastStatus === "running" || entry.kind === "compaction") && shouldSendProgressActivity(mode, entry));
if (pending.length === 0) {
this.clearProgressState(route);
return;
}
if (!this.adapter) return;
const text = formatProgressUpdate(pending, this.config, { header: false });
if (!text) return;
state.lastSentAt = Date.now();
await this.adapter.sendText(bindingAddress(binding), text);
}

private startTypingActivity(route: SessionRoute, address: ChannelRouteAddress): void {
this.stopTypingActivity(route.sessionKey);
this.typingStates.set(route.sessionKey, { address });
Expand Down
19 changes: 9 additions & 10 deletions extensions/relay/adapters/slack/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { buildHelpText, commandAllowsWhilePaused, normalizeAliasArg, parseRemote
import { delegationTaskActionButtons, parseDelegationInvocation, renderDelegationTaskCard } from "../../commands/delegation.js";
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, shouldSendNonTerminalProgress } from "../../notifications/progress.js";
import { displayProgressMode, formatProgressUpdate, normalizeProgressMode, progressIntervalMsFor, progressModeFor, shouldSendProgressActivity } from "../../notifications/progress.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 @@ -1494,15 +1494,13 @@ export class SlackRuntime {
const event = route.notification.progressEvent;
const binding = this.recentBindingBySessionKey.get(route.sessionKey);
const key = this.progressKey(route);
if (!key || !event || !binding || binding.paused || route.notification.lastStatus !== "running") {
const deliverableEvent = event && (route.notification.lastStatus === "running" || event.kind === "compaction");
if (!key || !event || !deliverableEvent || !binding || binding.paused) {
if (route.notification.lastStatus && isTerminalStatus(route.notification.lastStatus)) this.clearProgressState(route);
return;
}
const mode = progressModeFor({ progressMode: channelProgressMode(binding) }, this.config);
if (!shouldSendNonTerminalProgress(mode)) {
this.clearProgressState(route);
return;
}
if (!shouldSendProgressActivity(mode, event)) return;
let state = this.progressStates.get(key);
if (!state) {
state = { pending: [] };
Expand All @@ -1527,19 +1525,20 @@ export class SlackRuntime {
const state = this.progressStates.get(key);
if (!state) return;
state.timer = undefined;
state.lastSentAt = Date.now();
const route = this.routes.get(sessionKey);
const binding = route ? await this.activeBindingForRoute(route, { includePaused: true, address: bindingAddress(expectedBinding) }) : undefined;
if (!route || !binding || binding.conversationId !== expectedBinding.conversationId || binding.userId !== expectedBinding.userId || binding.paused || route.notification.lastStatus !== "running") {
if (!route || !binding || binding.conversationId !== expectedBinding.conversationId || binding.userId !== expectedBinding.userId || binding.paused) {
this.clearProgressStateByKey(key);
return;
}
const mode = progressModeFor({ progressMode: channelProgressMode(binding) }, this.config);
if (!shouldSendNonTerminalProgress(mode)) {
const pending = state.pending.splice(0).filter((entry) => (route.notification.lastStatus === "running" || entry.kind === "compaction") && shouldSendProgressActivity(mode, entry));
if (pending.length === 0) {
this.clearProgressState(route);
return;
}
const pending = state.pending.splice(0);
const text = formatProgressUpdate(pending, this.config);
const text = formatProgressUpdate(pending, this.config, { header: false });
if (!text || !this.adapter) return;
state.lastSentAt = Date.now();
await this.adapter.sendText(bindingAddress(binding), text);
Expand Down
34 changes: 34 additions & 0 deletions extensions/relay/adapters/telegram/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 @@ -31,6 +32,8 @@ const TELEGRAM_CHANNEL: ChannelAdapterKind = "telegram";
export interface TelegramApiOperations {
getUpdates(offset: number | undefined): Promise<Array<TelegramInboundMessage | TelegramInboundCallback>>;
sendPlainTextWithKeyboard(chatId: number, text: string, keyboard?: TelegramInlineKeyboard): Promise<void>;
sendEditablePlainText?(chatId: number, text: string): Promise<number>;
editPlainText?(chatId: number, messageId: number, text: string): Promise<void>;
sendDocumentData(chatId: number, filename: string, data: Uint8Array, caption?: string): Promise<void>;
answerCallbackQuery(callbackQueryId: string, text?: string, alert?: boolean): Promise<void>;
sendChatAction(chatId: number, action?: "typing" | "upload_document" | "record_video"): Promise<void>;
Expand Down Expand Up @@ -93,6 +96,37 @@ export class TelegramChannelAdapter implements ChannelAdapter {
await this.api.sendPlainTextWithKeyboard(telegramChatId(address), text, options?.buttons ? toTelegramKeyboard(options.buttons) : undefined);
}

async sendLiveProgress(address: ChannelRouteAddress, text: string): Promise<ChannelLiveProgressRef | undefined> {
if (!this.api.sendEditablePlainText) {
await this.sendText(address, text);
return undefined;
}
try {
const messageId = await this.api.sendEditablePlainText(telegramChatId(address), text);
return { messageId: String(messageId) };
} catch {
await this.sendText(address, text);
return undefined;
}
}

async updateLiveProgress(address: ChannelRouteAddress, ref: ChannelLiveProgressRef, text: string): Promise<void> {
if (!this.api.editPlainText) {
await this.sendText(address, text);
return;
}
const messageId = Number(ref.messageId);
if (!Number.isSafeInteger(messageId)) {
await this.sendText(address, text);
return;
}
try {
await this.api.editPlainText(telegramChatId(address), messageId, text);
} catch {
await this.sendText(address, text);
}
}

async sendDocument(address: ChannelRouteAddress, file: ChannelOutboundFile, options?: { caption?: string; buttons?: ChannelButtonLayout }): Promise<void> {
await this.api.sendDocumentData(telegramChatId(address), file.fileName, outboundFileBytes(file), options?.caption);
if (options?.buttons) {
Expand Down
17 changes: 17 additions & 0 deletions extensions/relay/adapters/telegram/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,23 @@ export class TelegramApiClient {
await this.sendPreparedChatTextWithKeyboard(chatId, formatted, keyboard);
}

async sendEditablePlainText(chatId: number, text: string): Promise<number> {
const redacted = redactSecret(text, this.config.redactionPatterns);
const formatted = formatTelegramChatText(redacted);
const chunk = chunkTelegramText(formatted.replace(/\r\n/g, "\n"), this.config.maxTelegramMessageChars)[0];
const rendered = this.renderPreparedChunk(chunk?.text ?? "");
const message = await this.withRetry(() => this.api.sendMessage(chatId, rendered.text, rendered.parseMode ? { parse_mode: rendered.parseMode } : undefined));
return message.message_id;
}

async editPlainText(chatId: number, messageId: number, text: string): Promise<void> {
const redacted = redactSecret(text, this.config.redactionPatterns);
const formatted = formatTelegramChatText(redacted);
const chunk = chunkTelegramText(formatted.replace(/\r\n/g, "\n"), this.config.maxTelegramMessageChars)[0];
const rendered = this.renderPreparedChunk(chunk?.text ?? "");
await this.withRetry(() => this.api.editMessageText(chatId, messageId, rendered.text, rendered.parseMode ? { parse_mode: rendered.parseMode } : undefined));
}

/**
* Sends chat text that is safe to render as Telegram HTML where supported.
* The method applies configured secret redaction before chunking so callers
Expand Down
Loading