mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 15:38:23 +00:00
mcp: the agent's tools refuse the plugin's own groups (#8304)
* mcp: test the tools on the Main group and the session groups * mcp: the agent's tools refuse the plugin's own groups
This commit is contained in:
1 parent
dbd3fd7ca5
commit
8f5dfa3d4e
8 files changed
+56
-18
No files matched your search
@@ -642,6 +642,7 @@ VERSION is the plugin's version, as in `npx -y @simplex-chat/mcp@0.3.0 link`. Th
|
||||
- The group is created in the Flat layout, which SimpleX apps from v7.1.0 show. Each member can choose another layout for it in Group info › `Chat theme` › `Chat layout`, for their own app. The Main group is shown in each member's own layout.
|
||||
- The group has the commands of the agent control chat of `serve` (see [What the owner sees](#what-the-owner-sees)), without a session prefix, such as `/approve 7`, `/receive @3 9` and `/leave #2`. It also has `/give CHAT N`, `/observer #G ID`, and `/approve N all` and `/revoke TOOL` for tools, see [Tool use](#tool-use).
|
||||
- A chat belongs to the session that connected it, even when the other side accepts after `connect` returned. The tools of other sessions don't show it. Their `connect` to its address returns `The chat of LINK belongs to another session; an admin or owner of that session's group can give it to this session with /give.` For example, `/give @3 2` in the group of the session that owns chat @3 gives it to session 2.
|
||||
- The Main group and the session groups belong to no session. The tools of every session don't show them: `send`, `receive`, `download` and `leave` return `No chat CHAT. list shows the agent's chats.`, and `connect` to one of them returns `The chat of LINK is the Main group or a session's group, not one of the agent's chats.`
|
||||
- `/list` and `/revoke` also work in the group of a closed session. A `/revoke` sent while the service is stopped applies when the service starts again.
|
||||
- `claude --resume` and `claude --continue` reopen a session with its group and chats. `/clear` keeps the session's group, because the service links the new session IDs of a Claude Code process to that process's session. A fork made with `claude --resume ID --fork-session` continues in the group of the resumed session. After `/resume` of another session inside a running one, prompts and answers go to the running session's group. A later `claude --resume` of that other session reopens its own group and chats.
|
||||
- A session closes 10 minutes after its Claude Code session ends, once the expiry times of its actions have passed. The service stops 10 minutes after the last session closes. The next session start or tool call starts it again.
|
||||
|
||||
@@ -683,8 +683,8 @@ stderr: `CONTEXT: ERROR` from [`logError`](../src/log.ts), with CONTEXT one of `
|
||||
| The four action tools are registered with `_meta: {"anthropic/requiresUserInteraction": true}` when the option `approve` is `host` at the start of the session process | [`startSession`](../src/session.ts), [`registerTools`](../src/tools.ts) |
|
||||
| `pre_tool_use`, with input `{tool}`, answers the PreToolUse hook of type `mcp_tool` of [4.8](#48-plugin-options-files-and-hook-output). For a tool in the approved tools of the session server's current attachment ([4.6](#46-socket-protocol)), its text is `{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","permissionDecisionReason":"Approved for this session by NAME in the session's SimpleX group."}}`; otherwise it is empty. It sends no request to the service and returns no error, also in a run that is not interactive and with an invalid option. Its description, which Claude sees: `Answers the plugin's PreToolUse hook before each tool use: allow for a tool that an admin or owner of the SimpleX group of this session approved for the rest of the session, and nothing otherwise. You never need to call it.` | [`hookTool`, `startSession`, `ServiceLink.approvedBy`, `hookOutput`](../src/session.ts) |
|
||||
| Instructions: those of [1.1](#11-common-rules), with the display name `Claude` and the host `SimpleX service`, followed by the channel instructions of [4.5](#45-channel) | [`channelInstructions`, `startSession`](../src/session.ts), [`instructions`](../src/tools.ts) |
|
||||
| `send`, `receive`, `download`, `leave` and `list` see only the session's own chats. For another session's chat, `send`, `receive`, `download` and `leave` return `No chat CHAT. list shows the agent's chats.` | [`AgentTools.owns`, `knownChat`](../src/tools.ts) |
|
||||
| At `connect`, a known chat without an owner becomes the session's chat. `connect` to a chat of another session returns the tool error `The chat of TARGET belongs to another session; an admin or owner of that session's group can give it to this session with /give.` | [`AgentTools.ownChat`](../src/tools.ts) |
|
||||
| `send`, `receive`, `download`, `leave` and `list` see only the session's own chats, never the Main group or a session group, even with an owner key. For any other chat, `send`, `receive`, `download` and `leave` return `No chat CHAT. list shows the agent's chats.` | [`AgentTools.owns`, `knownChat`, `isHubGroup`](../src/tools.ts) |
|
||||
| At `connect`, a known chat without an owner becomes the session's chat. `connect` to a chat of another session returns the tool error `The chat of TARGET belongs to another session; an admin or owner of that session's group can give it to this session with /give.` `connect` to the Main group or a session group returns the tool error `The chat of TARGET is the Main group or a session's group, not one of the agent's chats.`, and sets no owner | [`AgentTools.ownChat`, `claim`, `hubGroupChat`](../src/tools.ts) |
|
||||
| Actions are numbered from 1 in each session group. The session number is part of the action key, see [1.1](#11-common-rules) | [`Session`](../src/hub.ts) constructor, [`actionKey`](../src/tools.ts) |
|
||||
| Downloads are saved under `ROOT/_sessions/ID/files/` | the `agent` of the [`Session`](../src/hub.ts) constructor, [`chatFolder`](../src/messages.ts) |
|
||||
| A run is not interactive when `CLAUDE_CODE_SESSION_ATTENDED` is `0`, which Claude Code sets for the hooks of a run nobody attends, or when `CLAUDE_CODE_ENTRYPOINT` is `sdk-cli`, which Claude Code sets for `claude -p`, or `sdk-ts` or `sdk-py`, for the Agent SDK. Such a run has no session. Its session process does not connect to the service, and every tool returns `This Claude Code run is not interactive, so it has no SimpleX group; the SimpleX tools work in interactive sessions.`, even when an option is invalid. Its hooks return `{}`, and the turn hooks send no request | [`unattendedEntrypoints`, `interactiveEntrypoint`, `interactive`](../src/config.ts), [`unattendedRun`, `startSession`](../src/session.ts), [`sessionStart`, `turn`](../src/hook.ts) |
|
||||
|
||||
@@ -157,7 +157,7 @@ Tool definitions, call handlers, connect plans, perform steps, files.
|
||||
| <a id="tools-agenttools-register"></a>`AgentTools.register` | `registerTools` with `AgentTools.call` |
|
||||
| <a id="tools-agenttools-call"></a>`AgentTools.call` | handler result to `CallToolResult`; errors to `isError` |
|
||||
| <a id="tools-agenttools-perform"></a>`AgentTools.perform` | perform step of an approved action, which is the mode setter for a `mode` action |
|
||||
| <a id="tools-agenttools-givechat"></a>`giveChat`, `owns`, `claim` | the plugin's chat owners. A chat is the session's when no session ID is set or the chat's owner is that ID. `claim` sets the owner of a chat without one. It is called at a connection, and when `connect` names a known chat (`ownChat`). The hub calls it when a pending connection completes. |
|
||||
| <a id="tools-agenttools-givechat"></a>`giveChat`, `owns`, `claim` | the plugin's chat owners. A chat is the session's when it is not a group of the hub (`isHubGroup`), and no session ID is set or the chat's owner is that ID. `claim` sets the owner of a chat without one, and refuses a group of the hub with the tool error of [API 4.1](api.md#41-tools-in-the-plugin). It is called at a connection, and when `connect` names a known chat (`ownChat`), where a group of the hub is refused before the call. The hub calls it when a pending connection completes. |
|
||||
| <a id="tools-agenttools-onevent"></a>`onEvent` | events to the file handlers, connect completions and the item watch, for `serve` and the plugin's sessions |
|
||||
| <a id="tools-agenttools-reply"></a>`reply`, `sendFile` | `reply` sends a file to the group of the plugin's session at once, without an action, under the file rules of `send`. Its message with the caption and the preview is checked by `fitsMessage`. The core's refusal `feature not allowed NAME` is answered with the text with the preference's name. `sendFile` posts the file. |
|
||||
| <a id="tools-refusedfeature"></a>`refusedFeature`, `featureOff` | the preference NAME of a command error `feature not allowed NAME`, and the text `NAME are off in the group of this session; its owners can turn them on in the group's preferences.` The text is used for `reply`, the cards, `/forward` and the answers of a session group. |
|
||||
@@ -174,7 +174,7 @@ Tool definitions, call handlers, connect plans, perform steps, files.
|
||||
| <a id="tools-agenttools-selfsender"></a>`selfSender`, `toMessages` | the agent's name and peer type in a chat, its incognito name in an incognito chat, or its profile name when the incognito name can't be read; the items of one chat as messages with that name, for the results of `connect`, `send` and `receive` |
|
||||
| <a id="tools-classifyplan"></a>`classifyPlan` | `apiConnectPlan` response to a join plan or a known chat |
|
||||
| <a id="tools-chatsubject"></a>`chatSubject`, `isConnected`, `isActive`, `memberCurrent`, `memberCurrentOrPending` | chat and member predicates shared with `control.ts` and `hub.ts` |
|
||||
| <a id="tools-customdataof"></a>`customDataOf`, `setChatData`, `ownerOf` | a chat's custom data; the plugin's owner key `simplexMcpOwner` |
|
||||
| <a id="tools-customdataof"></a>`customDataOf`, `setChatData`, `ownerOf`, `isHubGroup` | a chat's custom data; the plugin's owner key `simplexMcpOwner`; `mainKey` and `sessionKey`, `simplexMcpMain` of the Main group and `simplexMcpSession` of a session group, which mark the groups of the hub |
|
||||
| <a id="tools-fitsmessage"></a>`tooLongText`, `fitsMessage`, `quoteContent` | the refusal text of `send` and `reply` for a message that is too long. `fitsMessage` checks that the message as the core sends it, with its quote, is within `maxMessageLength`, 15602 bytes. The check is used for `send`, `reply`, the post of `/forward`, and the parts and quotes of the plugin's posts. |
|
||||
| <a id="tools-realfile"></a>`realFile` | real path, size, inode and change time of a file |
|
||||
| <a id="tools-attachmentmedia"></a>`attachmentMedia`, `videoFrame`, `videoDuration` | previews and durations |
|
||||
@@ -891,7 +891,7 @@ Data flow of a prompt from the session group:
|
||||
|
||||
| Symbol | Contents |
|
||||
|---|---|
|
||||
| <a id="hub-constants"></a>constants, from `profileName` to `unsupportedReaction`, and `textUpdateMs`, `textEndMs`, `maxRecentTexts`, `stoppedLine` | profile name `Claude`, session data key, first action number, 10 s stop wait, 60 s echo of a raw prompt, 20 pushed prompts, 100 kept texts of passed prompts and 100 kept items of live messages, 10 minutes for a prompt's file, 1 day for a pending connection, 30 s of held prompts after the hub opens, the channel tags of this plugin, the one reply to the `/` commands of a member who is not an admin or owner, the eight emoji of the apps' reactions, the reply to another reaction, 3 s between the updates of a live text, 10 s from a text's final batch to its finalization, 20 ended texts kept for the claim of an answer, and `⏹️ Stopped`, the text of an opening message that no post filled; `relayWait` and `relayAge`, the 3 s that a PermissionRequest hook's prompt of the main conversation waits for the channel's request of its tool, and the 5 s before the hook's start from which that request counts |
|
||||
| <a id="hub-constants"></a>constants, from `profileName` to `unsupportedReaction`, and `textUpdateMs`, `textEndMs`, `maxRecentTexts`, `stoppedLine` | profile name `Claude`, first action number, 10 s stop wait, 60 s echo of a raw prompt, 20 pushed prompts, 100 kept texts of passed prompts and 100 kept items of live messages, 10 minutes for a prompt's file, 1 day for a pending connection, 30 s of held prompts after the hub opens, the channel tags of this plugin, the one reply to the `/` commands of a member who is not an admin or owner, the eight emoji of the apps' reactions, the reply to another reaction, 3 s between the updates of a live text, 10 s from a text's final batch to its finalization, 20 ended texts kept for the claim of an answer, and `⏹️ Stopped`, the text of an opening message that no post filled; `relayWait` and `relayAge`, the 3 s that a PermissionRequest hook's prompt of the main conversation waits for the channel's request of its tool, and the 5 s before the hook's start from which that request counts |
|
||||
| <a id="hub-hubtexts"></a>`hubTexts` | refusal texts of a lost session group, of a stop and of the limit of pending actions, which names the approvers |
|
||||
| <a id="hub-sessiongroupdata"></a>`SessionGroupData` | session number; pending connections of `connect` with their time; the approved mode |
|
||||
| <a id="hub-session"></a>`Session` | one Claude Code session, built from its `session.json` and its group's data. `Actions` get the hub's texts and the mode of the group's data, or `requests` without one. `AgentTools` get the session's ID and folder and the group for `reply`. `Control` of the session group gets the session's approver checks. The stored model and effort are kept as well. |
|
||||
@@ -939,7 +939,7 @@ Data flow of a prompt from the session group:
|
||||
|
||||
| Symbol | Contents |
|
||||
|---|---|
|
||||
| <a id="main-group-maincommands"></a>`mainCommands`, texts from `mainKey` to `shortDescr` | command menu; greeting, reply to an unknown command, log line; the welcome message, the text of the join post and the short description |
|
||||
| <a id="main-group-maincommands"></a>`mainCommands`, texts from `greeting` to `shortDescr` | command menu; greeting, reply to an unknown command, log line; the welcome message, the text of the join post and the short description |
|
||||
| <a id="main-group-sessiongroups"></a>`SessionGroups` | what the Main group asks of the hub |
|
||||
| <a id="main-group-maingroup-owners"></a>`MainGroup.owners` | human members with role `owner` while the group is not lost |
|
||||
| <a id="main-group-maingroup-load"></a>`MainGroup.load`, `start` | lost check, name and menu from the group's current profile, and members. The short description and welcome message are kept. Without owners, `start` takes the existing link, or creates a new one. |
|
||||
@@ -1083,9 +1083,9 @@ Chat database custom data is in the core `_hub` unless noted:
|
||||
|
||||
| Item | Entity | Value | Written by | Read by |
|
||||
|---|---|---|---|---|
|
||||
| Main group marker | Main group | `{simplexMcpMain: true}` | [`createMainGroup`](../src/main-group.ts) | [`findMainGroup`](../src/main-group.ts) |
|
||||
| Main group marker | Main group | `{simplexMcpMain: true}` | [`createMainGroup`](../src/main-group.ts) | [`findMainGroup`](../src/main-group.ts), [`isHubGroup`](../src/tools.ts) |
|
||||
| Board of sessions | Main group | `{simplexMcpMain: true, simplexMcpBoard: {summary?: {item, at}, sessions: [{session, item, at}]}}`, merged with the other keys; `simplexMcpList` of an earlier version removed | [`MainGroup.saveBoard`](../src/main-group.ts) | [`MainGroup` constructor, `boardOf`, `listOf`](../src/main-group.ts) |
|
||||
| Session group | group of session N | `{simplexMcpSession: {session: N, pending?: [{connId, at}], mode?}}`, where `mode` is the approved mode | [`createSessionGroup`](../src/hub.ts), [`setMode`](../src/hub.ts), [`savePending`](../src/hub.ts), [`claimPending`](../src/hub.ts) | [`storedGroup`](../src/hub.ts), [`Session` constructor](../src/hub.ts), [`claimPending`](../src/hub.ts) |
|
||||
| Session group | group of session N | `{simplexMcpSession: {session: N, pending?: [{connId, at}], mode?}}`, where `mode` is the approved mode | [`createSessionGroup`](../src/hub.ts), [`setMode`](../src/hub.ts), [`savePending`](../src/hub.ts), [`claimPending`](../src/hub.ts) | [`storedGroup`](../src/hub.ts), [`Session` constructor](../src/hub.ts), [`claimPending`](../src/hub.ts), [`isHubGroup`](../src/tools.ts) |
|
||||
| Action counter | group of session N | `{simplexMcp: {control: true, nextAction}}`, merged with the other keys | [`saveCounter`, `saveData`](../src/control.ts) | [`Session` constructor](../src/hub.ts) |
|
||||
| Chat owner | contact or group of a peer | `{...other keys, simplexMcpOwner: {session: ID}}` | [`claim`](../src/tools.ts), [`giveChat`](../src/tools.ts) | [`owns`](../src/tools.ts) |
|
||||
| Standing approvals | contact or group of a peer | as in [3.2](#32-chat-database-custom-data) | `Control` of the owning session's group | the same |
|
||||
@@ -1191,7 +1191,7 @@ On `SIGINT`, `SIGTERM`, `POST /stop` or the stop timer ([`Service.shutdown`](../
|
||||
| The first human who joins the Main group while it has no owner becomes an owner, and the link is deleted | [`MainGroup.handleEvent`, `ownerJoined`](../src/main-group.ts) |
|
||||
| A session runs in mode `host` after an approver approves its `mode` card. The card is posted once an approver is in the group. After a rejection, the card is posted again only after `requests`. `requests` applies at once, and the hub ends a pending `mode` card. The mode is kept in the session group's custom data. | [`Session.requestMode`, `askMode`, `declineHost`, `Hub.onEvent`](../src/hub.ts), [`AgentTools.perform`](../src/tools.ts) |
|
||||
| At a reset of the owners from the computer that runs Claude Code, the service replaces the Main group at once, even while owners exist. No owner's approval is needed for `reset-owners` and `POST /reset-owners`. | [`Hub.resetOwners`](../src/hub.ts), [`resetOwners`](../src/owner.ts), [`MainGroup.replace`](../src/main-group.ts) |
|
||||
| A chat without an owner is given to the session that connects it. The owner is set at one of four points: the perform, the connection event of its action, the completion of a pending connection that the session recorded, or a `connect` to the chat as a known chat. The tools of other sessions don't show the chat. With `/give CHAT N`, an approver moves the chat to session N. | [`AgentTools.owns`, `claim`, `ownChat`, `performConnect`, `markConnected`](../src/tools.ts), [`Session.claimPending`, `Hub.onEvent`](../src/hub.ts), [`Control.give`](../src/control.ts) |
|
||||
| A chat without an owner, other than the Main group and the session groups, is given to the session that connects it. The owner is set at one of four points: the perform, the connection event of its action, the completion of a pending connection that the session recorded, or a `connect` to the chat as a known chat. The tools of other sessions don't show the chat. With `/give CHAT N`, an approver moves the chat to session N. | [`AgentTools.owns`, `claim`, `ownChat`, `performConnect`, `markConnected`](../src/tools.ts), [`Session.claimPending`, `Hub.onEvent`](../src/hub.ts), [`Control.give`](../src/control.ts) |
|
||||
|
||||
Tool-use state machine, one action of tool `permission` per request:
|
||||
|
||||
@@ -1439,7 +1439,7 @@ Sources: [`Session.onMessage`, `turn`, `endPermissions`, `prompt`, `deliver`, `r
|
||||
| The service gets only the environment variables of `serviceVariables` | [`serviceVariables`, `spawnService`](../src/client.ts) |
|
||||
| `send` and `reply` refuse the files of ROOT except `files/` of the session's own folder | [`AgentTools.isRefused`](../src/tools.ts), the `agent` of the [`Session`](../src/hub.ts) constructor |
|
||||
| `User`'s messages and reactions are neither prompts nor commands. `Session.prompt` and `Control.onMessage` drop the messages, and `Session.onReaction` the reactions, of the member of the hub's contact marked `simplexMcpUser`, which is read at the hub's start. `User` joins only the groups to which it is invited by its `Claude` contact. | [`Session.prompt`, `onReaction`, `isUser`, `Hub.open`](../src/hub.ts), [`Control.onMessage`](../src/control.ts), [`User.onEvent`, `userContact`](../src/user.ts) |
|
||||
| The hub's own groups and the `User` contact have no owner key, so the tools of every session leave them out | [`AgentTools.owns`, `agentChats`](../src/tools.ts) |
|
||||
| The hub's own groups, marked `simplexMcpMain` and `simplexMcpSession`, are left out of the tools of every session, even with an owner key, and `connect` sets no owner of them. The `User` contact has no owner key, so it is left out too | [`AgentTools.owns`, `agentChats`, `ownChat`, `claim`, `isHubGroup`](../src/tools.ts) |
|
||||
| The approved mode is kept in the chat database, not in a file of ROOT | [`Session`](../src/hub.ts) constructor, [`Session.setMode`](../src/hub.ts), [`SessionFile`](../src/files.ts) |
|
||||
| These rules hold against Claude's tools, but not against a shell running as the same user. Such a shell can read ROOT, with the token and the chat databases, and send requests to the service. | |
|
||||
|
||||
|
||||
@@ -227,7 +227,7 @@ Notes:
|
||||
- The connection is matched by `contactConnected` or `userJoinedGroup`: by contact or group ID, or by the pending connection ID ([`AgentTools.onContactConnected`, `onUserJoinedGroup`, `completeConnect`](../src/tools.ts)). In the plugin, the pending connection ID is also recorded in the session group's custom data. When the connection completes after the call returned, within a day of the record, its chat becomes the session's ([`AgentTools.performConnect`](../src/tools.ts), [`Session.claimPending`, `Hub.onEvent`](../src/hub.ts)).
|
||||
- In the perform step the server waits for the other side until `startedAt + wait`, at most until `created + 23 h 50 min`, and then reports `connected: false` ([`editWindow`, `AgentTools.performConnect`](../src/tools.ts)).
|
||||
- Without `message`, the idle time is counted from the connection; with `message`, from the first reply ([`AgentTools.markConnected`](../src/tools.ts), [`awaitResponses`](../src/messages.ts)).
|
||||
- For a target the agent is connected to, the result is `status: known` with its chat fields, and no action is created ([`AgentTools.connect`](../src/tools.ts)). In the plugin, the chat becomes the session's when it has no owner ([`AgentTools.ownChat`](../src/tools.ts)).
|
||||
- For a target the agent is connected to, the result is `status: known` with its chat fields, and no action is created ([`AgentTools.connect`](../src/tools.ts)). In the plugin, the chat becomes the session's when it has no owner, and the Main group and the session groups are refused ([`AgentTools.ownChat`](../src/tools.ts)).
|
||||
- Exact progress texts: `Action N waits for an approver until TIME.`, then `Action N waits for the connection until TIME.`, then `K messages in CHAT; waiting until TIME.` ([`progressText`](../src/actions.ts), [`AgentTools.connectedChat`](../src/tools.ts)).
|
||||
|
||||
Source: [`AgentTools.connect`, `action`, `ownChat`, `connectResult`, `actionResult`, `connectedChat`, `plan`, `performConnect`, `join`, `connectPrepared`, `completeConnect`, `markConnected`](../src/tools.ts), [`Actions.create`, `decided`, `approve`](../src/actions.ts), [`Control.postCard`, `outcome`](../src/control.ts).
|
||||
|
||||
@@ -16,14 +16,12 @@ import {Changes, ChatItemsWatch, ReplyTo, ToolCall, duration, getChat, isLive, n
|
||||
import {AgentEvent, AskRequest, AttachLine, Decision, Failure, LimitWindow, Limits, OwnerState, PermissionRequest, Prompt, ResetReply, Step, TaskEnd, TextBatch, TurnRequest, Waiting, WorkflowRun} from "./protocol"
|
||||
import {waitForCancelledCards} from "./serve"
|
||||
import {Machine, limitParts, machineParts, machineState} from "./status-line"
|
||||
import {AgentTools, ToolName, featureOff, fitsMessage, maxMessageLength, ownerOf, refusedFeature} from "./tools"
|
||||
import {AgentTools, ToolName, featureOff, fitsMessage, maxMessageLength, ownerOf, refusedFeature, sessionKey} from "./tools"
|
||||
import {User, userContact} from "./user"
|
||||
|
||||
// spec: spec/architecture.md#hub-constants
|
||||
const profileName = "Claude"
|
||||
// spec: spec/architecture.md#hub-constants
|
||||
const sessionKey = "simplexMcpSession"
|
||||
// spec: spec/architecture.md#hub-constants
|
||||
const firstAction = 1
|
||||
// spec: spec/architecture.md#hub-constants
|
||||
const cardsWait = 10
|
||||
|
||||
@@ -3,15 +3,13 @@ import {api} from "simplex-chat"
|
||||
import {Command, createGroup, deleteGroup, isLost, joinedText, losesControl, parseCommand, safeName, updateGroupProfile} from "./control"
|
||||
import {chatErrorOf, log, logError, oneLine} from "./log"
|
||||
import {resetCommand} from "./owner"
|
||||
import {isActive} from "./tools"
|
||||
import {isActive, mainKey} from "./tools"
|
||||
|
||||
// spec: spec/architecture.md#main-group-maincommands
|
||||
const mainCommands: T.ChatBotCommand[] = [
|
||||
{type: "command", keyword: "sessions", label: "Claude Code sessions"},
|
||||
{type: "command", keyword: "join", label: "Join the group of a session", params: "<session number>"},
|
||||
]
|
||||
// spec: spec/architecture.md#main-group-maincommands
|
||||
const mainKey = "simplexMcpMain"
|
||||
// spec: spec/api.md#main-group-profile
|
||||
const listKey = "simplexMcpList"
|
||||
// spec: spec/api.md#main-group-profile
|
||||
|
||||
@@ -181,6 +181,8 @@ const pngSignature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
|
||||
const refusedName = /^id_|\.(pem|key|p12|pfx)$/i
|
||||
export const refusedFileReason = "private keys and the server's own files are not sent"
|
||||
const ownerKey = "simplexMcpOwner"
|
||||
export const mainKey = "simplexMcpMain"
|
||||
export const sessionKey = "simplexMcpSession"
|
||||
// spec: spec/api.md#tool-download
|
||||
const deletedItem = "The message or its chat was deleted."
|
||||
// spec: spec/api.md#tool-download
|
||||
@@ -638,13 +640,14 @@ export class AgentTools {
|
||||
|
||||
// spec: spec/architecture.md#tools-agenttools-givechat
|
||||
private owns(chatInfo: T.ChatInfo): boolean {
|
||||
return this.agent.owner === undefined || ownerOf(chatInfo) === this.agent.owner
|
||||
return !isHubGroup(chatInfo) && (this.agent.owner === undefined || ownerOf(chatInfo) === this.agent.owner)
|
||||
}
|
||||
|
||||
// spec: spec/architecture.md#tools-agenttools-givechat
|
||||
async claim(chat: string): Promise<void> {
|
||||
if (this.agent.owner === undefined) return
|
||||
const {chatInfo} = await getChat(this.agent.chat, chat, 0)
|
||||
if (isHubGroup(chatInfo)) throw hubGroupChat(chat)
|
||||
if (ownerOf(chatInfo) === undefined) await setChatData(this.agent.chat, chat, {...customDataOf(chatInfo), [ownerKey]: {session: this.agent.owner}})
|
||||
}
|
||||
|
||||
@@ -829,6 +832,7 @@ export class AgentTools {
|
||||
|
||||
// spec: spec/api.md#tool-connect
|
||||
private async ownChat(chatInfo: T.ChatInfo, target: string): Promise<T.ChatInfo> {
|
||||
if (isHubGroup(chatInfo)) throw hubGroupChat(target)
|
||||
const chat = chatRef(chatInfo)
|
||||
if (ownerOf(chatInfo) === undefined && chat !== undefined) await this.claim(chat)
|
||||
else if (!this.owns(chatInfo)) throw new ToolError(`The chat of ${target} belongs to another session; an admin or owner of that session's group can give it to this session with /give.`)
|
||||
@@ -1672,6 +1676,12 @@ export function ownerOf(chatInfo: T.ChatInfo): string | undefined {
|
||||
return (customDataOf(chatInfo) as {[ownerKey]?: {session?: string}} | undefined)?.[ownerKey]?.session
|
||||
}
|
||||
|
||||
// spec: spec/architecture.md#tools-customdataof
|
||||
function isHubGroup(chatInfo: T.ChatInfo): boolean {
|
||||
const data = chatInfo.type === "group" ? chatInfo.groupInfo.customData : undefined
|
||||
return data !== undefined && (mainKey in data || sessionKey in data)
|
||||
}
|
||||
|
||||
// spec: spec/architecture.md#tools-chatsubject
|
||||
export function isConnected(chatInfo: T.ChatInfo): boolean {
|
||||
if (chatInfo.type === "direct") return chatInfo.contact.activeConn?.connStatus.type === "ready"
|
||||
@@ -1756,6 +1766,11 @@ function unknownChat(chat: string): ToolError {
|
||||
return new ToolError(`No chat ${chat}. list shows the agent's chats.`)
|
||||
}
|
||||
|
||||
// spec: spec/api.md#plugin-tools
|
||||
function hubGroupChat(chat: string): ToolError {
|
||||
return new ToolError(`The chat of ${chat} is the Main group or a session's group, not one of the agent's chats.`)
|
||||
}
|
||||
|
||||
function isNotFound(error: unknown): boolean {
|
||||
const chatError = chatErrorOf(error)
|
||||
return chatError?.type === "errorStore" && notFoundErrors.includes(chatError.storeError.type)
|
||||
|
||||
@@ -428,6 +428,32 @@ describe("session groups", () => {
|
||||
expect(textOf(await session.call("connect", {target: link}, signal().call))).toBe(`The chat of ${link} belongs to another session; an admin or owner of that session's group can give it to this session with /give.`)
|
||||
})
|
||||
|
||||
it("refuse a connect to the Main group and to a session's group as known chats, and set no owner of them", async () => {
|
||||
const chat = new FakeChat()
|
||||
const session = await openSession(await hubWith(chat), id1, stored(1, "auth"))
|
||||
const link = "https://simplex.chat/g#control"
|
||||
for (const ref of ["#10", "#20"]) {
|
||||
const {groupInfo} = chat.chats.get(ref)!.chatInfo as T.ChatInfo.Group
|
||||
chat.responses.set(`/_connect plan 1 ${link}`, {type: "connectionPlan", user, connLink: {connFullLink: link}, connectionPlan: {type: "groupLink", groupLinkPlan: {type: "known", groupInfo}}})
|
||||
expect(textOf(await session.call("connect", {target: link}, signal().call))).toBe(`The chat of ${link} is the Main group or a session's group, not one of the agent's chats.`)
|
||||
}
|
||||
expect(chat.customData).toEqual([{chat: "#20", customData: {simplexMcpSession: {session: 1}}}])
|
||||
})
|
||||
|
||||
it("leave the Main group and the session groups out of list, send and receive, also with an owner", async () => {
|
||||
const chat = new FakeChat()
|
||||
const session = await openSession(await hubWith(chat), id1, stored(1, "auth"))
|
||||
for (const ref of ["#10", "#20"]) {
|
||||
const {groupInfo} = chat.chats.get(ref)!.chatInfo as T.ChatInfo.Group
|
||||
groupInfo.customData = {...groupInfo.customData, simplexMcpOwner: {session: id1}}
|
||||
}
|
||||
expect(await listed(session)).toEqual([])
|
||||
for (const ref of ["#10", "#20"]) {
|
||||
expect(textOf(await session.call("send", {chat: ref, text: "hi"}, signal().call))).toBe(`No chat ${ref}. list shows the agent's chats.`)
|
||||
expect(textOf(await session.call("receive", {chat: ref}, signal().call))).toBe(`No chat ${ref}. list shows the agent's chats.`)
|
||||
}
|
||||
})
|
||||
|
||||
it("claim a group joined after its connect call returned, and no chat of a connection pending for over a day", async () => {
|
||||
const chat = new FakeChat()
|
||||
const hub = await hubWith(chat)
|
||||
|
||||
Reference in new issue
Block a user