refactor: unify message tool + CLI

This commit is contained in:
Peter Steinberger
2026-01-13 00:12:05 +00:00
parent 103003d9ff
commit 3636a2bf51
20 changed files with 838 additions and 1380 deletions

View File

@@ -0,0 +1,385 @@
import type { OutboundDeliveryResult } from "../infra/outbound/deliver.js";
import {
formatGatewaySummary,
formatOutboundDeliverySummary,
} from "../infra/outbound/format.js";
import type { MessageActionRunResult } from "../infra/outbound/message-action-runner.js";
import { getProviderPlugin } from "../providers/plugins/index.js";
import type {
ProviderId,
ProviderMessageActionName,
} from "../providers/plugins/types.js";
import { renderTable } from "../terminal/table.js";
import { isRich, theme } from "../terminal/theme.js";
const shortenText = (value: string, maxLen: number) => {
const chars = Array.from(value);
if (chars.length <= maxLen) return value;
return `${chars.slice(0, Math.max(0, maxLen - 1)).join("")}`;
};
const resolveProviderLabel = (provider: ProviderId) =>
getProviderPlugin(provider)?.meta.label ?? provider;
function extractMessageId(payload: unknown): string | null {
if (!payload || typeof payload !== "object") return null;
const direct = (payload as { messageId?: unknown }).messageId;
if (typeof direct === "string" && direct.trim()) return direct.trim();
const result = (payload as { result?: unknown }).result;
if (result && typeof result === "object") {
const nested = (result as { messageId?: unknown }).messageId;
if (typeof nested === "string" && nested.trim()) return nested.trim();
}
return null;
}
export type MessageCliJsonEnvelope = {
action: ProviderMessageActionName;
provider: ProviderId;
dryRun: boolean;
handledBy: "plugin" | "core" | "dry-run";
payload: unknown;
};
export function buildMessageCliJson(
result: MessageActionRunResult,
): MessageCliJsonEnvelope {
return {
action: result.action,
provider: result.provider,
dryRun: result.dryRun,
handledBy: result.handledBy,
payload: result.payload,
};
}
type FormatOpts = {
width: number;
};
function renderObjectSummary(payload: unknown, opts: FormatOpts): string[] {
if (!payload || typeof payload !== "object") {
return [String(payload)];
}
const obj = payload as Record<string, unknown>;
const keys = Object.keys(obj);
if (keys.length === 0) return [theme.muted("(empty)")];
const rows = keys.slice(0, 20).map((k) => {
const v = obj[k];
const value =
v == null
? "null"
: Array.isArray(v)
? `${v.length} items`
: typeof v === "object"
? "object"
: typeof v === "string"
? v
: typeof v === "number"
? String(v)
: typeof v === "boolean"
? v
? "true"
: "false"
: typeof v === "bigint"
? v.toString()
: typeof v === "symbol"
? v.toString()
: typeof v === "function"
? "function"
: "unknown";
return { Key: k, Value: shortenText(value, 96) };
});
return [
renderTable({
width: opts.width,
columns: [
{ key: "Key", header: "Key", minWidth: 16 },
{ key: "Value", header: "Value", flex: true, minWidth: 24 },
],
rows,
}).trimEnd(),
];
}
function renderMessageList(
messages: unknown[],
opts: FormatOpts,
emptyLabel: string,
): string[] {
const rows = messages.slice(0, 25).map((m) => {
const msg = m as Record<string, unknown>;
const id =
(typeof msg.id === "string" && msg.id) ||
(typeof msg.ts === "string" && msg.ts) ||
(typeof msg.messageId === "string" && msg.messageId) ||
"";
const authorObj = msg.author as Record<string, unknown> | undefined;
const author =
(typeof msg.authorTag === "string" && msg.authorTag) ||
(typeof authorObj?.username === "string" && authorObj.username) ||
(typeof msg.user === "string" && msg.user) ||
"";
const time =
(typeof msg.timestamp === "string" && msg.timestamp) ||
(typeof msg.ts === "string" && msg.ts) ||
"";
const text =
(typeof msg.content === "string" && msg.content) ||
(typeof msg.text === "string" && msg.text) ||
"";
return {
Time: shortenText(time, 28),
Author: shortenText(author, 22),
Text: shortenText(text.replace(/\s+/g, " ").trim(), 90),
Id: shortenText(id, 22),
};
});
if (rows.length === 0) {
return [theme.muted(emptyLabel)];
}
return [
renderTable({
width: opts.width,
columns: [
{ key: "Time", header: "Time", minWidth: 14 },
{ key: "Author", header: "Author", minWidth: 10 },
{ key: "Text", header: "Text", flex: true, minWidth: 24 },
{ key: "Id", header: "Id", minWidth: 10 },
],
rows,
}).trimEnd(),
];
}
function renderMessagesFromPayload(
payload: unknown,
opts: FormatOpts,
): string[] | null {
if (!payload || typeof payload !== "object") return null;
const messages = (payload as { messages?: unknown }).messages;
if (!Array.isArray(messages)) return null;
return renderMessageList(messages, opts, "No messages.");
}
function renderPinsFromPayload(
payload: unknown,
opts: FormatOpts,
): string[] | null {
if (!payload || typeof payload !== "object") return null;
const pins = (payload as { pins?: unknown }).pins;
if (!Array.isArray(pins)) return null;
return renderMessageList(pins, opts, "No pins.");
}
function extractDiscordSearchResultsMessages(
results: unknown,
): unknown[] | null {
if (!results || typeof results !== "object") return null;
const raw = (results as { messages?: unknown }).messages;
if (!Array.isArray(raw)) return null;
// Discord search returns messages as array-of-array; first element is the message.
const flattened: unknown[] = [];
for (const entry of raw) {
if (Array.isArray(entry) && entry.length > 0) {
flattened.push(entry[0]);
} else if (entry && typeof entry === "object") {
flattened.push(entry);
}
}
return flattened.length ? flattened : null;
}
function renderReactions(payload: unknown, opts: FormatOpts): string[] | null {
if (!payload || typeof payload !== "object") return null;
const reactions = (payload as { reactions?: unknown }).reactions;
if (!Array.isArray(reactions)) return null;
const rows = reactions.slice(0, 50).map((r) => {
const entry = r as Record<string, unknown>;
const emojiObj = entry.emoji as Record<string, unknown> | undefined;
const emoji =
(typeof emojiObj?.raw === "string" && emojiObj.raw) ||
(typeof entry.name === "string" && entry.name) ||
(typeof entry.emoji === "string" && (entry.emoji as string)) ||
"";
const count = typeof entry.count === "number" ? String(entry.count) : "";
const userList = Array.isArray(entry.users)
? (entry.users as unknown[])
.slice(0, 8)
.map((u) => {
if (typeof u === "string") return u;
if (!u || typeof u !== "object") return "";
const user = u as Record<string, unknown>;
return (
(typeof user.tag === "string" && user.tag) ||
(typeof user.username === "string" && user.username) ||
(typeof user.id === "string" && user.id) ||
""
);
})
.filter(Boolean)
: [];
return {
Emoji: emoji,
Count: count,
Users: shortenText(userList.join(", "), 72),
};
});
if (rows.length === 0) return [theme.muted("No reactions.")];
return [
renderTable({
width: opts.width,
columns: [
{ key: "Emoji", header: "Emoji", minWidth: 8 },
{ key: "Count", header: "Count", align: "right", minWidth: 6 },
{ key: "Users", header: "Users", flex: true, minWidth: 20 },
],
rows,
}).trimEnd(),
];
}
export function formatMessageCliText(result: MessageActionRunResult): string[] {
const rich = isRich();
const ok = (text: string) => (rich ? theme.success(text) : text);
const muted = (text: string) => (rich ? theme.muted(text) : text);
const heading = (text: string) => (rich ? theme.heading(text) : text);
const width = Math.max(60, (process.stdout.columns ?? 120) - 1);
const opts: FormatOpts = { width };
if (result.handledBy === "dry-run") {
return [
muted(`[dry-run] would run ${result.action} via ${result.provider}`),
];
}
if (result.kind === "send") {
if (result.handledBy === "core" && result.sendResult) {
const send = result.sendResult;
if (send.via === "direct") {
const directResult = send.result as OutboundDeliveryResult | undefined;
return [ok(formatOutboundDeliverySummary(send.provider, directResult))];
}
const gatewayResult = send.result as { messageId?: string } | undefined;
return [
ok(
formatGatewaySummary({
provider: send.provider,
messageId: gatewayResult?.messageId ?? null,
}),
),
];
}
const label = resolveProviderLabel(result.provider);
const msgId = extractMessageId(result.payload);
return [ok(`✅ Sent via ${label}.${msgId ? ` Message ID: ${msgId}` : ""}`)];
}
if (result.kind === "poll") {
if (result.handledBy === "core" && result.pollResult) {
const poll = result.pollResult;
const pollId = (poll.result as { pollId?: string } | undefined)?.pollId;
const msgId = poll.result?.messageId ?? null;
const lines = [
ok(
formatGatewaySummary({
action: "Poll sent",
provider: poll.provider,
messageId: msgId,
}),
),
];
if (pollId) lines.push(ok(`Poll id: ${pollId}`));
return lines;
}
const label = resolveProviderLabel(result.provider);
const msgId = extractMessageId(result.payload);
return [
ok(`✅ Poll sent via ${label}.${msgId ? ` Message ID: ${msgId}` : ""}`),
];
}
// provider actions (non-send/poll)
const payload = result.payload;
const lines: string[] = [];
if (result.action === "react") {
const added = (payload as { added?: unknown }).added;
const removed = (payload as { removed?: unknown }).removed;
if (typeof added === "string" && added.trim()) {
lines.push(ok(`✅ Reaction added: ${added.trim()}`));
return lines;
}
if (typeof removed === "string" && removed.trim()) {
lines.push(ok(`✅ Reaction removed: ${removed.trim()}`));
return lines;
}
if (Array.isArray(removed)) {
const list = removed
.map((x) => String(x).trim())
.filter(Boolean)
.join(", ");
lines.push(ok(`✅ Reactions removed${list ? `: ${list}` : ""}`));
return lines;
}
lines.push(ok("✅ Reaction updated."));
return lines;
}
const reactionsTable = renderReactions(payload, opts);
if (reactionsTable && result.action === "reactions") {
lines.push(heading("Reactions"));
lines.push(reactionsTable[0] ?? "");
return lines;
}
if (result.action === "read") {
const messagesTable = renderMessagesFromPayload(payload, opts);
if (messagesTable) {
lines.push(heading("Messages"));
lines.push(messagesTable[0] ?? "");
return lines;
}
}
if (result.action === "list-pins") {
const pinsTable = renderPinsFromPayload(payload, opts);
if (pinsTable) {
lines.push(heading("Pinned messages"));
lines.push(pinsTable[0] ?? "");
return lines;
}
}
if (result.action === "search") {
const results = (payload as { results?: unknown }).results;
const list = extractDiscordSearchResultsMessages(results);
if (list) {
lines.push(heading("Search results"));
lines.push(renderMessageList(list, opts, "No results.")[0] ?? "");
return lines;
}
}
// Generic success + compact details table.
lines.push(
ok(`${result.action} via ${resolveProviderLabel(result.provider)}.`),
);
const summary = renderObjectSummary(payload, opts);
if (summary.length) {
lines.push("");
lines.push(...summary);
lines.push("");
lines.push(muted("Tip: use --json for full output."));
}
return lines;
}

View File

@@ -1,286 +1,32 @@
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
import type { CliDeps } from "../cli/deps.js";
import { withProgress } from "../cli/progress.js";
import { loadConfig } from "../config/config.js";
import { success } from "../globals.js";
import type {
OutboundDeliveryResult,
OutboundSendDeps,
} from "../infra/outbound/deliver.js";
import { buildOutboundResultEnvelope } from "../infra/outbound/envelope.js";
import type { OutboundSendDeps } from "../infra/outbound/deliver.js";
import { runMessageAction } from "../infra/outbound/message-action-runner.js";
import {
buildOutboundDeliveryJson,
formatGatewaySummary,
formatOutboundDeliverySummary,
} from "../infra/outbound/format.js";
import {
type MessagePollResult,
type MessageSendResult,
sendMessage,
sendPoll,
} from "../infra/outbound/message.js";
import { resolveMessageProviderSelection } from "../infra/outbound/provider-selection.js";
import { dispatchProviderMessageAction } from "../providers/plugins/message-actions.js";
import type { ProviderMessageActionName } from "../providers/plugins/types.js";
PROVIDER_MESSAGE_ACTION_NAMES,
type ProviderMessageActionName,
} from "../providers/plugins/types.js";
import type { RuntimeEnv } from "../runtime.js";
import {
GATEWAY_CLIENT_MODES,
GATEWAY_CLIENT_NAMES,
} from "../utils/message-provider.js";
type MessageAction =
| "send"
| "poll"
| "react"
| "reactions"
| "read"
| "edit"
| "delete"
| "pin"
| "unpin"
| "list-pins"
| "permissions"
| "thread-create"
| "thread-list"
| "thread-reply"
| "search"
| "sticker"
| "member-info"
| "role-info"
| "emoji-list"
| "emoji-upload"
| "sticker-upload"
| "role-add"
| "role-remove"
| "channel-info"
| "channel-list"
| "voice-status"
| "event-list"
| "event-create"
| "timeout"
| "kick"
| "ban";
type MessageCommandOpts = {
action?: string;
provider?: string;
to?: string;
message?: string;
media?: string;
buttonsJson?: string;
messageId?: string;
replyTo?: string;
threadId?: string;
account?: string;
emoji?: string;
remove?: boolean;
limit?: string;
before?: string;
after?: string;
around?: string;
pollQuestion?: string;
pollOption?: string[] | string;
pollDurationHours?: string;
pollMulti?: boolean;
channelId?: string;
channelIds?: string[] | string;
guildId?: string;
userId?: string;
authorId?: string;
authorIds?: string[] | string;
roleId?: string;
roleIds?: string[] | string;
emojiName?: string;
stickerId?: string[] | string;
stickerName?: string;
stickerDesc?: string;
stickerTags?: string;
threadName?: string;
autoArchiveMin?: string;
query?: string;
eventName?: string;
eventType?: string;
startTime?: string;
endTime?: string;
desc?: string;
location?: string;
durationMin?: string;
until?: string;
reason?: string;
deleteDays?: string;
includeArchived?: boolean;
participant?: string;
fromMe?: boolean;
dryRun?: boolean;
json?: boolean;
gifPlayback?: boolean;
};
type MessageSendOpts = {
to: string;
message: string;
provider: string;
json?: boolean;
dryRun?: boolean;
media?: string;
gifPlayback?: boolean;
account?: string;
};
function normalizeAction(value?: string): MessageAction {
const raw = value?.trim().toLowerCase() || "send";
return raw as MessageAction;
}
function parseIntOption(value: unknown, label: string): number | undefined {
if (value === undefined || value === null) return undefined;
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value !== "string" || value.trim().length === 0) return undefined;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed)) {
throw new Error(`${label} must be a number`);
}
return parsed;
}
function requireString(value: unknown, label: string): string {
if (typeof value !== "string") {
throw new Error(`${label} required`);
}
const trimmed = value.trim();
if (!trimmed) {
throw new Error(`${label} required`);
}
return trimmed;
}
function optionalString(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const trimmed = value.trim();
return trimmed ? trimmed : undefined;
}
function toStringArray(value: unknown): string[] {
if (Array.isArray(value)) {
return value.map((entry) => String(entry).trim()).filter(Boolean);
}
if (typeof value === "string") {
const trimmed = value.trim();
return trimmed ? [trimmed] : [];
}
return [];
}
function extractToolPayload(result: AgentToolResult<unknown>): unknown {
if (result.details !== undefined) return result.details;
const textBlock = Array.isArray(result.content)
? result.content.find(
(block) =>
block &&
typeof block === "object" &&
(block as { type?: unknown }).type === "text" &&
typeof (block as { text?: unknown }).text === "string",
)
: undefined;
const text = (textBlock as { text?: string } | undefined)?.text;
if (text) {
try {
return JSON.parse(text);
} catch {
return text;
}
}
return result.content ?? result;
}
function logSendDryRun(opts: MessageSendOpts, runtime: RuntimeEnv) {
runtime.log(
`[dry-run] would send via ${opts.provider} -> ${opts.to}: ${opts.message}${
opts.media ? ` (media ${opts.media})` : ""
}`,
);
}
function logPollDryRun(result: MessagePollResult, runtime: RuntimeEnv) {
runtime.log(
`[dry-run] would send poll via ${result.provider} -> ${result.to}:\n Question: ${result.question}\n Options: ${result.options.join(
", ",
)}\n Max selections: ${result.maxSelections}`,
);
}
function logSendResult(
result: MessageSendResult,
opts: MessageSendOpts,
runtime: RuntimeEnv,
) {
if (result.via === "direct") {
const directResult = result.result as OutboundDeliveryResult | undefined;
const summary = formatOutboundDeliverySummary(
result.provider,
directResult,
);
runtime.log(success(summary));
if (opts.json) {
runtime.log(
JSON.stringify(
buildOutboundDeliveryJson({
provider: result.provider,
via: "direct",
to: opts.to,
result: directResult,
mediaUrl: opts.media ?? null,
}),
null,
2,
),
);
}
return;
}
const gatewayResult = result.result as { messageId?: string } | undefined;
runtime.log(
success(
formatGatewaySummary({
provider: result.provider,
messageId: gatewayResult?.messageId ?? null,
}),
),
);
if (opts.json) {
runtime.log(
JSON.stringify(
buildOutboundResultEnvelope({
delivery: buildOutboundDeliveryJson({
provider: result.provider,
via: "gateway",
to: opts.to,
result: gatewayResult,
mediaUrl: opts.media ?? null,
}),
}),
null,
2,
),
);
}
}
import { buildMessageCliJson, formatMessageCliText } from "./message-format.js";
export async function messageCommand(
opts: MessageCommandOpts,
opts: Record<string, unknown>,
deps: CliDeps,
runtime: RuntimeEnv,
) {
const cfg = loadConfig();
const action = normalizeAction(opts.action);
const providerSelection = await resolveMessageProviderSelection({
cfg,
provider: opts.provider,
});
const provider = providerSelection.provider;
const accountId = optionalString(opts.account);
const actionParams = opts as Record<string, unknown>;
const rawAction =
typeof opts.action === "string" ? opts.action.trim().toLowerCase() : "";
const action = (rawAction || "send") as ProviderMessageActionName;
if (!(PROVIDER_MESSAGE_ACTION_NAMES as readonly string[]).includes(action)) {
throw new Error(`Unknown message action: ${action}`);
}
const outboundDeps: OutboundSendDeps = {
sendWhatsApp: deps.sendMessageWhatsApp,
sendTelegram: deps.sendMessageTelegram,
@@ -292,215 +38,40 @@ export async function messageCommand(
deps.sendMessageMSTeams({ cfg, to, text, mediaUrl: opts?.mediaUrl }),
};
if (opts.dryRun && action !== "send" && action !== "poll") {
runtime.log(`[dry-run] would run ${action} via ${provider}`);
return;
}
if (action === "send") {
const to = requireString(opts.to, "to");
const message = requireString(opts.message, "message");
const sendOpts: MessageSendOpts = {
to,
message,
provider,
json: opts.json,
dryRun: opts.dryRun,
media: optionalString(opts.media),
gifPlayback: opts.gifPlayback,
account: accountId,
};
if (opts.dryRun) {
logSendDryRun(sendOpts, runtime);
return;
}
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
const run = async () =>
await runMessageAction({
cfg,
params: actionParams,
accountId,
action,
params: opts,
deps: outboundDeps,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
const payload = extractToolPayload(handled);
if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2));
} else {
runtime.log(success(`Sent via ${provider}.`));
}
return;
}
const result = await withProgress(
{
label: `Sending via ${provider}...`,
indeterminate: true,
enabled: opts.json !== true,
},
async () =>
await sendMessage({
cfg,
to,
content: message,
provider,
mediaUrl: optionalString(opts.media),
gifPlayback: opts.gifPlayback,
accountId,
dryRun: opts.dryRun,
deps: outboundDeps,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
}),
);
logSendResult(result, sendOpts, runtime);
return;
}
const json = opts.json === true;
const dryRun = opts.dryRun === true;
const needsSpinner =
!json && !dryRun && (action === "send" || action === "poll");
if (action === "poll") {
const to = requireString(opts.to, "to");
const question = requireString(opts.pollQuestion, "poll-question");
const options = toStringArray(opts.pollOption);
if (options.length < 2) {
throw new Error("poll-option requires at least two values");
}
const durationHours = parseIntOption(
opts.pollDurationHours,
"poll-duration-hours",
);
const allowMultiselect = Boolean(opts.pollMulti);
const maxSelections = allowMultiselect ? Math.max(2, options.length) : 1;
if (opts.dryRun) {
const result = await sendPoll({
cfg,
to,
question,
options,
maxSelections,
durationHours,
provider,
dryRun: true,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
const result = needsSpinner
? await withProgress(
{
label: action === "poll" ? "Sending poll..." : "Sending...",
indeterminate: true,
enabled: true,
},
});
logPollDryRun(result, runtime);
return;
}
run,
)
: await run();
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
cfg,
params: actionParams,
accountId,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
const payload = extractToolPayload(handled);
if (opts.json) {
runtime.log(JSON.stringify(payload, null, 2));
} else {
runtime.log(success(`Poll sent via ${provider}.`));
}
return;
}
const result = await withProgress(
{
label: `Sending poll via ${provider}...`,
indeterminate: true,
enabled: opts.json !== true,
},
async () =>
await sendPoll({
cfg,
to,
question,
options,
maxSelections,
durationHours,
provider,
dryRun: opts.dryRun,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
}),
);
runtime.log(
success(
formatGatewaySummary({
action: "Poll sent",
provider,
messageId: result.result?.messageId ?? null,
}),
),
);
const pollId = (result.result as { pollId?: string } | undefined)?.pollId;
if (pollId) {
runtime.log(success(`Poll id: ${pollId}`));
}
if (opts.json) {
runtime.log(
JSON.stringify(
{
...buildOutboundResultEnvelope({
delivery: buildOutboundDeliveryJson({
provider,
via: "gateway",
to,
result: result.result,
mediaUrl: null,
}),
}),
question: result.question,
options: result.options,
maxSelections: result.maxSelections,
durationHours: result.durationHours,
pollId,
},
null,
2,
),
);
}
if (json) {
runtime.log(JSON.stringify(buildMessageCliJson(result), null, 2));
return;
}
const handled = await dispatchProviderMessageAction({
provider,
action: action as ProviderMessageActionName,
cfg,
params: actionParams,
accountId,
gateway: {
clientName: GATEWAY_CLIENT_NAMES.CLI,
mode: GATEWAY_CLIENT_MODES.CLI,
},
dryRun: opts.dryRun,
});
if (handled) {
runtime.log(JSON.stringify(extractToolPayload(handled), null, 2));
return;
for (const line of formatMessageCliText(result)) {
runtime.log(line);
}
throw new Error(
`Action ${action} is not supported for provider ${provider}.`,
);
}