diff --git a/docs/CONNECTED_TOOLS.md b/docs/CONNECTED_TOOLS.md index 5dfefe7f7..8bae3d32a 100644 --- a/docs/CONNECTED_TOOLS.md +++ b/docs/CONNECTED_TOOLS.md @@ -4,7 +4,7 @@ Related #10, #6, #11. Status: implemented, with **synthetic/mock** tests only. No real Composio key, real model or live provider mutation has been used to verify this. CI passing is not Teamily parity or real-vendor verification. -Connected app tools run in the user's own DS-Bot. The FlyBot connectors feature exposes the native `ot-apps` capability and handles the owner's one-time approvals. See [the native tool server](../runtime/flybot-workspace-web/features/connectors/tool-server.js). +Connected app tools run in the user's own DS-Bot through the native `ot-apps` capability. Where that capability is mounted, GitHub tools discovered through the user's active Composio connection run automatically within the account's granted permissions. This applies to both reads and writes in private and group chats. Other connected app tools continue to use one-time owner approval. Settings shows the execution history. See [the native tool server](../runtime/flybot-workspace-web/features/connectors/tool-server.js). ## Historical management task protocol diff --git a/docs/inventory/visible-controls.json b/docs/inventory/visible-controls.json index b0ec0365b..6fa14bd49 100644 --- a/docs/inventory/visible-controls.json +++ b/docs/inventory/visible-controls.json @@ -2547,7 +2547,7 @@ {"source": "flybot_workspace/static/settings/app.mjs", "line": 657, "construction": "const confirm = document.createElement('button');", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/settings/app.mjs", "line": 865, "construction": "const button = document.createElement('button');", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/settings/app.mjs", "line": 1019, "construction": "const remove = document.createElement('button');", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/settings/connected-tools.mjs", "line": 53, "construction": "const button = document.createElement('button')", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/settings/connected-tools.mjs", "line": 55, "construction": "const button = document.createElement('button')", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/settings/custom-mcp.mjs", "line": 23, "construction": "const remove = document.createElement('button')", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/shell/app.mjs", "line": 261, "construction": "link = doc.createElement('a');", "execution_profile": "shell", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/shell/app.mjs", "line": 437, "construction": "const skip = document.createElement('a');", "execution_profile": "shell", "verification": "unverified dynamic construction site; conditional instances require execution"}, diff --git a/flybot_workspace/static/settings/connected-tools.mjs b/flybot_workspace/static/settings/connected-tools.mjs index add456505..4bf7d05c6 100644 --- a/flybot_workspace/static/settings/connected-tools.mjs +++ b/flybot_workspace/static/settings/connected-tools.mjs @@ -3,6 +3,7 @@ const APPROVAL_STATUS = { pending: '待确认', approved: '已允许', executing: '执行中', succeeded: '已完成', denied: '已拒绝', failed: '执行失败', expired: '已过期', unknown: '结果未确认', } +const AUTOMATIC_MODES = new Map([['automatic', '自动执行'], ['automatic_read', '自动只读']]) export async function mountToolApprovals(document, fetcher = globalThis.fetch, schedule = globalThis.setInterval) { const keyCard = document.getElementById('composio-key-card') @@ -14,7 +15,7 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s title.className = 'composio-key-title' title.textContent = '应用工具调用' const note = document.createElement('p') - note.textContent = '在私聊里,已授权的 GitHub 只读查询(如检查 PR 是否合并)会自动执行。修改数据、发送消息和其他工具调用需要确认。每次确认只允许所示工具和参数执行一次。' + note.textContent = '在支持 GitHub 工具的对话中,账号已授权的 GitHub 读取和写入操作会自动执行。其他应用的工具调用需逐次确认,每次只允许所示工具和参数执行一次。' const list = document.createElement('div') list.setAttribute('aria-live', 'polite') section.append(title, note, list) @@ -36,9 +37,10 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s const row = document.createElement('div') const label = document.createElement('strong') const task = typeof item.task_id === 'string' && item.task_id ? ' · 任务 ' + item.task_id.slice(0, 8) : '' - const automatic = item.approval_mode === 'automatic_read' - const mode = automatic ? ' · 自动只读' : '' - label.textContent = item.name + mode + ' · ' + (APPROVAL_STATUS[item.status] ?? '状态未知') + task + const automatic = AUTOMATIC_MODES.get(item.approval_mode) + const mode = automatic ? ' · ' + automatic : '' + const state = automatic && ['pending', 'approved'].includes(item.status) ? '待执行' : APPROVAL_STATUS[item.status] + label.textContent = item.name + mode + ' · ' + (state ?? '状态未知') + task const context = document.createElement('p') const prompt = item.prompt ? '请求:' + item.prompt + '\n' : '' context.textContent = prompt + '连接:' + (item.account ? item.account.toolkit + ' / ' + item.account.account_id : '连接已移除') diff --git a/runtime/flybot-image/native-ds-bot-overlay.mjs b/runtime/flybot-image/native-ds-bot-overlay.mjs index 2e6ef054f..425521ba6 100644 --- a/runtime/flybot-image/native-ds-bot-overlay.mjs +++ b/runtime/flybot-image/native-ds-bot-overlay.mjs @@ -11,7 +11,7 @@ const patch = fileURLToPath(new URL('./native-ds-bot.patch', import.meta.url)) const files = { 'src/host/connectors/index.js': [ '1b5da94a41a8bb5f849e7f54eaab23f9da3aaa1ee27111e1c33f79f5ef9a2b24', - 'aae09738660a91ebdf8a64645bc6f16174bea715989e7638c170c6cc2d080bd8', + '687519fce1fe28d6932e244d1970d044c143e3f68529982508f593076a9d7390', ], 'src/host/tools.js': [ 'a5c743b7c75c96498775808f029a5f15c7e08dbe6eaf33089d29b3c2a9ffb382', @@ -55,7 +55,7 @@ const files = { ], 'src/host/capabilities.js': [ '656fcc0b0fb7fd597dfd0f62bd49522d92becd4ed1c77dd53ba016f045614c89', - 'bff22001141ec0ea02714a2e440575adf7d863a036eb91f487f3f7725046349c', + '321be0845446f49d8e0a8a2c6fc6acc95e178042b33a5c37e93aa7f2e6c079ca', ], 'src/host/channel.js': [ '34b2a23af48a7c90984cca4050d3187816a9873fd513005cfb4663a6b8a33cb8', diff --git a/runtime/flybot-image/native-ds-bot.patch b/runtime/flybot-image/native-ds-bot.patch index 45ef9e5ef..57b959b1a 100644 --- a/runtime/flybot-image/native-ds-bot.patch +++ b/runtime/flybot-image/native-ds-bot.patch @@ -1258,21 +1258,7 @@ diff --git a/src/host/capabilities.js b/src/host/capabilities.js index efe6323..e0e439e 100644 --- a/src/host/capabilities.js +++ b/src/host/capabilities.js -@@ -336,6 +336,13 @@ export function install(rt) { - let config - try { - config = configFor(item, bot.id) -+ // Never pass the private read endpoint to a group or detached task. -+ if (name === 'ot-apps' && config.transport === 'streamable-http' -+ && rt.chatOwners?.get(sessionId) === bot.id -+ && rt.groupOwners?.has(sessionId) === false && rt.taskOwners?.has(sessionId) === false) { -+ const url = await rt.flybotWorkspaceApps?.ownerPrivateToolUrl?.(config.url) -+ if (url) config.url = url -+ } - } catch (error) { - await drop() - statusSet(bot.id, name, sessionId, { state: 'error', error: rt.redactSecrets(error.message).slice(0, 300) }) -@@ -397,7 +404,9 @@ export function install(rt) { +@@ -397,7 +397,9 @@ export function install(rt) { } const desiredFor = (agent, bot) => { const sessionId = agent.session.id @@ -2221,8 +2207,8 @@ diff --git a/src/host/connectors/index.js b/src/host/connectors/index.js + const visible = new Set(attached ? (agent?.ctx?.tools?.schemas?.(agent) ?? []).map(tool => tool.name) : []) + return new Map(rows.map(({ slug, tools }) => [slug, tools.map(publicAppTool).filter(name => visible.has(name))])) + } -+ const describeComposio = tools => tools.length -+ ? `connected through FlyBot (Composio); ${tools.length} app tools available in this chat, including ${tools.slice(0, 5).join(', ')}. Calls require owner approval in /settings/connectors.` ++ const describeComposio = (slug, tools) => tools.length ++ ? `connected through FlyBot (Composio); ${tools.length} app tools available in this chat, including ${tools.slice(0, 5).join(', ')}. ${slug === 'github' ? 'Calls run automatically within the authorized GitHub permissions.' : 'Calls require owner approval in /settings/connectors.'}` + : 'connected through FlyBot (Composio); no app tools are currently mounted in this chat. Check /settings/connectors.' + const requestsOf = (botId) => { @@ -2248,13 +2234,13 @@ diff --git a/src/host/connectors/index.js b/src/host/connectors/index.js const connected = entry.id === 'mail' ? mailHasAccounts() : (statuses.get(entry.id)?.state === undefined && mounts.has(entry.id)) || hasCredential(entry.id) const usable = !offFor(entry.id).includes(bot.id) + const tools = apps.get(entry.id) -+ if (tools && (tools.length || !connected || !usable)) return `- ${entry.name} (${entry.id}) — ${describeComposio(tools)}` ++ if (tools && (tools.length || !connected || !usable)) return `- ${entry.name} (${entry.id}) — ${describeComposio(entry.id, tools)}` return `- ${entry.name} (${entry.id}) — ${entry.about} — ${connected ? 'connected' : 'not connected'}${usable ? '' : '; turned off for you'}` }) - return ['Connectors:', ...lines].join('\n') + const native = new Set(rows.map(entry => entry.id)) + for (const [slug, tools] of apps) { -+ if (!native.has(slug)) lines.push(`- ${slug} — ${describeComposio(tools)}`) ++ if (!native.has(slug)) lines.push(`- ${slug} — ${describeComposio(slug, tools)}`) + } + return lines.length ? ['Connectors:', ...lines].join('\n') : 'No connectors are set up.' }, @@ -2273,9 +2259,9 @@ diff --git a/src/host/connectors/index.js b/src/host/connectors/index.js const connected = id === 'mail' ? mailHasAccounts() : hasCredential(id) const signIn = statuses.get(id)?.state === 'needs-sign-in' - if (connected && !signIn && !offFor(id).includes(bot.id)) return `${entry.name} is already connected; use its tools (mcp__${id}__*).` -+ if (appTools?.length) return `${entry?.name ?? id} is ${describeComposio(appTools)}` ++ if (appTools?.length) return `${entry?.name ?? id} is ${describeComposio(id, appTools)}` + if (entry && connected && !signIn && !offFor(id).includes(bot.id)) return `${entry.name} is already connected; use its tools (mcp__${id}__*).` -+ if (appTools) return `${entry?.name ?? id} is ${describeComposio(appTools)}` ++ if (appTools) return `${entry?.name ?? id} is ${describeComposio(id, appTools)}` + if (entry === undefined) return `No connector named ${id}.` if (offFor(id).includes(bot.id)) return `${entry.name} is turned off for you. The user can turn it on in your details.` if (rt.taskOwners?.has(agentId)) return 'Background tasks cannot show connector cards. Finish or report back to your own chat so it can ask the user.' diff --git a/runtime/flybot-image/test/native-open-parts.test.mjs b/runtime/flybot-image/test/native-open-parts.test.mjs index 4d0e06315..ccc585706 100644 --- a/runtime/flybot-image/test/native-open-parts.test.mjs +++ b/runtime/flybot-image/test/native-open-parts.test.mjs @@ -114,6 +114,7 @@ test('native connector tools use the mounted Composio connection without asking const args = {id:'github',purpose:'Inspect a repository'} const result = String(await list.execute({},exec)) assert.match(result,/GitHub \(github\).*connected through FlyBot \(Composio\).*mcp__ot-apps__GITHUB_LIST_REPOS/) + assert.match(result,/run automatically within the authorized GitHub permissions/) assert.doesNotMatch(result,/GITHUB_CREATE_ISSUE/) assert.match(String(await request.execute(args,exec)),/connected through FlyBot \(Composio\)/) assert.equal(rt.state.connectorRequests?.writer?.length ?? 0,0) diff --git a/runtime/flybot-workspace-web/features/connectors/connectors.js b/runtime/flybot-workspace-web/features/connectors/connectors.js index 211547cf8..8e816ba1a 100644 --- a/runtime/flybot-workspace-web/features/connectors/connectors.js +++ b/runtime/flybot-workspace-web/features/connectors/connectors.js @@ -16,28 +16,7 @@ const MAX_ARGS = 12000 const MAX_RESULT = 10000 const MAX_CALLS_KEPT = 100 const APPROVAL_TTL = 300 -const AUTOMATIC_READ = 'automatic_read' -// Each entry is a known read in Composio's GitHub toolkit. Tool descriptions, -// name prefixes, and hints from custom MCP servers do not grant execution. -// https://docs.composio.dev/toolkits/github -// https://docs.github.com/en/rest/pulls/pulls#check-if-a-pull-request-has-been-merged -const GITHUB_READS = new Set([ - 'GITHUB_CHECK_IF_PULL_REQUEST_HAS_BEEN_MERGED', - 'GITHUB_CHECK_IF_PULL_REQUEST_MERGED', - 'GITHUB_GET_A_PULL_REQUEST', - 'GITHUB_LIST_PULL_REQUESTS', - 'GITHUB_GET_A_REPOSITORY', - 'GITHUB_GET_REPOS', - 'GITHUB_LIST_REPOS', - 'GITHUB_LIST_REPOSITORIES', - 'GITHUB_LIST_REPOSITORIES_FOR_THE_AUTHENTICATED_USER', - 'GITHUB_LIST_REPOSITORIES_FOR_A_USER', - 'GITHUB_GET_AN_ISSUE', - 'GITHUB_LIST_REPOSITORY_ISSUES', - 'GITHUB_GET_A_RELEASE', - 'GITHUB_GET_A_RELEASE_BY_TAG_NAME', - 'GITHUB_LIST_RELEASES', -]) +const AUTOMATIC = 'automatic' const newId = () => randomUUID().replaceAll('-', '') const KEY_PURPOSE = 'flybot-workspace.composio.key' const mcpPurpose = id => `flybot-workspace.mcp.${id}` @@ -62,7 +41,7 @@ const keyView = row => (row ? { configured: true, key_hint: row.key_hint, revisi const serverView = row => ({ id: row.id, name: row.name, origin: row.origin, revision: row.revision, created: row.created, updated: row.updated }) const callView = (row, withArgs = false) => { const view = { id: row.id, task_id: null, name: row.name, status: row.status, created: row.created, expires: row.expires } - if (row.approval_mode === AUTOMATIC_READ) view.approval_mode = AUTOMATIC_READ + if (row.approval_mode === AUTOMATIC || row.approval_mode === 'automatic_read') view.approval_mode = row.approval_mode if (withArgs) view.arguments = JSON.parse(row.arguments) if (row.result != null) view.result = row.result return view @@ -367,25 +346,31 @@ export function createConnectors({ dir, sealKey, identity, env = process.env, cl return false }) } - function propose(name, args, { automaticReads = false } = {}) { + function propose(name, args) { const entry = catalog.get(name) if (!entry) fail(403, 'tool_not_discovered', 'Tool is not connected for this account') if (!isObject(args)) fail(400, 'invalid', 'arguments must be an object') const argumentsText = JSON.stringify(sortKeys(args)) if (Buffer.byteLength(argumentsText) > MAX_ARGS) fail(413, 'invalid', 'Tool arguments exceed bound') - const automatic = automaticReads === true && entry.kind === 'composio' && entry.toolkit === 'github' && GITHUB_READS.has(name) + const automatic = entry.kind === 'composio' && entry.toolkit === 'github' const now = clock() return store.update((draft) => { expireCalls(draft, now, MAX_CALLS_KEPT - 1) - // Allow the same account, tool and arguments to resume an approval. - // A private automatic receipt cannot be claimed by another context. + // Reuse the exact receipt, including an in-flight GitHub operation, to avoid a duplicate write. const open = draft.calls.find(row => row.name === name && row.arguments === argumentsText && row.kind === entry.kind && row.ref === entry.ref && row.version === entry.version && row.revision === entry.revision && - (row.approval_mode === AUTOMATIC_READ) === automatic && live(row, now)) - if (open) return open + (live(row, now) || (automatic && row.status === 'executing' && row.expires > now))) + if (open) { + // An old pending receipt may proceed only when the Bot calls it again. + if (automatic && open.status === 'pending') { + open.status = 'approved' + open.approval_mode = AUTOMATIC + } + return open + } if (draft.calls.length >= MAX_CALLS_KEPT) fail(429, 'quota', 'Too many active connected-tool calls') const row = { id: newId(), name, kind: entry.kind, ref: entry.ref, version: entry.version, revision: entry.revision, arguments: argumentsText, - status: automatic ? 'approved' : 'pending', ...(automatic ? {approval_mode: AUTOMATIC_READ} : {}), + status: automatic ? 'approved' : 'pending', ...(automatic ? {approval_mode: AUTOMATIC} : {}), result: null, created: now, expires: now + APPROVAL_TTL } draft.calls.push(row) return row @@ -427,12 +412,11 @@ export function createConnectors({ dir, sealKey, identity, env = process.env, cl }) return { items } } - async function run(id, { automaticReads = false } = {}) { + async function run(id) { // Consume the approval before any network I/O; 'executing' is terminal. let claimed = false const row = store.update((draft) => { const item = draft.calls.find(c => c.id === id) - if (item?.approval_mode === AUTOMATIC_READ && automaticReads !== true) return null if (!item || item.status !== 'approved' || item.expires <= clock()) return item ? { ...item } : null item.status = 'executing' claimed = true @@ -443,11 +427,17 @@ export function createConnectors({ dir, sealKey, identity, env = process.env, cl try { const st = state() if (row.kind === 'composio') { - const account = st.connections.find(c => c.id === row.ref && c.status === 'ACTIVE') + const activeAccount = snapshot => snapshot.connections.find(c => c.id === row.ref && c.status === 'ACTIVE') + const account = activeAccount(st) const key = secretKey() if (!account || !key || st.composio?.revision !== row.revision) throw new Fault(409, 'connection_changed', 'Connection or key changed; call blocked') const c = new composio.Client(key, transport) const remote = await c.getAccount(account.account_id) + const latest = state() + if (latest.composio?.revision !== row.revision || latest.composio?.key_sealed !== st.composio.key_sealed || + activeAccount(latest)?.account_id !== account.account_id) { + throw new Fault(409, 'connection_changed', 'Connection or key changed; call blocked') + } if (remote.status !== 'ACTIVE' || ![undefined, null, '', userRef()].includes(remote.user_id)) { status = 'failed'; result = { error: 'connection_not_active' } } else { @@ -476,19 +466,20 @@ export function createConnectors({ dir, sealKey, identity, env = process.env, cl return item ? { ...item } : null }) } - // One agent tool call. Verified private reads are ready to run immediately. + // One agent tool call. Connected GitHub tools are ready to run immediately. // Other tools wait for a bounded period on a one-shot owner decision. - async function callTool(name, args, { automaticReads = false, waitMs = 40_000, pollMs = 500 } = {}) { + async function callTool(name, args, { waitMs = 40_000, pollMs = 500 } = {}) { if (!catalog.has(name)) await discover({ force: true }) - let row = propose(name, args, {automaticReads}) + let row = propose(name, args) const deadline = Date.now() + waitMs while (row && row.status === 'pending' && Date.now() < deadline) { await sleep(pollMs) row = state().calls.find(c => c.id === row.id) } - if (row?.status === 'approved') row = await run(row.id, {automaticReads}) + if (row?.status === 'approved') row = await run(row.id) if (!row) return { error: 'tool_unavailable' } if (row.status === 'pending') return { error: 'tool_pending', approval_id: row.id, note: 'Waiting for the owner to approve in Settings > App connectors; call again with the same arguments after approval. No implicit retry.' } + if (row.status === 'executing') return { error: 'tool_executing', note: 'The matching call is already running. Do not repeat it.' } return row.result ?? { error: 'tool_' + row.status, note: 'Await owner approval in Settings > App connectors; no implicit retry.' } } diff --git a/runtime/flybot-workspace-web/features/connectors/index.js b/runtime/flybot-workspace-web/features/connectors/index.js index f5de9eb45..bb3a42fdf 100644 --- a/runtime/flybot-workspace-web/features/connectors/index.js +++ b/runtime/flybot-workspace-web/features/connectors/index.js @@ -32,7 +32,7 @@ export default function connectors(host) { pending = setTimeout(() => { pending = null; sync().then((done) => { if (done === false && !host.currentRuntime()?.mainBot) schedule(5000) }).catch(error => { host.log(`apps capability sync failed: ${String(error?.code ?? error?.message ?? 'error').slice(0, 80)}`); schedule(15000) }) }, delay) pending.unref?.() } - const apps = Object.freeze({ connectedToolkits: api.connectedToolkits, ownerPrivateToolUrl: tools.ownerPrivateToolUrl, sync }) + const apps = Object.freeze({ connectedToolkits: api.connectedToolkits, sync }) const attach = runtime => { if (!runtime?.rt) return runtime.rt.flybotWorkspaceApps = apps diff --git a/runtime/flybot-workspace-web/features/connectors/tool-server.js b/runtime/flybot-workspace-web/features/connectors/tool-server.js index 6178ed73d..155615ab6 100644 --- a/runtime/flybot-workspace-web/features/connectors/tool-server.js +++ b/runtime/flybot-workspace-web/features/connectors/tool-server.js @@ -1,15 +1,14 @@ // Loopback MCP server (streamable HTTP, JSON responses) that gives this user's // DS-Bot its connected app tools as a native MCP capability ("ot-apps"). // Bound to 127.0.0.1 with a per-boot random path token; requests carrying an -// Origin header (browsers, DNS rebinding) are refused. A separate path is -// mounted only in the owner's native private chats for automatic reads. +// Origin header (browsers, DNS rebinding) are refused. import { createServer } from 'node:http' import { randomBytes } from 'node:crypto' export const CAPABILITY = 'ot-apps' const BODY_LIMIT = 1024 * 1024 -export async function handleRpc(connectors, message, {automaticReads = false} = {}) { +export async function handleRpc(connectors, message) { if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string') return { jsonrpc: '2.0', id: message?.id ?? null, error: { code: -32600, message: 'Invalid Request' } } if (message.id === undefined) return null const ok = result => ({ jsonrpc: '2.0', id: message.id, result }) @@ -17,9 +16,7 @@ export async function handleRpc(connectors, message, {automaticReads = false} = case 'initialize': return ok({ protocolVersion: typeof message.params?.protocolVersion === 'string' ? message.params.protocolVersion : '2025-03-26', capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'flybot-workspace-apps', version: '1.0.0' }, - instructions: automaticReads - ? "Your owner's connected apps. Known read-only Composio queries run automatically in this private chat. Other calls wait for approval in Settings > App connectors." - : "Your owner's connected apps. Calls in this context wait for approval in Settings > App connectors." }) + instructions: "Your owner's connected GitHub tools run automatically within their granted permissions. Other connected app calls wait for approval in Settings > App connectors." }) case 'ping': return ok({}) case 'tools/list': @@ -28,7 +25,7 @@ export async function handleRpc(connectors, message, {automaticReads = false} = const args = message.params?.arguments ?? {} if (!args || typeof args !== 'object' || Array.isArray(args)) return { jsonrpc: '2.0', id: message.id, error: { code: -32602, message: 'arguments must be an object' } } try { - const result = await connectors.callTool(String(message.params?.name ?? ''), args, {automaticReads}) + const result = await connectors.callTool(String(message.params?.name ?? ''), args) return ok({ isError: Boolean(result?.error), content: [{ type: 'text', text: JSON.stringify(result).slice(0, 60000) }] }) } catch (error) { return ok({ isError: true, content: [{ type: 'text', text: JSON.stringify({ error: error?.code ?? 'tool_failed', note: 'No automatic retry.' }) }] }) @@ -41,12 +38,11 @@ export async function handleRpc(connectors, message, {automaticReads = false} = export function startToolServer(connectors, { port = 0, host = '127.0.0.1' } = {}) { const path = `/mcp/${randomBytes(18).toString('hex')}` - const ownerPath = `/mcp/${randomBytes(18).toString('hex')}` const server = createServer(async (req, res) => { const send = (status, value) => { const body = Buffer.from(JSON.stringify(value)); res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': body.length, 'Cache-Control': 'no-store' }); res.end(body) } if (req.headers.origin !== undefined) return send(403, { error: 'forbidden' }) const requestPath = (req.url || '').split('?')[0] - if (requestPath !== path && requestPath !== ownerPath) return send(404, { error: 'not found' }) + if (requestPath !== path) return send(404, { error: 'not found' }) if (req.method !== 'POST') { res.writeHead(405, { Allow: 'POST' }); return res.end() } const chunks = [] let size = 0 @@ -56,7 +52,7 @@ export function startToolServer(connectors, { port = 0, host = '127.0.0.1' } = { const message = JSON.parse(Buffer.concat(chunks).toString('utf8')) const batch = Array.isArray(message) const replies = [] - for (const item of batch ? message : [message]) { const reply = await handleRpc(connectors, item, {automaticReads:requestPath === ownerPath}); if (reply) replies.push(reply) } + for (const item of batch ? message : [message]) { const reply = await handleRpc(connectors, item); if (reply) replies.push(reply) } if (!replies.length) { res.writeHead(202); return res.end() } send(200, batch ? replies : replies[0]) } catch { if (!res.headersSent) send(400, { error: 'bad request' }) } @@ -66,14 +62,7 @@ export function startToolServer(connectors, { port = 0, host = '127.0.0.1' } = { server.once('error', reject) server.listen(port, host, () => resolve(`http://${host}:${server.address().port}${path}`)) }) - async function ownerPrivateToolUrl(candidate) { - if (typeof candidate !== 'string') return undefined - const normal = await ready - const [base, version] = candidate.split('?') - if (base !== normal) return undefined - return normal.slice(0, -path.length) + ownerPath + (version ? `?${version}` : '') - } - return { server, ready, ownerPrivateToolUrl, close: () => new Promise(resolve => server.close(() => resolve())) } + return { server, ready, close: () => new Promise(resolve => server.close(() => resolve())) } } // Save/attach the capability on the user's Main Bot once the runtime wrapper @@ -86,7 +75,7 @@ export async function syncCapability({ rt, mainBot }, url, version, wanted) { if (attached) await rt.changeCapabilityAttachment('detach', { name: CAPABILITY }, botId).catch(() => {}) return false } - await rt.capabilitySave({ name: CAPABILITY, kind: 'mcp', description: "Owner's connected apps. Known Composio reads run automatically in private chats. Other calls require approval.", transport: 'streamable-http', url: `${url}?v=${version}` }, { ui: true }) + await rt.capabilitySave({ name: CAPABILITY, kind: 'mcp', description: "Owner's connected apps. Authorized GitHub calls run automatically. Other calls require approval.", transport: 'streamable-http', url: `${url}?v=${version}` }, { ui: true }) if (!attached) await rt.changeCapabilityAttachment('attach', { name: CAPABILITY }, botId) return true } diff --git a/runtime/flybot-workspace-web/test/connector-private-tools.test.js b/runtime/flybot-workspace-web/test/connector-private-tools.test.js deleted file mode 100644 index cac0f075a..000000000 --- a/runtime/flybot-workspace-web/test/connector-private-tools.test.js +++ /dev/null @@ -1,32 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import {startToolServer} from '../features/connectors/tool-server.js' - -test('only the private native MCP endpoint can opt into automatic Composio reads', async t => { - const seen = [] - const tools = startToolServer({ - async callTool(_name, _args, options) { - seen.push(options.automaticReads) - return {success:true} - }, - }) - t.after(tools.close) - const manual = await tools.ready - const owner = await tools.ownerPrivateToolUrl(manual + '?v=7') - assert.notEqual(new URL(owner).pathname, new URL(manual).pathname) - assert.equal(new URL(owner).search, '?v=7') - assert.equal(await tools.ownerPrivateToolUrl('https://example.com/mcp?v=7'), undefined) - - const call = (url, headers = {}) => fetch(url, { - method:'POST', headers:{'Content-Type':'application/json', ...headers}, - body:JSON.stringify({jsonrpc:'2.0', id:1, method:'tools/call', - params:{name:'GITHUB_CHECK_IF_PULL_REQUEST_MERGED', arguments:{pull_number:1}}}), - }) - const ordinary = await call(manual + '?automaticReads=true') - assert.equal(ordinary.status, 200) - const privateChat = await call(owner) - assert.equal(privateChat.status, 200) - const browser = await call(owner, {Origin:'https://botawaken.com'}) - assert.equal(browser.status, 403) - assert.deepEqual(seen, [false,true]) -}) diff --git a/runtime/flybot-workspace-web/test/connector-tool-server.test.js b/runtime/flybot-workspace-web/test/connector-tool-server.test.js new file mode 100644 index 000000000..eb37352db --- /dev/null +++ b/runtime/flybot-workspace-web/test/connector-tool-server.test.js @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import {startToolServer} from '../features/connectors/tool-server.js' + +test('the native connector endpoint only accepts calls at its loopback capability path', async t => { + const seen = [] + const tools = startToolServer({ + async callTool(...args) { + seen.push(args) + return {successful:true} + }, + }) + t.after(tools.close) + const url = await tools.ready + const name = 'GITHUB_CREATE_AN_ISSUE_COMMENT' + const args = {issue_number:1, body:'Fixture'} + const call = (address, headers = {}) => fetch(address, { + method:'POST', headers:{'Content-Type':'application/json', ...headers}, + body:JSON.stringify({jsonrpc:'2.0', id:1, method:'tools/call', params:{name, arguments:args}}), + }) + assert.equal(new URL(url).hostname, '127.0.0.1') + const rejected = await call(new URL('/mcp/invalid',url)) + assert.equal(rejected.status, 404) + const browser = await call(url, {Origin:'https://botawaken.com'}) + assert.equal(browser.status, 403) + const runtime = await call(url + '?v=7') + assert.equal(runtime.status, 200) + assert.deepEqual(seen, [[name,args]]) +}) diff --git a/runtime/flybot-workspace-web/test/connectors.test.js b/runtime/flybot-workspace-web/test/connectors.test.js index c12851932..c9f4c764e 100644 --- a/runtime/flybot-workspace-web/test/connectors.test.js +++ b/runtime/flybot-workspace-web/test/connectors.test.js @@ -206,26 +206,26 @@ test('custom MCP servers: public HTTPS only, bearer sealed, endpoint change need test('manual tool calls wait for the owner, run once, and scrub credentials', async () => { const { api, v1, composio, mcp } = make() await v1('POST', '/v1/composio/key', { api_key: KEY }) - await v1('POST', '/v1/composio/connections', { toolkit: 'github' }) + composio.accounts.set('ca_slack', {id:'ca_slack', status:'ACTIVE', toolkit:{slug:'slack'}, user_id:USER}) await v1('GET', '/v1/composio/connections') await v1('POST', '/v1/mcp/servers', { name: 'Docs', url: 'https://mcp.example/mcp', bearer_token: 'tok_secret_123' }) const tools = await api.discover({ force: true }) const names = tools.map(t => t.name) - assert.ok(names.includes('GITHUB_LIST_REPOS')) + assert.ok(names.includes('SLACK_LIST_CHANNELS')) assert.ok(!names.includes('COMPOSIO_SEARCH')) const mcpName = names.find(n => n.startsWith('OTMCP_')) assert.ok(mcpName) assert.ok(!JSON.stringify(tools).includes('tok_secret_123')) - const waiting = await api.callTool('GITHUB_LIST_REPOS', { per_page: 1 }, { waitMs: 0 }) + const waiting = await api.callTool('SLACK_LIST_CHANNELS', { per_page: 1 }, { waitMs: 0 }) assert.equal(waiting.error, 'tool_pending') assert.equal(composio.calls.filter(c => c.path.includes('/tools/execute/')).length, 0, 'nothing executes before approval') const listing = await v1('GET', '/v1/composio/approvals') const item = listing.body.items[0] - assert.deepEqual([item.status, item.arguments, item.account.toolkit], ['pending', { per_page: 1 }, 'github']) + assert.deepEqual([item.status, item.arguments, item.account.toolkit], ['pending', { per_page: 1 }, 'slack']) assert.equal((await v1('POST', `/v1/composio/approvals/${item.id}`, { decision: 'maybe' })).status, 400) assert.equal((await v1('POST', `/v1/composio/approvals/${item.id}`, { decision: 'approve' })).body.call.status, 'approved') - const result = await api.callTool('GITHUB_LIST_REPOS', { per_page: 1 }, { waitMs: 0 }) + const result = await api.callTool('SLACK_LIST_CHANNELS', { per_page: 1 }, { waitMs: 0 }) assert.deepEqual(result.data.repos, ['a']) assert.equal(result.data.echo, '[redacted]', 'our key never comes back to the agent') assert.equal(composio.calls.filter(c => c.path.includes('/tools/execute/')).length, 1) @@ -253,20 +253,19 @@ test('approvals expire, and a key change blocks an approved call', async () => { await v1('POST', '/v1/composio/connections', { toolkit: 'github' }) await v1('GET', '/v1/composio/connections') await api.discover({ force: true }) - const first = await api.callTool('GITHUB_LIST_REPOS', {}, { waitMs: 0 }) + const first = api.propose('GITHUB_LIST_REPOS', {}) tick(301) - assert.equal((await v1('POST', `/v1/composio/approvals/${first.approval_id}`, { decision: 'approve' })).status, 409) - const second = await api.callTool('GITHUB_LIST_REPOS', {}, { waitMs: 0 }) - await v1('POST', `/v1/composio/approvals/${second.approval_id}`, { decision: 'approve' }) + assert.equal((await v1('POST', `/v1/composio/approvals/${first.id}`, { decision: 'approve' })).status, 409) + const second = api.propose('GITHUB_LIST_REPOS', {}) + assert.equal(second.status, 'approved') await v1('POST', '/v1/composio/key', { api_key: KEY }) - assert.equal((await api.run(second.approval_id)).result.error, 'connection_changed') + assert.equal((await api.run(second.id)).result.error, 'connection_changed') assert.equal(composio.calls.filter(c => c.path.includes('/tools/execute/')).length, 0) }) -test('concurrent callers consume an approved receipt once while the provider call is in flight', async () => { - const upstream = fakeComposio() - const checkedApproval = Promise.withResolvers() - const allowApprovalPoll = Promise.withResolvers() +test('identical automatic GitHub writes execute once while the provider call is in flight', async () => { + const write = 'GITHUB_CREATE_AN_ISSUE_COMMENT' + const upstream = fakeComposio({githubTools:[write]}) const providerStarted = Promise.withResolvers() const releaseProvider = Promise.withResolvers() let executes = 0 @@ -279,29 +278,21 @@ test('concurrent callers consume an approved receipt once while the provider cal } return upstream.transport(...args) }, - async sleep() { - checkedApproval.resolve() - await allowApprovalPoll.promise - }, }) api.saveKey({api_key: KEY}) - upstream.accounts.set('ca_1', {id:'ca_1', status:'ACTIVE', toolkit:{slug:'github'}, user_id:USER}) + await api.connect({toolkit:'github'}) await api.syncConnections() - const first = api.callTool('GITHUB_LIST_REPOS', {}) - await checkedApproval.promise - const approval = api.approvals().items[0] - api.decide(approval.id,{decision:'approve'}) - allowApprovalPoll.resolve() - await providerStarted.promise - - const concurrent = api.run(approval.id) - releaseProvider.resolve() - const [result, second] = await Promise.all([first,concurrent]) - assert.equal(result.successful, true) - assert.equal(second.status,'executing') - assert.equal(executes,1) - assert.equal((await api.run(approval.id)).status,'succeeded') - assert.equal(executes,1) + const args = {issue_number:1, body:'Fixture'} + const first = api.callTool(write, args) + try { + await providerStarted.promise + assert.equal((await api.callTool(write, args)).error, 'tool_executing') + assert.equal(executes, 1) + } finally { + releaseProvider.resolve() + } + assert.equal((await first).successful, true) + assert.equal(api.approvals().items.filter(row => row.name === write).length, 1) }) test('the pending approval view returns only a boolean without writing expired state', async () => { @@ -311,10 +302,10 @@ test('the pending approval view returns only a boolean without writing expired s assert.deepEqual(await pending(),{pending:false}) assert.equal((await v1('GET',path,undefined,'view=pending&extra=true')).status,400) api.saveKey({api_key: KEY}) - composio.accounts.set('ca_1', {id:'ca_1', status:'ACTIVE', toolkit:{slug:'github'}, user_id:USER}) + composio.accounts.set('ca_1', {id:'ca_1', status:'ACTIVE', toolkit:{slug:'slack'}, user_id:USER}) await api.syncConnections() await api.discover() - api.propose('GITHUB_LIST_REPOS',{organization:'private-fixture'}) + api.propose('SLACK_LIST_CHANNELS',{organization:'private-fixture'}) const saved = readFileSync(api.store.file,'utf8') assert.deepEqual(await pending(),{pending:true}) tick(301) @@ -323,60 +314,80 @@ test('the pending approval view returns only a boolean without writing expired s assert.equal((await v1('GET',path)).body.items[0].status,'expired') }) -test('verified GitHub reads run automatically only for a trusted private call', async () => { - const read = 'GITHUB_CHECK_IF_PULL_REQUEST_MERGED' - const alias = 'GITHUB_CHECK_IF_PULL_REQUEST_HAS_BEEN_MERGED' - const history = 'GITHUB_LIST_REPOS' - const write = 'GITHUB_CREATE_AN_ISSUE' - const unknown = 'GITHUB_GET_UNVERIFIED_ACTION' - const upstream = fakeComposio({githubTools:[read,alias,history,write,unknown]}) +test('the native tool endpoint runs authorized GitHub reads and writes while other connectors wait', async t => { + const read = 'GITHUB_GET_A_PULL_REQUEST' + const write = 'GITHUB_CREATE_AN_ISSUE_COMMENT' + const close = 'GITHUB_UPDATE_AN_ISSUE' + const upstream = fakeComposio({githubTools:[read,write,close]}) const { api } = make({transport:upstream.transport}) - api.saveKey({api_key: KEY}) + api.saveKey({api_key:KEY}) await api.connect({toolkit:'github'}) + upstream.accounts.set('ca_slack', {id:'ca_slack',status:'ACTIVE',toolkit:{slug:'slack'},user_id:USER}) await api.syncConnections() - const args = {owner:'fixture',repo:'example',pull_number:5} - - const shared = await api.callTool(read,args,{waitMs:0}) - assert.equal(shared.error,'tool_pending') - const privateReceipt = api.propose(read,args,{automaticReads:true}) - assert.notEqual(privateReceipt.id,shared.approval_id) - assert.equal(await api.run(privateReceipt.id),null) - assert.equal(upstream.calls.filter(call => call.path.includes('/tools/execute/')).length,0) + api.saveServer({name:'Remote',url:'https://mcp.example/mcp'}) + const mcpTool = (await api.discover()).find(tool => tool.description.startsWith('Remote:')) - for (const name of [read,alias,history]) { - const result = await api.callTool(name,args,{automaticReads:true,waitMs:0}) + const mcp = startToolServer(api) + t.after(mcp.close) + const url = await mcp.ready + for (const [index, name] of [read, write, close].entries()) { + const response = await fetch(url, {method:'POST',headers:{'Content-Type':'application/json'}, + body:JSON.stringify({jsonrpc:'2.0', id:index+1, method:'tools/call', + params:{name,arguments:{issue_number:1}}})}) + assert.equal(response.status, 200) + const result = JSON.parse((await response.json()).result.content[0].text) assert.equal(result.successful,true) assert.notEqual(result.data.echo,KEY) } - for (const name of [write,unknown]) { - assert.equal((await api.callTool(name,args,{automaticReads:true,waitMs:0})).error,'tool_pending') + for (const name of ['SLACK_LIST_CHANNELS', mcpTool.name]) { + assert.equal((await api.callTool(name,{}, {waitMs:0})).error,'tool_pending') } - api.saveServer({name:'Remote',url:'https://mcp.example/mcp'}) - const mcpTool = (await api.discover()).find(tool=>tool.description.startsWith('Remote:')) - assert.equal((await api.callTool(mcpTool.name,{}, {automaticReads:true,waitMs:0})).error,'tool_pending') assert.deepEqual(upstream.calls.filter(call => call.path.includes('/tools/execute/')) .map(call=>[call.path.split('/').at(-1),call.body.connected_account_id,call.body.user_id]), - [read,alias,history].map(name=>[name,'ca_1',USER])) - const items = api.approvals().items - assert.equal(items.find(row=>row.id===shared.approval_id).status,'pending') - assert.ok(items.slice(0,4).every(row=>row.status==='pending')) - assert.deepEqual(items.filter(row=>row.approval_mode==='automatic_read').map(row=>row.status), - ['succeeded','succeeded','succeeded']) + [read,write,close].map(name=>[name,'ca_1',USER])) + assert.deepEqual(api.approvals().items.map(row => row.status).sort(), + ['pending','pending','succeeded','succeeded','succeeded']) + assert.equal(api.approvals().items.filter(row => row.approval_mode==='automatic').length, 3) +}) + +test('a live legacy GitHub approval runs only on a fresh call and expired history is preserved', async () => { + const write = 'GITHUB_CREATE_AN_ISSUE_COMMENT' + const upstream = fakeComposio({githubTools:[write]}) + const { api } = make({transport:upstream.transport}) + api.saveKey({api_key:KEY}) + await api.connect({toolkit:'github'}) + await api.syncConnections() + await api.discover() + const args = {issue_number:1, body:'Fixture'} + const old = api.propose(write,args) + api.store.update(draft => { + const pending = draft.calls[0] + delete pending.approval_mode + pending.status = 'pending' + draft.calls.push({...pending,id:'e'.repeat(32), arguments:'{"issue_number":2}', expires:pending.created-1}) + }) + + assert.equal(api.approvals().items.find(row=>row.id===old.id).status,'pending') + assert.equal(upstream.calls.filter(call => call.path.includes('/tools/execute/')).length,0) + assert.equal((await api.callTool(write,args)).successful,true) + const rows = api.approvals().items + assert.equal(rows.length, 2) + assert.equal(rows.find(row=>row.id===old.id).approval_mode,'automatic') + assert.equal(rows.find(row=>row.id===old.id).status,'succeeded') + assert.equal(rows.find(row=>row.id==='e'.repeat(32)).status,'expired') }) -test('a burst of automatic read history preserves a write still waiting for approval', async () => { - const read = 'GITHUB_LIST_REPOS' - const write = 'GITHUB_CREATE_AN_ISSUE' - const upstream = fakeComposio({githubTools:[read,write]}) - const { api, tick } = make({transport:upstream.transport}) +test('a burst of automatic GitHub history preserves a different app awaiting approval', async () => { + const { api, composio, tick } = make() api.saveKey({api_key:KEY}) await api.connect({toolkit:'github'}) + composio.accounts.set('ca_slack', {id:'ca_slack',status:'ACTIVE',toolkit:{slug:'slack'},user_id:USER}) await api.syncConnections() - const pending = await api.callTool(write,{title:'Fixture'},{automaticReads:true,waitMs:0}) + const pending = await api.callTool('SLACK_LIST_CHANNELS',{limit:1},{waitMs:0}) assert.equal(pending.error,'tool_pending') for (let i = 0; i < 105; i += 1) { tick(1) - assert.equal((await api.callTool(read,{page:i+1},{automaticReads:true,waitMs:0})).successful,true) + assert.equal((await api.callTool('GITHUB_LIST_REPOS',{page:i+1},{waitMs:0})).successful,true) } assert.equal(api.approvals().items[0].id,pending.approval_id) assert.equal(api.approvals().items[0].status,'pending') diff --git a/tests/settings_page.test.mjs b/tests/settings_page.test.mjs index 56203890d..e07cfc4de 100644 --- a/tests/settings_page.test.mjs +++ b/tests/settings_page.test.mjs @@ -1084,7 +1084,7 @@ test('connected-tool approvals do not imply a connected account before key setup assert.doesNotMatch(source, /innerHTML/); }); -test('verified read activity has no approval buttons and native writes require one explicit decision', async () => { +test('automatic GitHub activity has no approval buttons and another app requires an explicit decision', async () => { const {doc} = settingsDocument(); let section; doc.getElementById('composio-key-card').after = node => { section = node; }; @@ -1098,29 +1098,34 @@ test('verified read activity has no approval buttons and native writes require o return createElement(tag); }; const id = 'a'.repeat(32); - const item = {id, name: 'GITHUB_CREATE_ISSUE', status: 'pending', task_id: null, - arguments: {title: 'fixture issue'}, account: {toolkit: 'github', account_id: 'fixture'}, prompt: ''}; + const item = {id, name: 'SLACK_SEND_MESSAGE', status: 'pending', task_id: null, + arguments: {text: 'fixture message'}, account: {toolkit: 'slack', account_id: 'fixture'}, prompt: ''}; const read = {...item, id: 'c'.repeat(32), name: 'GITHUB_GET_A_PULL_REQUEST', status: 'succeeded', - approval_mode: 'automatic_read', arguments: {pull_number: 17}}; + approval_mode: 'automatic_read', arguments: {pull_number: 17}, account: {...item.account, toolkit: 'github'}}; + const write = {...read, id: 'd'.repeat(32), name: 'GITHUB_CREATE_ISSUE', status: 'approved', + approval_mode: 'automatic', arguments: {title: 'fixture issue'}}; const decisions = []; const view = await mountToolApprovals(doc, async (path, options) => { if (options?.method === 'POST') { decisions.push({path, csrf: options.headers['X-CSRF-Token'], body: JSON.parse(options.body)}); return {ok: true}; } - return {ok: true, json: async () => ({items: [item, {...item, id: 'b'.repeat(32), task_id: 'legacy-1234'}, read]})}; + return {ok: true, json: async () => ({items: [item, {...item, id: 'b'.repeat(32), task_id: 'legacy-1234'}, read, write]})}; }, null); const list = section.children[2]; assert.deepEqual(list.children, []); await view.refresh(); - const [native, legacy, automatic] = list.children; - assert.match(section.children[1].textContent, /在私聊里.*只读查询.*会自动执行。/); - assert.match(section.children[1].textContent, /其他工具调用需要确认。/); - assert.equal(native.children[0].textContent, 'GITHUB_CREATE_ISSUE · 待确认'); - assert.match(native.children[2].textContent, /"title": "fixture issue"/); + const [native, legacy, automaticRead, automaticWrite] = list.children; + assert.match(section.children[1].textContent, /支持 GitHub 工具的对话.*已授权.*读取和写入.*会自动执行。/); + assert.match(section.children[1].textContent, /其他应用的工具调用需逐次确认/); + assert.equal(native.children[0].textContent, 'SLACK_SEND_MESSAGE · 待确认'); + assert.match(native.children[2].textContent, /"text": "fixture message"/); assert.match(legacy.children[0].textContent, / · 任务 legacy-1$/); - assert.equal(automatic.children[0].textContent, 'GITHUB_GET_A_PULL_REQUEST · 自动只读 · 已完成'); - assert.equal(automatic.children.some(node => node.tagName === 'button'), false); + assert.equal(automaticRead.children[0].textContent, 'GITHUB_GET_A_PULL_REQUEST · 自动只读 · 已完成'); + assert.equal(automaticWrite.children[0].textContent, 'GITHUB_CREATE_ISSUE · 自动执行 · 待执行'); + for (const automatic of [automaticRead, automaticWrite]) { + assert.equal(automatic.children.some(node => node.tagName === 'button'), false); + } assert.deepEqual(decisions, []); const approve = native.children.find(node => node.textContent === '允许此调用一次'); await approve.handlers.click[0]();