mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 15:38:23 +00:00
mcp server: files, /leave and library methods (#7962)
* bots, nodejs: document chat, connection, member contact and network commands, typed commands in library * bots, nodejs: restore apiConnect, wrap domain once, test all connect responses * nodejs: JSDoc for new methods * docs: plan for bot API commands and typed Node library methods * tests: channel prepared with a domain has a verified SimpleX name * docs: apply review fixes to the plan for bot API commands * docs: apply second review pass to the plan for bot API commands * docs: refer the bot API plan to the rewritten test commit * docs: record decisions in the plan for bot API commands * docs: plan tests of the generated Python command strings * python: test the generated strings of the documented commands * docs: plan for files, /leave and library methods in the MCP server * docs: wait at stop in the MCP plan * docs: library methods and /leave mechanics in the MCP plan * mcp: typed library methods for chat commands * docs: plan the message information command for bots * mcp: /leave CHAT owner command to leave a chat at once * docs: file servers, GIF and video choices decided in the MCP plan * docs: file mechanics in the MCP plan * mcp: files of received messages * bots, nodejs: message information with the file servers for bots * docs: plan the relay approval option of receiving files in Node * mcp: download of received files with owner approval * docs: name the xftp-server test helper in the files plan * nodejs: receive files without approving unknown relays * docs: plan the user servers command for bots * bots, nodejs: user servers and relays by operator for bots * nodejs: document the message information method * docs: plan the file upload progress event for bots * mcp: send files with owner approval, refusing private keys * bots: file upload progress event for bots * mcp: /leave template in the agent control chat menu * docs: sent copies are deleted for contacts too, at sndFileCompleteXFTP * bots: drop the file upload progress event * docs: drop the upload progress event plan * nodejs: document user servers and relay approval of received files * mcp: download cards name unknown file servers after the upload * docs: record the wait for the file description in the files plan * mcp: fixed wait at stop for cancelled cards, without /sql * docs: record decision C4, a fixed wait at stop, in the files plan * ci: test the MCP server package on pull requests * ci: state when the MCP workflow can be dispatched * ci: run the MCP server tests when its libraries change * mcp: log the errors of image previews and resizing * mcp: keep files in transfer in the data folder * mcp: restrict sent files by the real paths of refused folders * mcp: validate the file at the send by its inode and change time * mcp: limit ffmpeg and ffprobe to local files and no input commands * mcp: ask the owner for unknown file servers; read approvals at creation * mcp: name downloaded files by their ID; return paths of downloads only * mcp: end each download with a result for the agent and the card * mcp: show files above their sender's size limit as failed * mcp: refuse empty files, as without file and captions too long to send * mcp: tell the owner about failed uploads and unposted received files * mcp: delete resized copies left by the last run at start * mcp: name downloads and leaving in the help and greeting, align docs * mcp: compute the download path for received files only * mcp: send a /receive file to the owner under its name * mcp: keep files received without a download in the chat's folder * mcp: keep a left chat's files and delete them with /delete CHAT files * mcp: test that sent images are resized by the core * mcp: wait 30 minutes for a download's progress before cancelling it * mcp: end a download as deleted only when its message is not found * mcp: delete the copy of a /receive file whose post fails * mcp: count the quoted content in a message's length, as the core sends it * mcp: name received bytes, unknown-server downloads and left chat files plainly * mcp: test refused folders, file changes and download approvals * docs: align MCP server docs with refused folders, leaves and download waits * mcp: move received files only in full, delete partials only of downloads * mcp: report a received file missing from its folder as failed * mcp: move received files of a group's member chats into its folder * mcp: read a video's preview and duration as an MP4 or QuickTime file * mcp: 0.2.0 on simplex-chat 7.1.0-beta.10.1 * mcp: file folders by chat type, /delete cancels downloads, files reply * docs: MCP server specs and plan for 0.2.0 * mcp: /receive gives the agent a file, /forward sends it to the owner * docs: MCP server specs for /receive and /forward of download cards * docs: MCP plan records the temp folder command as a library exception * mcp: /delete cancels resumed downloads; /forward quote fits the limit * docs: MCP specs and plans for /forward quotes and resumed downloads * docs: MCP specs name the source commit they are checked against * docs: MCP PLAN states the /forward quote and move rules * mcp: a download moves its completed file whatever its size * mcp: /receive N all covers its card and later files, not pending ones * docs: MCP files approval scope, reply text and README server wording * mcp: a download approves relays only for a card naming unknown servers * mcp: files in member chats of a group are tracked as in the main chat * docs: MCP relay approval of downloads and files in member chats * mcp: a rejected file gets a card again under the files approval * docs: MCP rejected files under the files approval, README scope * mcp: an offered file without a description gets no card or action * docs: MCP a file without a description is not downloaded * mcp: 0.2.0 on simplex-chat 7.1.0-beta.10.2 * ci: test the MCP server as a scope of build-linux
This commit is contained in:
1 parent
911f8986e5
commit
be668564df
35 files changed
+4930
-960
No files matched your search
@@ -1,9 +1,10 @@
|
||||
import {errorText, log, logError, oneLine} from "./log"
|
||||
import {Changes, Collected, ToolCall, nextChange, reportProgress, utcMinutes} from "./messages"
|
||||
import type {ConnectInput, LeaveInput, PlanSummary, SendInput} from "./tools"
|
||||
import {Changes, Collected, FileOffer, FileType, ToolCall, nextChange, reportProgress, utcMinutes} from "./messages"
|
||||
import type {ConnectInput, DownloadInput, LeaveInput, PlanSummary, SendInput} from "./tools"
|
||||
|
||||
export type Mode = "requests" | "host"
|
||||
export type State = "pending" | "performing" | "done" | "failed" | "rejected" | "expired"
|
||||
export type Standing = "messages" | "files"
|
||||
|
||||
const progressTick = 60_000
|
||||
const expiryTick = 60_000
|
||||
@@ -44,6 +45,7 @@ interface ActionRecord {
|
||||
interrupted: boolean
|
||||
error?: string
|
||||
stopCollecting?: () => void
|
||||
cardImage?: string
|
||||
}
|
||||
|
||||
export interface ConnectAction extends ActionRecord {
|
||||
@@ -62,11 +64,24 @@ export interface ConnectAction extends ActionRecord {
|
||||
linkTextBytes?: number
|
||||
}
|
||||
|
||||
export interface Attachment {
|
||||
readonly path: string
|
||||
readonly name: string
|
||||
readonly size: number
|
||||
readonly inode: number
|
||||
readonly changedAt: number
|
||||
readonly type: FileType
|
||||
readonly resize: boolean
|
||||
readonly preview?: string
|
||||
readonly duration?: number
|
||||
}
|
||||
|
||||
export interface SendAction extends ActionRecord {
|
||||
readonly tool: "send"
|
||||
readonly input: SendInput
|
||||
readonly subject: Subject
|
||||
readonly chat: string
|
||||
readonly file?: Attachment
|
||||
readonly replyTo?: {from: string; text: string}
|
||||
readonly mentions: {name: string; member: number}[]
|
||||
readonly responses: Collected
|
||||
@@ -81,9 +96,22 @@ export interface LeaveAction extends ActionRecord {
|
||||
readonly chat: string
|
||||
}
|
||||
|
||||
export type Action = ConnectAction | SendAction | LeaveAction
|
||||
export interface DownloadAction extends ActionRecord {
|
||||
readonly tool: "download"
|
||||
readonly input: DownloadInput
|
||||
readonly subject: Subject
|
||||
readonly chat: string
|
||||
readonly item: number
|
||||
readonly from?: string
|
||||
readonly file: FileOffer
|
||||
readonly unknownServers?: string[]
|
||||
startedAt?: number
|
||||
path?: string
|
||||
}
|
||||
|
||||
export type NewAction = Omit<ConnectAction, keyof ActionRecord> | Omit<SendAction, keyof ActionRecord> | Omit<LeaveAction, keyof ActionRecord>
|
||||
export type Action = ConnectAction | SendAction | LeaveAction | DownloadAction
|
||||
|
||||
export type NewAction = Omit<ConnectAction, keyof ActionRecord> | Omit<SendAction, keyof ActionRecord> | Omit<LeaveAction, keyof ActionRecord> | Omit<DownloadAction, keyof ActionRecord>
|
||||
|
||||
export interface ActionHooks {
|
||||
refusal(action: Action): string | undefined
|
||||
@@ -175,12 +203,12 @@ export class Actions {
|
||||
}
|
||||
}
|
||||
|
||||
async decided(action: Action, call: ToolCall): Promise<boolean> {
|
||||
async decided(action: Action, call: ToolCall, until: () => number = () => Infinity): Promise<boolean> {
|
||||
if (isDecided(action.state)) return true
|
||||
const stopProgress = reportProgress(call, () => progressText(action))
|
||||
try {
|
||||
while (!isDecided(action.state)) {
|
||||
if (!(await nextChange(action.changes, call.signal, progressTick))) return false
|
||||
while (!isDecided(action.state) && Date.now() < until()) {
|
||||
if (!(await nextChange(action.changes, call.signal, Math.min(progressTick, until() - Date.now())))) return false
|
||||
}
|
||||
return true
|
||||
} finally {
|
||||
@@ -209,7 +237,7 @@ export class Actions {
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<number> {
|
||||
async stop(): Promise<Action[]> {
|
||||
this.stopping = true
|
||||
clearInterval(this.expiry)
|
||||
await Promise.all(this.posting.values())
|
||||
@@ -218,7 +246,7 @@ export class Actions {
|
||||
this.abortPerforms.abort()
|
||||
if (!this.lost) await Promise.all(stopped.map(action => this.hooks.outcome(action).catch(error => logError(`action ${action.n} card`, error))))
|
||||
await Promise.allSettled(this.outcomes)
|
||||
return stopped.length
|
||||
return stopped
|
||||
}
|
||||
|
||||
private async post(action: Action): Promise<boolean> {
|
||||
@@ -271,6 +299,10 @@ export class Actions {
|
||||
}
|
||||
}
|
||||
|
||||
export function hasUnknownServers({unknownServers}: Pick<DownloadAction, "unknownServers">): boolean {
|
||||
return unknownServers !== undefined && unknownServers.length > 0
|
||||
}
|
||||
|
||||
export function isDecided(state: State): boolean {
|
||||
return state === "done" || state === "failed" || state === "rejected" || state === "expired"
|
||||
}
|
||||
@@ -289,10 +321,12 @@ export function summary(action: Action, showName: (name: string) => string): {wh
|
||||
return {what: `send to ${target}`, detail: ` (${action.chat})`}
|
||||
case "leave":
|
||||
return {what: `${leaveVerbs(action).present} ${target}`, detail: ` (${action.chat})`}
|
||||
case "download":
|
||||
return {what: `download ${showName(action.file.name)} from ${target}`, detail: ` (${action.chat})`}
|
||||
}
|
||||
}
|
||||
|
||||
export function leaveVerbs({chat}: LeaveAction): {present: string; past: string} {
|
||||
export function leaveVerbs({chat}: Pick<LeaveAction, "chat">): {present: string; past: string} {
|
||||
return chat.startsWith("@") ? {present: "delete", past: "deleted"} : {present: "leave", past: "left"}
|
||||
}
|
||||
|
||||
@@ -302,6 +336,7 @@ function performedText(action: Action, mode: Mode): string {
|
||||
if (failure !== "") return `failed: ${oneLine(action.error ?? "")}.`
|
||||
if (action.tool === "send") return "sent."
|
||||
if (action.tool === "leave") return `${leaveVerbs(action).past}.`
|
||||
if (action.tool === "download") return "downloaded."
|
||||
return action.connected ? "connected." : "connection requested."
|
||||
}
|
||||
|
||||
|
||||
@@ -15,13 +15,16 @@ serve options:
|
||||
--data DIR data folder (default: ~/.simplex-mcp/NAME)
|
||||
--display-name TEXT the agent's name in SimpleX (default at the first start: NAME)
|
||||
--approve MODE what the owner approves in the agent control chat:
|
||||
requests the agent's connections and messages (default)
|
||||
requests the agent's connections, messages, downloads
|
||||
and leaving chats (default)
|
||||
host nothing; the MCP host asks
|
||||
--owners [ID:NAME,...] only these owners approve; without a list, the link
|
||||
adds an observer and its ID is printed at the join.
|
||||
Without --owners, whoever joins becomes an owner and
|
||||
every owner approves.
|
||||
--expire HOURS pending actions expire after HOURS, 1 to 23 (default: 23)
|
||||
--stop-wait SECONDS at stop, wait SECONDS for cancelled cards to be sent,
|
||||
0 to 60 (default: 10)
|
||||
--reset-owners replace the owners: a new agent control chat and link
|
||||
--new-token replace the access token
|
||||
--port N HTTP port on 127.0.0.1 (default: 5226)
|
||||
@@ -58,6 +61,7 @@ function serveOptions(name: string, options: OptionReader, home: string): ServeO
|
||||
newToken: false,
|
||||
port: 5226,
|
||||
qrCode: "small",
|
||||
stopWait: 10,
|
||||
dataGiven: false,
|
||||
}
|
||||
for (let option = options.next(); option !== undefined; option = options.next()) {
|
||||
@@ -78,6 +82,9 @@ function serveOptions(name: string, options: OptionReader, home: string): ServeO
|
||||
case "--expire":
|
||||
serve.expireHours = integer(option, options.value(option), 1, 23, "hours from 1 to 23")
|
||||
break
|
||||
case "--stop-wait":
|
||||
serve.stopWait = integer(option, options.value(option), 0, 60, "seconds from 0 to 60")
|
||||
break
|
||||
case "--reset-owners":
|
||||
serve.resetOwners = true
|
||||
break
|
||||
|
||||
@@ -1,25 +1,34 @@
|
||||
import {ChatEvent, T} from "@simplex-chat/types"
|
||||
import {CEvt, ChatEvent, T} from "@simplex-chat/types"
|
||||
import * as qrcode from "qrcode"
|
||||
import {api} from "simplex-chat"
|
||||
import {Action, ActionHooks, Actions, ConnectAction, Subject, ToolError, leaveVerbs, subjectText, summary} from "./actions"
|
||||
import {ExitError, chatErrorOf, log, logError, oneLine, shellWord} from "./log"
|
||||
import {chatNumber, chatRef, isChatRef, utcMinutes, validName, viewName} from "./messages"
|
||||
import {api, core} from "simplex-chat"
|
||||
import {Action, ActionHooks, Actions, ConnectAction, DownloadAction, Standing, Subject, ToolError, hasUnknownServers, leaveVerbs, subjectText, summary} from "./actions"
|
||||
import {ExitError, chatErrorOf, errorText, fileError, log, logError, oneLine, serverHostname, shellWord} from "./log"
|
||||
import {chatNumber, chatRef, fileContent, isChatRef, utcMinutes, validName, viewName} from "./messages"
|
||||
import type {OwnerEntry, QrCodeSize} from "./serve"
|
||||
import {AgentTools, chatSubject, isActive, isConnected, memberCurrent} from "./tools"
|
||||
import {AgentTools, chatSubject, fitsMessage, isActive, isConnected, memberCurrent, refusedFileReason} from "./tools"
|
||||
|
||||
const controlCommands: T.ChatBotCommand[] = [
|
||||
{type: "command", keyword: "pending", label: "Pending actions"},
|
||||
{type: "command", keyword: "list", label: "Chats and approvals"},
|
||||
{type: "command", keyword: "leave", label: "Leave a chat", params: "<chat ID>"},
|
||||
]
|
||||
|
||||
const commandsReply = "Commands: /approve, /reject, /revoke, /pending, /list. Each card shows its commands."
|
||||
const cardTooLong = {send: "text: too long for its approval card; shorten it.", connect: "message: too long for its approval card; shorten it."}
|
||||
const commandsReply = "Commands: /approve, /reject, /receive, /forward, /revoke, /leave, /delete, /pending, /list. Each card shows its commands."
|
||||
const cardTooLong = {
|
||||
send: "text: too long for its approval card; shorten it.",
|
||||
connect: "message: too long for its approval card; shorten it.",
|
||||
download: "item: the names of its file and chat are too long for its approval card.",
|
||||
}
|
||||
const standings: {[standing in Standing]: {key: string; approved: string; scope: string; revoke: (chat: string) => string; listed: string}} = {
|
||||
messages: {key: "simplexMcp", approved: "Approved for", scope: "Messages to", revoke: chat => `revoke ${chat}`, listed: "approved for this chat by"},
|
||||
files: {key: "simplexMcpFiles", approved: "Files approved for", scope: "Files from", revoke: chat => `receive ${chat} off`, listed: "files approved by"},
|
||||
}
|
||||
const maxCardLength = 15_000
|
||||
const listedChats = 100
|
||||
const maxLineLength = 100
|
||||
const truncationMark = "…"
|
||||
const longestError = "€".repeat(600)
|
||||
const greeting = "I'm your agent. I ask here before I connect or send."
|
||||
const greeting = "I'm your agent. I ask here before I connect, send, download a file or leave a chat."
|
||||
const noOwners = "No owners in the agent control chat."
|
||||
const qrCodeHint = "If the QR code does not scan, restart with --qr-code large, or paste the link into the app."
|
||||
const qrMargin = 2
|
||||
@@ -55,8 +64,10 @@ interface ChatApproval {
|
||||
}
|
||||
|
||||
type OwnerRequest =
|
||||
| {type: "approve" | "reject"; action: number; chat?: string}
|
||||
| {type: "approveChat" | "revoke"; chat: string}
|
||||
| {type: "approve" | "reject" | "receive" | "forward"; action: number; chat?: string}
|
||||
| {type: "receiveAll"; action: number; chat: string}
|
||||
| {type: "approveChat" | "revoke"; chat: string; standing: Standing}
|
||||
| {type: "leave" | "deleteFiles"; chat: string}
|
||||
| {type: "pending" | "list"}
|
||||
|
||||
interface Shown {
|
||||
@@ -77,7 +88,7 @@ export class Control implements Pick<ActionHooks, "refusal" | "saveCounter" | "p
|
||||
private group: T.GroupInfo,
|
||||
private readonly options: ControlOptions,
|
||||
private readonly actions: Actions,
|
||||
private readonly tools: Pick<AgentTools, "knownChat" | "agentChats">,
|
||||
private readonly tools: Pick<AgentTools, "knownChat" | "agentChats" | "leaveChat" | "forwardFile" | "deleteSentCopy" | "chatFiles" | "deleteChatFiles">,
|
||||
) {}
|
||||
|
||||
get groupId(): number {
|
||||
@@ -116,8 +127,8 @@ export class Control implements Pick<ActionHooks, "refusal" | "saveCounter" | "p
|
||||
: "The agent has no approving owner. The person who runs it has to restart it with the --owners options it printed."
|
||||
}
|
||||
|
||||
standingApprover(chatInfo: T.ChatInfo): string | undefined {
|
||||
const approval = approvalOf(customDataOf(chatInfo))
|
||||
standingApprover(chatInfo: T.ChatInfo, standing: Standing): string | undefined {
|
||||
const approval = approvalOf(customDataOf(chatInfo), standings[standing].key)
|
||||
return this.actions.mode === "requests" && approval !== undefined && this.approvers().some(({groupMemberId}) => groupMemberId === approval.approvedById) ? safeName(approval.approvedBy) : undefined
|
||||
}
|
||||
|
||||
@@ -128,13 +139,33 @@ export class Control implements Pick<ActionHooks, "refusal" | "saveCounter" | "p
|
||||
}
|
||||
|
||||
async postCard(action: Action): Promise<number> {
|
||||
return this.post(cardText(action, this.actions.mode))
|
||||
return this.postMessage({msgContent: await this.cardContent(action), mentions: {}})
|
||||
}
|
||||
|
||||
async outcome(action: Action): Promise<void> {
|
||||
const text = cardText(action, this.actions.mode)
|
||||
if (action.card === undefined) await this.post(text)
|
||||
else await this.chat.apiUpdateChatItem(T.ChatType.Group, this.groupId, action.card, {type: "text", text}, false)
|
||||
if (!hasOutcomeCard(action)) return
|
||||
const content = await this.cardContent(action)
|
||||
if (action.card === undefined) await this.postMessage({msgContent: content, mentions: {}})
|
||||
else await this.chat.apiUpdateChatItem(T.ChatType.Group, this.groupId, action.card, content, false)
|
||||
const filesNote = action.tool === "leave" && action.state === "done" ? this.leftChatFilesNote(action.chat, action.subject) : undefined
|
||||
if (filesNote !== undefined) await this.post(filesNote)
|
||||
}
|
||||
|
||||
refusedFile(path: string, chatInfo: T.ChatInfo, chat: string): void {
|
||||
const refused = (shown: Shown, shownPath: string): string => `Refused to send ${shownPath} to ${chatName(chatSubject(chatInfo), shown.name)} (${chat}): ${refusedFileReason}.`
|
||||
log(refused(inLog, oneLine(path)))
|
||||
if (!this.actions.lost) this.post(refused(inChat, codeSpan(oneLine(path)))).catch(error => logError("refused file", error))
|
||||
}
|
||||
|
||||
fileNotSent({chatItem_, errorMessage}: CEvt.SndFileError): void {
|
||||
const file = chatItem_?.chatItem.file
|
||||
const chat = chatItem_ === undefined ? undefined : chatRef(chatItem_.chatInfo)
|
||||
if (chatItem_ === undefined || file === undefined || chat === undefined) return logError("file not sent", errorMessage)
|
||||
const {chatInfo} = chatItem_
|
||||
const reason = fileError(file) ?? errorMessage
|
||||
const notSent = (shown: Shown, name: string, error: string): string => `The file ${name} was not sent to ${chatName(chatSubject(chatInfo), shown.name)} (${chat}): ${error}.`
|
||||
log(notSent(inLog, oneLine(file.fileName), oneLine(reason)))
|
||||
if (!this.actions.lost) this.post(notSent(inChat, codeSpan(oneLine(file.fileName)), codeSpan(oneLine(reason)))).catch(error => logError("file not sent", error))
|
||||
}
|
||||
|
||||
onMessage(ci: T.AChatItem): void {
|
||||
@@ -180,50 +211,114 @@ export class Control implements Pick<ActionHooks, "refusal" | "saveCounter" | "p
|
||||
return this.chatsText()
|
||||
case "approveChat":
|
||||
if (this.actions.mode === "host") return "Approvals apply in mode requests; this server runs in mode host."
|
||||
return this.approveChat(sender, request.chat)
|
||||
return this.approveChat(sender, request.chat, request.standing)
|
||||
case "revoke":
|
||||
return this.revoke(request.chat)
|
||||
return this.revoke(request.chat, request.standing)
|
||||
case "leave":
|
||||
return this.leave(sender, request.chat)
|
||||
case "deleteFiles":
|
||||
return this.deleteFiles(request.chat)
|
||||
case "approve":
|
||||
case "reject": {
|
||||
case "reject":
|
||||
case "receive":
|
||||
case "forward":
|
||||
case "receiveAll": {
|
||||
const action = this.actions.get(request.action)
|
||||
if (action === undefined || action.state !== "pending" || action.card === undefined) return `Action ${request.action} is not pending.`
|
||||
if (request.chat !== undefined && (action.tool === "connect" || action.chat !== request.chat)) return `Action ${request.action} is not for ${request.chat}.`
|
||||
const approver = safeName(sender.memberProfile.displayName)
|
||||
if (request.type === "approve") this.actions.approve(action, approver)
|
||||
else this.actions.reject(action, approver)
|
||||
if (request.type === "reject") this.actions.reject(action, approver)
|
||||
else if (action.tool !== "download") {
|
||||
if (request.type !== "approve") return `Action ${request.action} is not a download.`
|
||||
this.actions.approve(action, approver)
|
||||
} else if (request.type === "approve") return `Action ${action.n} is a download: ${commandsLine(action)}.`
|
||||
else if (request.type === "receive") this.actions.approve(action, approver)
|
||||
else if (request.type === "forward") this.forward(action)
|
||||
else return this.approveChat(sender, action.chat, "files", action)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async approveChat(sender: T.GroupMember, chat: string): Promise<string> {
|
||||
private async approveChat(sender: T.GroupMember, chat: string, standing: Standing, named?: Action): Promise<string> {
|
||||
const {key, approved, revoke} = standings[standing]
|
||||
const chatInfo = await this.agentChat(chat)
|
||||
if (chatInfo === undefined) return `No chat ${chat}. /list shows the agent's chats.`
|
||||
const approvedBy = sender.memberProfile.displayName
|
||||
const approval: ChatApproval = {approvedBy, approvedById: sender.groupMemberId, approvedAt: new Date().toISOString()}
|
||||
await this.setCustomData(chat, {...customDataOf(chatInfo), simplexMcp: approval})
|
||||
await this.setCustomData(chat, {...customDataOf(chatInfo), [key]: approval})
|
||||
const approver = safeName(approvedBy)
|
||||
for (const action of this.actions.pending()) {
|
||||
if (action.tool === "send" && action.chat === chat && action.card !== undefined) this.actions.approve(action, approver)
|
||||
}
|
||||
return `Approved for ${chatName(chatSubject(chatInfo))} (${chat}) by ${approver}. /'revoke ${chat}'`
|
||||
const pending = this.actions.pending().filter(action => (named === undefined ? action.tool === "send" && action.chat === chat && action.card !== undefined : action === named))
|
||||
for (const action of pending) this.actions.approve(action, approver)
|
||||
return `${approved} ${chatName(chatSubject(chatInfo))} (${chat}) by ${approver}. /'${revoke(chat)}'`
|
||||
}
|
||||
|
||||
private async revoke(chat: string): Promise<string> {
|
||||
private async revoke(chat: string, standing: Standing): Promise<string> {
|
||||
const {key, scope} = standings[standing]
|
||||
const chatInfo = await this.agentChat(chat)
|
||||
if (chatInfo === undefined || approvalOf(customDataOf(chatInfo)) === undefined) return `Messages to ${chat} have no standing approval.`
|
||||
const {simplexMcp, ...customData} = customDataOf(chatInfo) as {simplexMcp: unknown}
|
||||
if (chatInfo === undefined || approvalOf(customDataOf(chatInfo), key) === undefined) return `${scope} ${chat} have no standing approval.`
|
||||
const {[key]: _, ...customData} = customDataOf(chatInfo) as {[key: string]: unknown}
|
||||
await this.setCustomData(chat, customData)
|
||||
return `Messages to ${chatName(chatSubject(chatInfo))} (${chat}) need approval again.`
|
||||
return `${scope} ${chatName(chatSubject(chatInfo))} (${chat}) need approval again.`
|
||||
}
|
||||
|
||||
private forward(action: DownloadAction): void {
|
||||
this.tools
|
||||
.forwardFile(action)
|
||||
.then(copy =>
|
||||
this.cardContent(action)
|
||||
.then(card => {
|
||||
const msgContent = fileContent(action.file, "")
|
||||
return this.postMessage({fileSource: {filePath: copy}, msgContent, quotedItemId: fitsMessage(msgContent, action.file.name, {content: card}) ? action.card : undefined, mentions: {}})
|
||||
})
|
||||
.catch(error => {
|
||||
this.tools.deleteSentCopy(copy)
|
||||
throw error
|
||||
}),
|
||||
)
|
||||
.catch(error => this.post(`Action ${action.n}: the file was not received: ${codeSpan(oneLine(errorText(error)))}.`))
|
||||
.catch(error => logError(`action ${action.n} file`, error))
|
||||
}
|
||||
|
||||
private async leave(sender: T.GroupMember, chat: string): Promise<string> {
|
||||
const chatInfo = await this.agentChat(chat)
|
||||
if (chatInfo === undefined) return `No chat ${chat}. /list shows the agent's chats.`
|
||||
await this.tools.leaveChat(chat)
|
||||
const {past} = leaveVerbs({chat})
|
||||
const left = (shown: Shown): string => `${past[0].toUpperCase()}${past.slice(1)} ${chatName(chatSubject(chatInfo), shown.name)} (${chat}), requested by ${shown.name(sender.memberProfile.displayName)}.`
|
||||
log(left(inLog))
|
||||
const approver = safeName(sender.memberProfile.displayName)
|
||||
for (const action of this.actions.pending()) {
|
||||
if (action.chat === chat && action.card !== undefined) this.actions.reject(action, approver)
|
||||
}
|
||||
const filesNote = this.leftChatFilesNote(chat, chatSubject(chatInfo))
|
||||
if (filesNote !== undefined) this.queueAfterReplies(() => this.post(filesNote))
|
||||
return left(inChat)
|
||||
}
|
||||
|
||||
private leftChatFilesNote(chat: string, subject: Subject): string | undefined {
|
||||
const {folder, count, bytes} = this.tools.chatFiles(chat)
|
||||
return count === 0 ? undefined : `Files from ${chatName(subject)} (${chat}) are kept in ${codeSpan(oneLine(folder))}: ${filesText(count)}, ${sizeText(bytes)}. /'delete ${chat} files'`
|
||||
}
|
||||
|
||||
private async deleteFiles(chat: string): Promise<string> {
|
||||
const {count, bytes} = await this.tools.deleteChatFiles(chat)
|
||||
return count === 0 ? `No files from ${chat}.` : `Deleted ${filesText(count)} from ${chat}, ${sizeText(bytes)}.`
|
||||
}
|
||||
|
||||
private queueAfterReplies(post: () => Promise<unknown>): void {
|
||||
this.ownerCommands = this.ownerCommands.then(post).catch(error => logError("control chat command", error))
|
||||
}
|
||||
|
||||
private async chatsText(): Promise<string> {
|
||||
const chats = await this.tools.agentChats()
|
||||
const lines = chats.slice(0, listedChats).map(({chatInfo}) => {
|
||||
const approvedBy = this.standingApprover(chatInfo)
|
||||
const approval = approvedBy === undefined ? "" : `, approved for this chat by ${approvedBy}`
|
||||
const approvals = (["messages", "files"] as const).map(standing => {
|
||||
const approvedBy = this.standingApprover(chatInfo, standing)
|
||||
return approvedBy === undefined ? "" : `, ${standings[standing].listed} ${approvedBy}`
|
||||
})
|
||||
const connection = isConnected(chatInfo) ? "" : ", not connected"
|
||||
return truncatedLine(`${chatRef(chatInfo)} ${chatName(chatSubject(chatInfo))}${approval}${connection}`, maxLineLength)
|
||||
return truncatedLine(`${chatRef(chatInfo)} ${chatName(chatSubject(chatInfo))}${approvals.join("")}${connection}`, maxLineLength)
|
||||
})
|
||||
const rest = chats.length - lines.length
|
||||
if (rest > 0) lines.push(`${rest} older chat${rest === 1 ? " is" : "s are"} not shown.`)
|
||||
@@ -335,10 +430,36 @@ export class Control implements Pick<ActionHooks, "refusal" | "saveCounter" | "p
|
||||
}
|
||||
|
||||
private async post(text: string): Promise<number> {
|
||||
const [item] = await this.chat.apiSendMessages([T.ChatType.Group, this.groupId], [{msgContent: {type: "text", text}, mentions: {}}])
|
||||
return this.postMessage({msgContent: {type: "text", text}, mentions: {}})
|
||||
}
|
||||
|
||||
private async postMessage(message: T.ComposedMessage): Promise<number> {
|
||||
const [item] = await this.chat.apiSendMessages([T.ChatType.Group, this.groupId], [message])
|
||||
return item.chatItem.meta.itemId
|
||||
}
|
||||
|
||||
private async cardContent(action: Action): Promise<T.MsgContent> {
|
||||
const text = cardText(action, this.actions.mode)
|
||||
const file = action.tool === "download" || action.tool === "send" ? action.file : undefined
|
||||
const content = file === undefined ? undefined : fileContent(file, text)
|
||||
if (content?.type !== "image" && content?.type !== "video") return {type: "text", text}
|
||||
action.cardImage ??= await this.fittedImage(action, content)
|
||||
return action.cardImage === "" ? {type: "text", text} : {...content, image: action.cardImage}
|
||||
}
|
||||
|
||||
private async fittedImage(action: Action, content: T.MsgContent.Image | T.MsgContent.Video): Promise<string> {
|
||||
const {image} = content
|
||||
const fields = JSON.stringify({...content, text: "", image: ""}).length - JSON.stringify({type: "text", text: ""}).length
|
||||
const budget = maxCardLength - largestCard(action, this.actions.mode, this.longestApproverName()) - fields
|
||||
if (encodedLength(image) <= budget) return image
|
||||
try {
|
||||
return await core.chatResizeImageUri(Buffer.from(image.slice(image.indexOf(",") + 1), "base64"), budget)
|
||||
} catch (error) {
|
||||
logError(`action ${action.n} card image`, error)
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshMembers(): Promise<void> {
|
||||
this.members = await this.chat.apiListMembers(this.groupId)
|
||||
}
|
||||
@@ -371,6 +492,10 @@ export class Control implements Pick<ActionHooks, "refusal" | "saveCounter" | "p
|
||||
}
|
||||
}
|
||||
|
||||
export function hasOutcomeCard(action: Action): boolean {
|
||||
return action.tool !== "download" || action.card !== undefined
|
||||
}
|
||||
|
||||
export async function findControlGroup(chat: api.ChatApi, userId: number): Promise<T.GroupInfo | undefined> {
|
||||
const groups = (await chat.apiListGroups(userId)).filter(({customData}) => controlDataOf(customData) !== undefined)
|
||||
return groups.reduce<T.GroupInfo | undefined>((latest, group) => (latest === undefined || group.groupId > latest.groupId ? group : latest), undefined)
|
||||
@@ -456,15 +581,22 @@ function requestLines(action: Action): string[] {
|
||||
return [`${verb} to ${subject}, ${action.subject.incognito ? "incognito" : "as myself"}.`, ...linkLines(action), ...message]
|
||||
}
|
||||
case "send": {
|
||||
const {replyTo, mentions} = action
|
||||
const {file, replyTo, mentions} = action
|
||||
const attaching = file === undefined ? [] : [`attaching ${file.type} ${codeSpan(oneLine(file.path))}, ${sizeText(file.size)}`]
|
||||
const reply = replyTo === undefined ? [] : [`replying to ${safeName(replyTo.from)}: ${codeSpan([...replyTo.text.replace(/\s+/g, " ")].slice(0, 100).join(""))}`]
|
||||
const mentioning = mentions.length === 0 ? [] : [`mentioning ${mentions.map(({name}) => mentionText(name)).join(", ")}`]
|
||||
return [`${done ? "I sent" : "I want to send"} a message to ${subject}${action.subject.incognito ? ", where I am incognito" : ""}:`, ...codeLines(action.input.text), ...reply, ...mentioning]
|
||||
return [`${done ? "I sent" : "I want to send"} a message to ${subject}${action.subject.incognito ? ", where I am incognito" : ""}:`, ...codeLines(action.input.text), ...attaching, ...reply, ...mentioning]
|
||||
}
|
||||
case "leave": {
|
||||
const {present, past} = leaveVerbs(action)
|
||||
return [`${done ? `I ${past}` : `I want to ${present}`} ${chatName(action.subject)} (${action.chat}).`]
|
||||
}
|
||||
case "download": {
|
||||
const {from, file, unknownServers} = action
|
||||
const source = `${from === undefined ? "" : `${safeName(from)} in `}${chatName(action.subject)} (${action.chat})`
|
||||
const servers = unknownServers === undefined ? [] : [serversLine(unknownServers)]
|
||||
return [`${done ? "I downloaded" : "I want to download"} a file from ${source}:`, `${codeSpan(oneLine(file.name))}, ${sizeText(file.size)}`, ...servers]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,6 +608,10 @@ function commandsLine(action: Action): string {
|
||||
return `/'approve ${action.chat} ${action.n}', /'approve ${action.chat} all' or /'reject ${action.chat} ${action.n}'`
|
||||
case "leave":
|
||||
return `/'approve ${action.chat} ${action.n}' or /'reject ${action.chat} ${action.n}'`
|
||||
case "download": {
|
||||
const all = hasUnknownServers(action) ? "" : `/'receive ${action.chat} ${action.n} all', `
|
||||
return `/'receive ${action.chat} ${action.n}', ${all}/'forward ${action.chat} ${action.n}' or /'reject ${action.chat} ${action.n}'`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,8 +657,23 @@ function linkLines({plan, linkTextBytes = Infinity}: ConnectAction): string[] {
|
||||
return lines
|
||||
}
|
||||
|
||||
function chatName(subject: Subject): string {
|
||||
return subjectText({...subject, simplexName: undefined}, safeName)
|
||||
function chatName(subject: Subject, showName: (name: string) => string = safeName): string {
|
||||
return subjectText({...subject, simplexName: undefined}, showName)
|
||||
}
|
||||
|
||||
function serversLine(unknownServers: string[]): string {
|
||||
if (unknownServers.length === 0) return "Servers: known."
|
||||
const hosts = unknownServers.map(server => codeSpan(oneLine(serverHostname(server)))).join(", ")
|
||||
return `Servers: ${hosts}, unknown: downloading shows ${unknownServers.length === 1 ? "it" : "them"} this computer's IP address.`
|
||||
}
|
||||
|
||||
function sizeText(bytes: number): string {
|
||||
const exponent = Math.min(Math.floor(Math.log10(Math.max(bytes, 1)) / 3), 3)
|
||||
return exponent === 0 ? `${bytes} bytes` : `${(bytes / 1000 ** exponent).toFixed(1)} ${["KB", "MB", "GB"][exponent - 1]}`
|
||||
}
|
||||
|
||||
function filesText(count: number): string {
|
||||
return `${count} file${count === 1 ? "" : "s"}`
|
||||
}
|
||||
|
||||
function codeLines(text: string | undefined): string[] {
|
||||
@@ -551,8 +702,8 @@ function customDataOf(chatInfo: T.ChatInfo): object | undefined {
|
||||
return chatInfo.type === "direct" ? chatInfo.contact.customData : (chatInfo as T.ChatInfo.Group).groupInfo.customData
|
||||
}
|
||||
|
||||
function approvalOf(customData: object | undefined): {approvedBy: string; approvedById: number} | undefined {
|
||||
const data = (customData as {simplexMcp?: Partial<ChatApproval>} | undefined)?.simplexMcp
|
||||
function approvalOf(customData: object | undefined, key: string): {approvedBy: string; approvedById: number} | undefined {
|
||||
const data = (customData as {[key: string]: Partial<ChatApproval> | undefined} | undefined)?.[key]
|
||||
return typeof data?.approvedBy === "string" && typeof data.approvedById === "number" ? {approvedBy: data.approvedBy, approvedById: data.approvedById} : undefined
|
||||
}
|
||||
|
||||
@@ -560,9 +711,13 @@ function ownerRequest({keyword, params}: Command): OwnerRequest | undefined {
|
||||
const words = params === "" ? [] : params.split(/\s+/)
|
||||
const chat = words.length === 2 && isChatRef(words[0]) ? words[0] : undefined
|
||||
const value = words.length === 1 || chat !== undefined ? words.at(-1) : undefined
|
||||
if ((keyword === "approve" || keyword === "reject") && value !== undefined && /^\d+$/.test(value)) return {type: keyword, action: Number(value), chat}
|
||||
if (keyword === "approve" && chat !== undefined && value === "all") return {type: "approveChat", chat}
|
||||
if (keyword === "revoke" && chat === undefined && value !== undefined && isChatRef(value)) return {type: "revoke", chat: value}
|
||||
if ((keyword === "approve" || keyword === "reject" || keyword === "receive" || keyword === "forward") && value !== undefined && /^\d+$/.test(value)) return {type: keyword, action: Number(value), chat}
|
||||
if (keyword === "receive" && words.length === 3 && isChatRef(words[0]) && /^\d+$/.test(words[1]) && words[2] === "all") return {type: "receiveAll", action: Number(words[1]), chat: words[0]}
|
||||
if (keyword === "receive" && chat !== undefined && value === "off") return {type: "revoke", chat, standing: "files"}
|
||||
if (keyword === "approve" && chat !== undefined && value === "all") return {type: "approveChat", chat, standing: "messages"}
|
||||
if (keyword === "revoke" && chat === undefined && value !== undefined && isChatRef(value)) return {type: keyword, chat: value, standing: "messages"}
|
||||
if (keyword === "leave" && chat === undefined && value !== undefined && isChatRef(value)) return {type: keyword, chat: value}
|
||||
if (keyword === "delete" && chat !== undefined && value === "files") return {type: "deleteFiles", chat}
|
||||
if ((keyword === "pending" || keyword === "list") && words.length === 0) return {type: keyword}
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {T} from "@simplex-chat/types"
|
||||
import {api, core} from "simplex-chat"
|
||||
import {fullDomainName} from "./messages"
|
||||
|
||||
const maxDetails = 500
|
||||
const causeKey = /(Err|Error|errorType)$/
|
||||
@@ -8,6 +7,13 @@ const blockingReasons: {[reason in T.BlockingReason]: string} = {
|
||||
[T.BlockingReason.Spam]: "Spam",
|
||||
[T.BlockingReason.Content]: "Content violates conditions of use",
|
||||
}
|
||||
const badgeIssues: {[status in T.BadgeStatus]: string} = {
|
||||
[T.BadgeStatus.Active]: "",
|
||||
[T.BadgeStatus.Expired]: " Sender's badge expired.",
|
||||
[T.BadgeStatus.ExpiredOld]: " Sender's badge expired.",
|
||||
[T.BadgeStatus.Failed]: " Sender's badge verification failed.",
|
||||
[T.BadgeStatus.UnknownKey]: " No key to verify sender's badge.",
|
||||
}
|
||||
|
||||
export class ExitError extends Error {
|
||||
constructor(message: string, readonly code: number) {
|
||||
@@ -69,6 +75,8 @@ function chatErrorTypeText(error: T.ChatErrorType): string | undefined {
|
||||
? `No valid link: The SimpleX name ${name} is registered, but it has no valid link.`
|
||||
: `Unconfirmed name: The SimpleX name ${name} is registered, but not added to profile. Please add it to your address or channel profile, if you are the owner.`
|
||||
}
|
||||
case "fileNotApproved":
|
||||
return `Unknown servers! Without Tor or VPN, your IP address will be visible to these XFTP relays: ${[...new Set(error.unknownServers.map(serverHostname))].sort().join(", ")}.`
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
@@ -186,7 +194,56 @@ function storeErrorText(error: T.StoreError): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
function serverHostname(server: string): string {
|
||||
export function fileError({fileStatus, fileProhibited}: T.CIFile): string | undefined {
|
||||
if (fileProhibited === undefined) return fileStatusError(fileStatus)
|
||||
const {maxSize, badgeStatus} = fileProhibited
|
||||
return `Large file! The file is above the limit of ${maxSize} bytes for its sender.${badgeStatus === undefined ? "" : badgeIssues[badgeStatus]}`
|
||||
}
|
||||
|
||||
function fileStatusError(status: T.CIFileStatus): string | undefined {
|
||||
switch (status.type) {
|
||||
case "rcvCancelled":
|
||||
return "The file was cancelled."
|
||||
case "rcvAborted":
|
||||
return "The download was aborted."
|
||||
case "rcvError":
|
||||
return fileErrorText(status.rcvFileError)
|
||||
case "sndError":
|
||||
return fileErrorText(status.sndFileError)
|
||||
case "invalid":
|
||||
return oneLine(`Invalid file: ${status.text}`)
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function fileErrorText(error: T.FileError): string {
|
||||
switch (error.type) {
|
||||
case "auth":
|
||||
return "Wrong key or unknown file chunk address - most likely file is deleted."
|
||||
case "blocked":
|
||||
return `File is blocked by server operator: ${blockingReasons[error.blockInfo.reason]}.`
|
||||
case "noFile":
|
||||
return "File not found - most likely file was deleted or cancelled."
|
||||
case "relay":
|
||||
return oneLine(`File server error: ${srvErrorText(error.srvError)}`)
|
||||
case "other":
|
||||
return oneLine(`Error: ${error.fileError}`)
|
||||
}
|
||||
}
|
||||
|
||||
function srvErrorText(error: T.SrvError): string {
|
||||
switch (error.type) {
|
||||
case "host":
|
||||
return "Server address is incompatible with network settings."
|
||||
case "version":
|
||||
return "Server version is incompatible with network settings."
|
||||
case "other":
|
||||
return error.srvError
|
||||
}
|
||||
}
|
||||
|
||||
export function serverHostname(server: string): string {
|
||||
return /^[a-z]+:\/\/[^@]*@([^,:/]+)/.exec(server)?.[1] ?? server
|
||||
}
|
||||
|
||||
@@ -211,3 +268,8 @@ function isTyped(value: unknown): boolean {
|
||||
export function chatErrorOf(error: unknown): T.ChatError | undefined {
|
||||
return error instanceof core.ChatAPIError ? error.chatError : undefined
|
||||
}
|
||||
|
||||
export function fullDomainName({nameTLD, domain, subDomain}: T.SimplexDomain): string {
|
||||
const tld = nameTLD === T.SimplexTLD.Simplex ? ".simplex" : nameTLD === T.SimplexTLD.Testing ? ".testing" : ""
|
||||
return `${[...subDomain].reverse().concat(domain).join(".")}${tld}`
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import {ChatResponse, T} from "@simplex-chat/types"
|
||||
import {existsSync} from "fs"
|
||||
import {extname, join} from "path"
|
||||
import {T} from "@simplex-chat/types"
|
||||
import {api} from "simplex-chat"
|
||||
import {fileError} from "./log"
|
||||
|
||||
const progressInterval = 60_000
|
||||
const maxTimer = 2_147_483_647
|
||||
@@ -7,6 +10,8 @@ const pageSize = 100
|
||||
const maxCollected = 100
|
||||
const prohibitedNameChars = ".,;/\\#@'\"`~"
|
||||
const maxNameLength = 50
|
||||
const receivingStatuses: T.CIFileStatus["type"][] = ["rcvAccepted", "rcvTransfer", "rcvWarning"]
|
||||
export const missingFile = "The received file is not in the agent's files folder."
|
||||
|
||||
export interface Message {
|
||||
chat: string
|
||||
@@ -16,11 +21,34 @@ export interface Message {
|
||||
from_type?: string
|
||||
time: string
|
||||
text: string
|
||||
file?: MessageFile
|
||||
new: boolean
|
||||
reply_to?: {chat: string; item: number}
|
||||
mentions_me: boolean
|
||||
}
|
||||
|
||||
export type FileType = "image" | "video" | "voice" | "file"
|
||||
|
||||
export type FilesRoot = "files" | "forwarded"
|
||||
|
||||
export interface MessageFile {
|
||||
name: string
|
||||
size: number
|
||||
type: FileType
|
||||
status: "offered" | "received" | "rejected" | "failed"
|
||||
path?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface FileOffer {
|
||||
fileId: number
|
||||
name: string
|
||||
size: number
|
||||
type: FileType
|
||||
preview?: string
|
||||
duration?: number
|
||||
}
|
||||
|
||||
export interface Sender {
|
||||
name: string
|
||||
type?: string
|
||||
@@ -105,11 +133,15 @@ export class ChatItemsWatch {
|
||||
}
|
||||
|
||||
export function chatRef(chatInfo: T.ChatInfo): string | undefined {
|
||||
return chatInfo.type === "group" && chatInfo.groupChatScope !== undefined ? undefined : anyScopeChatRef(chatInfo)
|
||||
}
|
||||
|
||||
export function anyScopeChatRef(chatInfo: T.ChatInfo): string | undefined {
|
||||
switch (chatInfo.type) {
|
||||
case "direct":
|
||||
return `@${chatInfo.contact.contactId}`
|
||||
case "group":
|
||||
return chatInfo.groupChatScope === undefined ? `#${chatInfo.groupInfo.groupId}` : undefined
|
||||
return `#${chatInfo.groupInfo.groupId}`
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
@@ -123,6 +155,10 @@ export function chatNumber(chat: string): number {
|
||||
return Number(chat.slice(1))
|
||||
}
|
||||
|
||||
export function chatType(chat: string): T.ChatType {
|
||||
return chat.startsWith("@") ? T.ChatType.Direct : T.ChatType.Group
|
||||
}
|
||||
|
||||
export function isMessageItem({content}: T.ChatItem): boolean {
|
||||
return content.type === "rcvMsgContent" || content.type === "sndMsgContent"
|
||||
}
|
||||
@@ -135,7 +171,7 @@ export function isLive({meta}: T.ChatItem): boolean {
|
||||
return meta.itemLive === true
|
||||
}
|
||||
|
||||
export function toMessage(chatInfo: T.ChatInfo, item: T.ChatItem, self: Sender): Message {
|
||||
export function toMessage(chatInfo: T.ChatInfo, item: T.ChatItem, self: Sender, rejectedFiles: ReadonlySet<number>, data: string): Message {
|
||||
const chat = chatRef(chatInfo) ?? ""
|
||||
const {meta, content, quotedItem} = item
|
||||
const text = content.type === "rcvMsgContent" || content.type === "sndMsgContent" ? content.msgContent.text : ""
|
||||
@@ -148,12 +184,71 @@ export function toMessage(chatInfo: T.ChatInfo, item: T.ChatItem, self: Sender):
|
||||
...(sender.type === undefined ? {} : {from_type: sender.type}),
|
||||
time: meta.itemTs,
|
||||
text,
|
||||
...(content.type === "rcvMsgContent" && item.file !== undefined ? {file: messageFile(chat, content.msgContent, item.file, rejectedFiles, data)} : {}),
|
||||
new: isNew(item),
|
||||
...(quotedItem?.itemId === undefined ? {} : {reply_to: {chat, item: quotedItem.itemId}}),
|
||||
mentions_me: meta.userMention,
|
||||
}
|
||||
}
|
||||
|
||||
function messageFile(chat: string, msgContent: T.MsgContent, ciFile: T.CIFile, rejectedFiles: ReadonlySet<number>, data: string): MessageFile {
|
||||
const {name, size, type} = fileOffer(msgContent, ciFile)
|
||||
const file = {name, size, type}
|
||||
const {fileId, fileSource, fileStatus} = ciFile
|
||||
const error = receivedFileError(data, chat, ciFile)
|
||||
const {path, forwarded} = filePaths(data, chat, fileId, name)
|
||||
if (rejectedFiles.has(fileId)) return {...file, status: "rejected"}
|
||||
if (error !== undefined) return {...file, status: "failed", error}
|
||||
if (fileStatus.type === "rcvComplete" && existsSync(path) && [path, forwarded].includes(fileSource?.filePath ?? "")) return {...file, status: "received", path}
|
||||
return {...file, status: "offered"}
|
||||
}
|
||||
|
||||
export function receivedFileError(data: string, chat: string, file: T.CIFile): string | undefined {
|
||||
return fileError(file) ?? (file.fileStatus.type === "rcvComplete" && receivedPath(data, chat, file) === undefined ? missingFile : undefined)
|
||||
}
|
||||
|
||||
export function receivedPath(data: string, chat: string, {fileId, fileName}: T.CIFile): string | undefined {
|
||||
const {path, forwarded} = filePaths(data, chat, fileId, fileName)
|
||||
return [path, forwarded].find(file => existsSync(file))
|
||||
}
|
||||
|
||||
export function filePaths(data: string, chat: string, fileId: number, name: string): {path: string; forwarded: string} {
|
||||
const extension = extname(name)
|
||||
const file = `${fileId}${/^\.[A-Za-z0-9]{1,16}$/.test(extension) ? extension : ""}`
|
||||
return {path: join(chatFolder(data, chat), file), forwarded: join(chatFolder(data, chat, "forwarded"), file)}
|
||||
}
|
||||
|
||||
export function chatFolder(data: string, chat: string, root: FilesRoot = "files"): string {
|
||||
return join(data, root, `${chatType(chat) === T.ChatType.Direct ? "contact" : "group"}-${chatNumber(chat)}`)
|
||||
}
|
||||
|
||||
export function fileOffer(msgContent: T.MsgContent, {fileId, fileName, fileSize}: T.CIFile): FileOffer {
|
||||
const file = {fileId, name: fileName, size: fileSize}
|
||||
switch (msgContent.type) {
|
||||
case "image":
|
||||
return {...file, type: "image", preview: msgContent.image}
|
||||
case "video":
|
||||
return {...file, type: "video", preview: msgContent.image, duration: msgContent.duration}
|
||||
case "voice":
|
||||
return {...file, type: "voice", duration: msgContent.duration}
|
||||
default:
|
||||
return {...file, type: "file"}
|
||||
}
|
||||
}
|
||||
|
||||
export function fileContent({type, preview = "", duration = 0}: Pick<FileOffer, "type" | "preview" | "duration">, text: string): T.MsgContent {
|
||||
switch (type) {
|
||||
case "image":
|
||||
return {type, text, image: preview}
|
||||
case "video":
|
||||
return {type, text, image: preview, duration}
|
||||
case "voice":
|
||||
return {type, text, duration}
|
||||
case "file":
|
||||
return {type, text}
|
||||
}
|
||||
}
|
||||
|
||||
function itemSender(chatInfo: T.ChatInfo, chatDir: T.CIDirection, self: Sender): Sender & {member?: number} {
|
||||
switch (chatDir.type) {
|
||||
case "groupRcv": {
|
||||
@@ -169,25 +264,29 @@ function itemSender(chatInfo: T.ChatInfo, chatDir: T.CIDirection, self: Sender):
|
||||
}
|
||||
}
|
||||
|
||||
export async function chatCommand<R>(chat: api.ChatApi, cmd: string, type: string): Promise<R> {
|
||||
const r: ChatResponse = await chat.sendChatCmd(cmd)
|
||||
if ((r.type as string) !== type) throw new api.ChatCommandError(`unexpected response to ${cmd.split(" ")[0]}`, r)
|
||||
return r as unknown as R
|
||||
export async function getChat(chat: api.ChatApi, ref: string, pagination: T.ChatPagination | number): Promise<T.AChat> {
|
||||
return chat.apiGetChat(chatType(ref), chatNumber(ref), pagination)
|
||||
}
|
||||
|
||||
export async function getChat(chat: api.ChatApi, ref: string, pagination: string): Promise<T.AChat> {
|
||||
return (await chatCommand<{chat: T.AChat}>(chat, `/_get chat ${ref} ${pagination}`, "apiChat")).chat
|
||||
export async function receivingFiles(chat: api.ChatApi, ref: string): Promise<number[]> {
|
||||
const fileIds: number[] = []
|
||||
for (let pagination: T.ChatPagination = {type: "last", count: pageSize}; ; ) {
|
||||
const items: T.ChatItem[] = (await getChat(chat, ref, pagination)).chatItems
|
||||
fileIds.push(...items.flatMap(({file}) => (file !== undefined && receivingStatuses.includes(file.fileStatus.type) ? [file.fileId] : [])))
|
||||
if (items.length < pageSize) return fileIds
|
||||
pagination = {type: "before", chatItemId: items[0].meta.itemId, count: pageSize}
|
||||
}
|
||||
}
|
||||
|
||||
export async function markRead(chat: api.ChatApi, ref: string, itemIds: number[]): Promise<void> {
|
||||
if (itemIds.length > 0) await chatCommand(chat, `/_read chat items ${ref} ${itemIds.join(",")}`, "itemsReadForChat")
|
||||
if (itemIds.length > 0) await chat.apiChatItemsRead(chatType(ref), chatNumber(ref), itemIds)
|
||||
}
|
||||
|
||||
export async function unreadItems(chat: api.ChatApi, ref: string, {chatInfo, chatStats}: T.AChat, messages: number): Promise<{chatInfo: T.ChatInfo; items: T.ChatItem[]; unreadRest: number}> {
|
||||
if (chatStats.unreadCount === 0) return {chatInfo, items: [], unreadRest: 0}
|
||||
const items = (await getChat(chat, ref, `around=${chatStats.minUnreadItemId} count=0`)).chatItems
|
||||
const items = (await getChat(chat, ref, {type: "around", chatItemId: chatStats.minUnreadItemId, count: 0})).chatItems
|
||||
for (let last = items.at(-1); last !== undefined && items.filter(isNewMessage).length < messages;) {
|
||||
const page = (await getChat(chat, ref, `after=${last.meta.itemId} count=${pageSize}`)).chatItems
|
||||
const page = (await getChat(chat, ref, {type: "after", chatItemId: last.meta.itemId, count: pageSize})).chatItems
|
||||
items.push(...page)
|
||||
last = page.length === pageSize ? page.at(-1) : undefined
|
||||
}
|
||||
@@ -262,8 +361,3 @@ export function validName(name: string): string {
|
||||
export function viewName(name: string): string {
|
||||
return /\s/u.test(name) || /\p{P}$/u.test(name) ? `'${name}'` : name
|
||||
}
|
||||
|
||||
export function fullDomainName({nameTLD, domain, subDomain}: T.SimplexDomain): string {
|
||||
const tld = nameTLD === T.SimplexTLD.Simplex ? ".simplex" : nameTLD === T.SimplexTLD.Testing ? ".testing" : ""
|
||||
return `${[...subDomain].reverse().concat(domain).join(".")}${tld}`
|
||||
}
|
||||
@@ -1,21 +1,19 @@
|
||||
import {mkdirSync, rmSync} from "fs"
|
||||
import {Server} from "http"
|
||||
import {join} from "path"
|
||||
import {McpServer, McpServerFactory} from "@modelcontextprotocol/server"
|
||||
import {ChatEvent, T} from "@simplex-chat/types"
|
||||
import {api, util} from "simplex-chat"
|
||||
import {Actions, Mode} from "./actions"
|
||||
import {Control, controlDataOf, createControlChat, findControlGroup, isControlEvent, resetControlChat} from "./control"
|
||||
import {Action, Actions, Mode} from "./actions"
|
||||
import {Control, controlDataOf, createControlChat, findControlGroup, hasOutcomeCard, isControlEvent, resetControlChat} from "./control"
|
||||
import {acquireLock, createDataFolder, releaseLock, serverToken, writeHeadersFile, writeServerFile} from "./files"
|
||||
import {startHttp, stopHttp} from "./http"
|
||||
import {ExitError, log, logError, shellPath} from "./log"
|
||||
import {ChatItemsWatch, chatCommand} from "./messages"
|
||||
import {ChatItemsWatch} from "./messages"
|
||||
import {AgentTools, instructions} from "./tools"
|
||||
|
||||
export const version: string = require("../package.json").version
|
||||
|
||||
const deliveryTimeout = 10_000
|
||||
const deliveryPoll = 100
|
||||
|
||||
export type QrCodeSize = "small" | "large"
|
||||
|
||||
export interface OwnerEntry {
|
||||
@@ -35,6 +33,7 @@ export interface ServeOptions {
|
||||
newToken: boolean
|
||||
port: number
|
||||
qrCode: QrCodeSize
|
||||
stopWait: number
|
||||
}
|
||||
|
||||
export interface RunningServer {
|
||||
@@ -42,14 +41,16 @@ export interface RunningServer {
|
||||
chat: api.ChatApi
|
||||
user: T.User
|
||||
actions: Actions
|
||||
stop(): Promise<void>
|
||||
stop(endWait?: AbortSignal): Promise<void>
|
||||
}
|
||||
|
||||
export async function serve(options: ServeOptions): Promise<void> {
|
||||
const server = await startServer(options)
|
||||
const endWait = new AbortController()
|
||||
let stopping: Promise<void> | undefined
|
||||
const stop = (): void => {
|
||||
stopping ??= server.stop().then(
|
||||
if (stopping !== undefined) return endWait.abort()
|
||||
stopping = server.stop(endWait.signal).then(
|
||||
() => process.exit(0),
|
||||
error => {
|
||||
logError("stop", error)
|
||||
@@ -87,7 +88,10 @@ export async function startServer(options: ServeOptions): Promise<RunningServer>
|
||||
async function startAgent(chat: api.ChatApi, options: ServeOptions, token: string): Promise<RunningServer> {
|
||||
const {name, data, port, approve, expireHours} = options
|
||||
const created = (await chat.apiGetActiveUser()) ?? (await chat.apiCreateActiveUser({displayName: options.displayName ?? name, fullName: "", peerType: T.ChatPeerType.Agent}))
|
||||
await chatCommand(chat, "/network socks=off smp-proxy=always smp-proxy-fallback=protected", "networkConfig")
|
||||
const networkConfig = await chat.apiGetNetworkConfig()
|
||||
await chat.apiSetNetworkConfig({...networkConfig, smpProxyMode: T.SMPProxyMode.Always, smpProxyFallback: T.SMPProxyFallback.AllowProtected})
|
||||
await setTempFolder(chat, join(data, "tmp"))
|
||||
rmSync(join(data, "files", "sent"), {recursive: true, force: true})
|
||||
const events = bufferEvents(chat)
|
||||
await chat.startChat()
|
||||
const user = await updatedUser(chat, created, options.displayName)
|
||||
@@ -101,7 +105,7 @@ async function startAgent(chat: api.ChatApi, options: ServeOptions, token: strin
|
||||
perform: (action, signal) => tools.perform(action, signal),
|
||||
})
|
||||
const watch = new ChatItemsWatch()
|
||||
const tools = new AgentTools({chat, user, actions, watch, controlChat: () => control.chatRef, standingApprover: chatInfo => control.standingApprover(chatInfo)}, approve)
|
||||
const tools = new AgentTools({chat, user, actions, watch, controlChat: () => control.chatRef, standingApprover: (chatInfo, standing) => control.standingApprover(chatInfo, standing), refusedFile: (path, chatInfo, chat) => control.refusedFile(path, chatInfo, chat), data}, approve)
|
||||
const control: Control = new Control(chat, group, {displayName, owners: options.owners, registerHint: registerHint(options), qrCode: options.qrCode}, actions, tools)
|
||||
await control.load()
|
||||
const factory = (): McpServer => {
|
||||
@@ -129,9 +133,11 @@ async function startAgent(chat: api.ChatApi, options: ServeOptions, token: strin
|
||||
for (const ci of event.chatItems) {
|
||||
if (ci.chatInfo.type === "group" && ci.chatInfo.groupInfo.groupId === control.groupId && ci.chatInfo.groupChatScope === undefined) control.onMessage(ci)
|
||||
}
|
||||
tools.onNewItems(event.chatItems)
|
||||
watch.deliver(event.chatItems)
|
||||
return
|
||||
case "chatItemUpdated":
|
||||
tools.onFile(event.chatItem)
|
||||
return watch.update(event.chatItem)
|
||||
case "chatItemsDeleted":
|
||||
return watch.remove(event.chatItemDeletions.map(({deletedChatItem}) => deletedChatItem))
|
||||
@@ -139,6 +145,19 @@ async function startAgent(chat: api.ChatApi, options: ServeOptions, token: strin
|
||||
return tools.onContactConnected(event)
|
||||
case "userJoinedGroup":
|
||||
return tools.onUserJoinedGroup(event)
|
||||
case "rcvFileComplete":
|
||||
return tools.onFileComplete(event.chatItem)
|
||||
case "rcvFileSndCancelled":
|
||||
return tools.onFileCancelled(event)
|
||||
case "rcvFileError":
|
||||
return tools.onFileError(event)
|
||||
case "rcvFileDescrReady":
|
||||
return tools.onFileDescription()
|
||||
case "sndFileCompleteXFTP":
|
||||
return tools.onSentFile(event.fileTransferMeta)
|
||||
case "sndFileError":
|
||||
tools.onSentFile(event.fileTransferMeta)
|
||||
return control.fileNotSent(event)
|
||||
}
|
||||
if (isControlEvent(event, control.groupId)) {
|
||||
controlEvents = controlEvents.then(() => control.onEvent(event)).catch(error => logError(`${event.type} in the agent control chat`, error))
|
||||
@@ -149,13 +168,13 @@ async function startAgent(chat: api.ChatApi, options: ServeOptions, token: strin
|
||||
chat,
|
||||
user,
|
||||
actions,
|
||||
async stop() {
|
||||
async stop(endWait = new AbortController().signal) {
|
||||
stopped = true
|
||||
const cancelling = actions.stop()
|
||||
await stopHttp(server)
|
||||
const cancelled = await cancelling
|
||||
if (cancelled > 0) log(`Cancelled ${cancelled} action${cancelled === 1 ? "" : "s"}.`)
|
||||
await deliveries(chat, control.groupId)
|
||||
if (cancelled.length > 0) log(`Cancelled ${cancelled.length} action${cancelled.length === 1 ? "" : "s"}.`)
|
||||
await waitForCancelledCards(actions.lost ? [] : cancelled, options.stopWait, endWait)
|
||||
await chat.close()
|
||||
releaseLock(data)
|
||||
log("Stopped.")
|
||||
@@ -167,24 +186,26 @@ export function registerHint({name, data, dataGiven}: ServeOptions): string {
|
||||
return `Add the agent to Claude Code:\n npx -y @simplex-chat/mcp register ${name}${dataGiven ? ` --data ${shellPath(data)}` : ""}`
|
||||
}
|
||||
|
||||
export async function deliveries(chat: api.ChatApi, groupId: number): Promise<void> {
|
||||
const connIds = (await sqlRows(chat, `/sql chat SELECT hex(agent_conn_id) FROM connections WHERE group_member_id IN (SELECT group_member_id FROM group_members WHERE group_id = ${groupId})`)).slice(1)
|
||||
if (connIds.length === 0) return
|
||||
const pending = `/sql agent SELECT count(*) FROM snd_message_deliveries WHERE failed = 0 AND hex(conn_id) IN (${connIds.map(id => `'${id}'`).join(",")})`
|
||||
const deadline = Date.now() + deliveryTimeout
|
||||
while (Date.now() < deadline && Number((await sqlRows(chat, pending)).at(-1) ?? 0) > 0) {
|
||||
await new Promise(resolve => setTimeout(resolve, deliveryPoll))
|
||||
}
|
||||
export async function waitForCancelledCards(stopped: Action[], seconds: number, endWait: AbortSignal): Promise<void> {
|
||||
const cards = stopped.filter(hasOutcomeCard).length
|
||||
if (cards === 0 || seconds === 0) return
|
||||
log(`Stopping: sending ${cards} cancelled card${cards === 1 ? "" : "s"}, up to ${seconds} s. Ctrl-C to stop now.`)
|
||||
await new Promise<void>(resolve => {
|
||||
const end = (): void => {
|
||||
clearTimeout(timer)
|
||||
endWait.removeEventListener("abort", end)
|
||||
resolve()
|
||||
}
|
||||
const timer = setTimeout(end, seconds * 1000)
|
||||
if (endWait.aborted) end()
|
||||
else endWait.addEventListener("abort", end, {once: true})
|
||||
})
|
||||
}
|
||||
|
||||
async function sqlRows(chat: api.ChatApi, query: string): Promise<string[]> {
|
||||
try {
|
||||
const {rows} = (await chat.sendChatCmd(query)) as unknown as {rows?: string[]}
|
||||
return rows ?? []
|
||||
} catch (error) {
|
||||
logError("delivery wait", error)
|
||||
return []
|
||||
}
|
||||
async function setTempFolder(chat: api.ChatApi, folder: string): Promise<void> {
|
||||
mkdirSync(folder, {recursive: true, mode: 0o700})
|
||||
const r = await chat.sendChatCmd(`/_temp_folder ${folder}`)
|
||||
if (r.type !== "cmdOk") throw new api.ChatCommandError("error setting the temp folder", r)
|
||||
}
|
||||
|
||||
async function updatedUser(chat: api.ChatApi, user: T.User, displayName: string | undefined): Promise<T.User> {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user