Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
316 changes: 159 additions & 157 deletions docs/inventory/visible-controls.json

Large diffs are not rendered by default.

35 changes: 35 additions & 0 deletions flybot_workspace/static/chat/activity.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,38 @@ export function mountChatActivity(document, {request, update, interval = 2000})
},
};
}

// App approvals are account-level. Read them only during a visible private reply.
export function mountChatApprovalNotice(document, {request, interval = 3000}) {
const notice = document.getElementById('chat-app-approvals');
let state;

function stop() {
const current = state;
state = null;
clearTimeout(current?.timer);
current?.controller.abort();
if (notice) notice.hidden = true;
}

async function refresh(current) {
const active = () => current === state && current.ownsView();
if (!active()) return;
const signal = AbortSignal.any([current.controller.signal, AbortSignal.timeout(4000)]);
const result = await request('GET', '/v1/composio/approvals?view=pending', undefined, undefined, signal).catch(() => null);
if (!active()) return;
notice.hidden = !(result?.status === 200 && result.body?.pending === true);
current.timer = setTimeout(() => void refresh(current), interval);
current.timer?.unref?.();
}

return {
start(ownsView) {
stop();
if (!notice) return;
state = {ownsView, controller: new AbortController()};
return refresh(state);
},
stop,
};
}
13 changes: 13 additions & 0 deletions flybot_workspace/static/chat/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -3507,6 +3507,19 @@ body.app-workspace .mobile-inbox-heading h1 {
border-radius: 50%;
background: var(--ot-accent);
}
.chat-approval-notice:not([hidden]) {
display: flex;
flex-wrap: wrap;
gap: .25rem .65rem;
max-width: var(--chat-reading-width);
margin: 0 auto .4rem;
padding: .35rem .65rem;
border-radius: .5rem;
background: var(--ot-accent-soft);
color: var(--ot-ink);
font-size: .8125rem;
line-height: 1.4;
}
.composer-row textarea { font-size: .94rem; }
.composer-plus > summary, .composer-tools button { border-radius: .55rem; }
#chat-form .composer-tools button { border-color: transparent; }
Expand Down
9 changes: 7 additions & 2 deletions flybot_workspace/static/chat/app.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { countMentionedGroupMembers, hasEveryoneMention, hasGroupAllMention, mou
import { AGENT_FILE_ACCEPT, chatFileDownload, chatUploadProgress, deferModule, localChatFile, mountChatFiles,
ownSocialReceipt, renderChatFile, sendPrivateAttachmentMessage, sendSocialAttachmentMessage, unclearSocialDelivery } from './files.mjs';
import { mountGroupTranslation } from './translation.mjs';
import { mountChatActivity } from './activity.mjs';
import { mountChatActivity, mountChatApprovalNotice } from './activity.mjs';
import { meetingCodeFromHash, meetingDraftFromCallHref, stageMeetingFromChat } from '../shell/meeting-link.mjs';
import { workNotificationSummary, workNotificationTarget } from '../shell/work-notification.mjs';
import { mountPublicDraft } from './public-draft.mjs';
Expand Down Expand Up @@ -1204,6 +1204,7 @@ export function mount(document, {fetcher = globalThis.fetch.bind(globalThis)} =
let privateThreadReceipt = 0;
const agentReplyViews = new Map();
let replyWatch = null;
const approvalNotice = mountChatApprovalNotice(document, {request});
const sendScope = (conversation = currentConversation?.id) =>
JSON.stringify([currentUser?.id, workspaceId(), currentSource, currentAgent?.id, conversation]);
const readingPositions = new Map();
Expand Down Expand Up @@ -3449,6 +3450,7 @@ export function mount(document, {fetcher = globalThis.fetch.bind(globalThis)} =
const watch = replyWatch;
if (!watch) return;
replyWatch = null;
approvalNotice.stop();
globalThis.clearTimeout(watch.timer);
globalThis.clearTimeout(watch.timeout);
globalThis.clearTimeout(watch.receiptTimer);
Expand Down Expand Up @@ -3525,6 +3527,7 @@ export function mount(document, {fetcher = globalThis.fetch.bind(globalThis)} =

async function settleReplyProgress(watch, {terminal = true} = {}) {
watch.terminal ||= terminal;
if (replyWatch === watch) approvalNotice.stop();
globalThis.clearTimeout(watch.receiptTimer);
if (watch.posting) {
if (!await acceptPostingReply(watch)) scheduleReplyProgress(watch, 1200);
Expand Down Expand Up @@ -3630,7 +3633,9 @@ export function mount(document, {fetcher = globalThis.fetch.bind(globalThis)} =
stopReplyProgress();
const path = `${agentBase()}/conversations/${currentConversation.id}/reply-progress?${new URLSearchParams({key})}`;
replyWatch = {scope, key, view, path, posting, failures: 0, revision:0};
if (!startReplyStream(replyWatch)) scheduleReplyProgress(replyWatch);
const watch = replyWatch;
if (!startReplyStream(watch)) scheduleReplyProgress(watch);
void approvalNotice.start(() => isCurrentReply(watch) && !watch.terminal);
return true;
}

Expand Down
4 changes: 4 additions & 0 deletions flybot_workspace/static/chat/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,10 @@ <h2 id="conversation-agents-heading" class="visually-hidden" data-ui-text="chat.
</details>
<form id="chat-form" method="post" action="/v1/workspaces" novalidate>
<p id="group-bot-activity" role="status" aria-atomic="true"></p>
<p id="chat-app-approvals" class="chat-approval-notice" role="status" aria-atomic="true" hidden>
<span data-ui-text="chat.approvals.pending">有应用调用待确认</span>
<a href="/settings/connectors#connected-tool-approvals" target="_blank" rel="noopener" data-ui-text="chat.approvals.review">在新标签页查看</a>
</p>
<div class="composer">
<div id="composer-file-drop" class="composer-file-drop" hidden aria-hidden="true" data-ui-text="chat.files.drop">松开鼠标,将文件添加到当前消息</div>
<div id="chat-reply-preview" class="composer-reply" hidden>
Expand Down
17 changes: 10 additions & 7 deletions flybot_workspace/static/settings/connected-tools.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s
const keyCard = document.getElementById('composio-key-card')
if (!keyCard || (globalThis.location && globalThis.location.pathname !== '/settings/connectors')) return
const section = document.createElement('section')
section.id = 'connected-tool-approvals'
section.className = 'composio-key-card'
const title = document.createElement('h2')
title.className = 'composio-key-title'
Expand All @@ -14,6 +15,7 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s
list.setAttribute('aria-live', 'polite')
section.append(title, note, list)
keyCard.after(section)
if (globalThis.location?.hash === '#connected-tool-approvals') section.scrollIntoView?.({block: 'start'})
let busy = false
let previous = ''
async function refresh() {
Expand All @@ -26,13 +28,11 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s
const pending = (payload.items || []).slice(0, 10)
const raw = JSON.stringify(pending)
if (raw === previous) return
previous = raw
list.replaceChildren()
if (!pending.length) list.textContent = '暂无待确认调用。请在私人聊天中请求智能体使用你授权的应用;群聊、定时任务和对外 API 尚未接通个人工具。'
for (const item of pending) {
const rows = pending.map(item => {
const row = document.createElement('div')
const label = document.createElement('strong')
label.textContent = item.name + ' · ' + item.status + ' · 任务 ' + item.task_id.slice(0, 8)
const task = typeof item.task_id === 'string' && item.task_id ? ' · 任务 ' + item.task_id.slice(0, 8) : ''
label.textContent = item.name + ' · ' + item.status + task
const context = document.createElement('p')
context.textContent = '请求:' + item.prompt + '\n连接:' + (item.account ? item.account.toolkit + ' / ' + item.account.account_id : '连接已移除')
const args = document.createElement('pre')
Expand Down Expand Up @@ -61,8 +61,11 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s
}
row.prepend(label, context, args)
row.append(status)
list.append(row)
}
return row
})
list.replaceChildren(...rows)
if (!rows.length) list.textContent = '暂无待确认调用。请在私人聊天中请求智能体使用你授权的应用;群聊、定时任务和对外 API 尚未接通个人工具。'
previous = raw
} catch { /* A polling failure grants nothing. */ }
finally { busy = false }
}
Expand Down
2 changes: 2 additions & 0 deletions flybot_workspace/static/shell/system-locale-chat.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,8 @@ export const CHAT_MESSAGES = Object.freeze({
"chat.memory.disabled": ["记忆 · 关闭", "Off"],
"chat.send": ["发送", "Send"],
"chat.reply.stop": ["停止生成", "Stop generating"],
"chat.approvals.pending": ["有应用调用待确认", "App calls awaiting your approval"],
"chat.approvals.review": ["在新标签页查看", "Review in a new tab"],
"chat.memory.history_help": ["从这段私聊中选择最多 12 条你发出的消息,生成待核对建议。", "Select up to 12 of your messages in this direct chat to create suggestions for review."],
"chat.search.find_messages": ["查找消息", "Find messages"],
"chat.search.by_message_body": ["按消息内容搜索", "Search message text"],
Expand Down
4 changes: 4 additions & 0 deletions runtime/flybot-image/ds-bot-bridge.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,10 @@ export async function prepareNativeChat(rt, botId, savedSessionId) {
const bot = rt.botOf(botId)
const sessionId = livePrivateChat(rt, botId, savedSessionId)
if (!sessionId) throw new Error('Mapped native chat is no longer active')
if (rt.flybotWorkspaceApps && (rt.isMain?.(botId) || bot.capabilities?.includes('ot-apps'))) {
try { await rt.flybotWorkspaceApps.sync() }
catch { rt.warn?.('FlyBot app tools could not be refreshed before this turn') }
}
const ref = await rt.applyModel(bot)
const route = splitRef(ref)
if (route) {
Expand Down
4 changes: 4 additions & 0 deletions runtime/flybot-image/native-ds-bot-overlay.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
const sourceDir = fileURLToPath(new URL('../ds-bot-upstream/ds-bot/', import.meta.url))
const patch = fileURLToPath(new URL('./native-ds-bot.patch', import.meta.url))
const files = {
'src/host/connectors/index.js': [
'1b5da94a41a8bb5f849e7f54eaab23f9da3aaa1ee27111e1c33f79f5ef9a2b24',
'aae09738660a91ebdf8a64645bc6f16174bea715989e7638c170c6cc2d080bd8',
],
'src/host/tools.js': [
'a5c743b7c75c96498775808f029a5f15c7e08dbe6eaf33089d29b3c2a9ffb382',
'852dafff886dd8625d98152afe85432b8a22648d3627df5b61eddba4cea8c510',
Expand Down
90 changes: 90 additions & 0 deletions runtime/flybot-image/native-ds-bot.patch
Original file line number Diff line number Diff line change
Expand Up @@ -2156,3 +2156,93 @@ diff --git a/src/host/prompt.js b/src/host/prompt.js
].join('\n')
}
const room = rt.roomOf(id)
diff --git a/src/host/connectors/index.js b/src/host/connectors/index.js
--- a/src/host/connectors/index.js
+++ b/src/host/connectors/index.js
@@ -3,7 +3,7 @@
// gateway (gateway.js), so every Bot gets mcp__<id>__* tools while credentials
// stay DS Bot secrets that never reach the mcp-client config. OAuth sign-in is
// in oauth.js, the service list in catalog.js, mail in mail/.
-import { randomBytes, randomUUID } from 'node:crypto'
+import { createHash, randomBytes, randomUUID } from 'node:crypto'
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import { homedir, platform } from 'node:os'
@@ -514,6 +514,25 @@

// --- request cards (request_connector) ---------------------------------

+ const appsPrefix = 'mcp__ot-apps__'
+ const publicAppTool = slug => {
+ const name = appsPrefix + slug
+ if (name.length <= 64) return name
+ // Match DSH's shortened, collision-resistant MCP name.
+ const hash = createHash('sha256').update('ot-apps\0' + slug).digest('hex').slice(0, 12)
+ return name.slice(0, 51) + '_' + hash
+ }
+ const composioFor = async (bot, agent) => {
+ const attached = bot.capabilities?.includes('ot-apps')
+ if ((!attached && !rt.isMain(bot.id)) || !rt.flybotWorkspaceApps) return new Map()
+ const rows = await rt.flybotWorkspaceApps.connectedToolkits()
+ 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.`
+ : 'connected through FlyBot (Composio); no app tools are currently mounted in this chat. Check /settings/connectors.'
+
const requestsOf = (botId) => {
const requests = (state.connectorRequests ??= {})
if (!Object.hasOwn(requests, botId) && rt.botOf(botId) === undefined) return []
@@ -539,7 +558,7 @@

rt.teamTools.push(defineTool({
name: 'list_connectors',
- description: 'List the connectors the team can use: name, what it offers, whether it is connected, and whether you may use it. Connect one for yourself with request_connector.',
+ description: 'List the connectors you can use, including connected FlyBot (Composio) apps and their available tools. Use an available tool directly, or request_connector when the service needs authorization.',
parameters: {},
output,
async execute(_args, exec) {
@@ -547,14 +566,20 @@
const self = rt.selfOf(exec.agent?.id)
const bot = rt.botOf(self)
if (!bot) return 'Only Bots on the team can use list_connectors.'
+ const apps = await composioFor(bot, exec.agent)
const rows = entries().filter(entry => entry.id !== 'mail' || mailHasAccounts())
- if (rows.length === 0) return 'No connectors are set up.'
const lines = rows.map((entry) => {
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)}`
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)}`)
+ }
+ return lines.length ? ['Connectors:', ...lines].join('\n') : 'No connectors are set up.'
},
}))

@@ -570,13 +595,17 @@
await rt.load()
const id = String(args.id ?? '').trim()
const entry = id === 'mail' ? entryOf('mail') : entryFor(id)
- if (entry === undefined) return `No connector named ${id}.`
const agentId = exec.agent?.id
const bot = rt.botOf(rt.selfOf(agentId))
if (bot === undefined) return 'Only Bots on the team can use request_connector.'
+ const apps = await composioFor(bot, exec.agent)
+ const appTools = apps.get(id)
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 (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 (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.'
if (rt.groupOwners.has(agentId)) return 'Connector cards only work in your own chat. Tell the group you will ask the user in your own chat, and call request_connector there.'
41 changes: 37 additions & 4 deletions runtime/flybot-image/test/native-open-parts.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const legacyState = () => ({
},
})

test('the image preserves managed threads, delivery and rollovers across a v0.3.9 volume upgrade', async t => {
async function nativeHost(t) {
const scratch = mkdtempSync(join(tmpdir(),'ot-host-open-parts-'))
t.after(()=>rmSync(scratch,{recursive:true,force:true,maxRetries:5}))
const staged = join(scratch,'ds-bot')
Expand All @@ -87,11 +87,44 @@ test('the image preserves managed threads, delivery and rollovers across a v0.3.
process.env.DSH_HARNESS = harness
t.after(()=>{ if (prior === undefined) delete process.env.DSH_HARNESS; else process.env.DSH_HARNESS = prior })
await load(staged,'test/harness-resolve.mjs')
const [{createRuntime},{fakeContext},threads] = await Promise.all([
load(staged,'index.js'),load(staged,'test/fake-ctx.js'),load(staged,'src/host/threads.js'),
])
const [{createRuntime},{fakeContext},threads] = await Promise.all(
['index.js','test/fake-ctx.js','src/host/threads.js'].map(file => load(staged,file)))
const home = join(scratch,'volume')
mkdirSync(home)
return {createRuntime,fakeContext,threads,home,scratch}
}

test('native connector tools use the mounted Composio connection without asking for another sign-in', async t => {
const {createRuntime,fakeContext,home} = await nativeHost(t)
const roster = legacyState()
roster.bots.writer.tasks = []
writeFileSync(join(home,'state.json'), JSON.stringify(roster))
const context = fakeContext()
context.sessionController = {resolveAgent:async id => ({agent:context.scopeAgent(id)})}
const rt = createRuntime(context,{home})
try {
await rt.load()
rt.botOf('writer').capabilities = ['ot-apps']
rt.flybotWorkspaceApps = {connectedToolkits:async () => [{slug:'github',tools:['GITHUB_LIST_REPOS','GITHUB_CREATE_ISSUE']}]}
const agent = context.scopeAgent(FOREGROUND)
agent.ctx.tools.schemas = () => [{name:'mcp__ot-apps__GITHUB_LIST_REPOS'}]
const exec = {agent,concludeTurn:() => assert.fail('Composio is already connected')}
const list = rt.teamTools.find(tool => tool.name === 'list_connectors')
const request = rt.teamTools.find(tool => tool.name === 'request_connector')
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.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)
agent.ctx.tools.schemas = () => []
assert.match(String(await request.execute(args,exec)),/no app tools are currently mounted/)
assert.equal(rt.state.connectorRequests?.writer?.length ?? 0,0)
} finally { await context.dispose() }
})

test('the image preserves managed threads, delivery and rollovers across a v0.3.9 volume upgrade', async t => {
const {createRuntime,fakeContext,threads,home,scratch} = await nativeHost(t)
const file = join(home,'state.json')
const originalRoutingId = process.env.FLYBOT_WORKSPACE_ROUTING_INSTANCE_ID
const originalInstanceId = process.env.FLYBOT_WORKSPACE_INSTANCE_ID
Expand Down
2 changes: 1 addition & 1 deletion runtime/flybot-image/test/recipe.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ test('the image overlay checks pinned inputs before adding native group and skil
const files = [
'client.js', 'src/client/at-menu.js', 'src/client/group-settings.js', 'src/client/i18n.js',
'src/client/new-chat.js', 'src/client/team-actions.js', 'src/client/text.js', 'src/host/bot-tasks.js',
'src/host/capabilities.js', 'src/host/channel.js', 'src/host/groups.js', 'src/host/parts.js',
'src/host/capabilities.js', 'src/host/channel.js', 'src/host/connectors/index.js', 'src/host/groups.js', 'src/host/parts.js',
'src/host/prompt.js', 'src/host/roster.js', 'src/host/store.js', 'src/host/threads.js',
'src/host/tools.js', 'src/shared/mentions.js',
]
Expand Down
Loading
Loading