diff --git a/runtime/flybot-image/native-ds-bot-overlay.mjs b/runtime/flybot-image/native-ds-bot-overlay.mjs index 911b9c321..173f22e3b 100644 --- a/runtime/flybot-image/native-ds-bot-overlay.mjs +++ b/runtime/flybot-image/native-ds-bot-overlay.mjs @@ -9,6 +9,18 @@ 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/tools.js': [ + 'a5c743b7c75c96498775808f029a5f15c7e08dbe6eaf33089d29b3c2a9ffb382', + '852dafff886dd8625d98152afe85432b8a22648d3627df5b61eddba4cea8c510', + ], + 'src/host/roster.js': [ + '20461d2d4aeae6ca373e3431a5802317d1130468e1940d22032189134429f984', + '31c4ec4f68067b79ef2d4fc967e254e15b5854cbc1928eed831c725030dd77aa', + ], + 'src/host/prompt.js': [ + 'b15fd1dd8b046589533540b45388e6573e84fdf51bb09aa48a97e694c1e83c21', + 'ebf5a93da2ef5941e0417f4018635350cb251212c9eb9384671f2ef9a7bbc2b8', + ], 'client.js': [ '98713d86c6cbf85adab1d0a2d303140778d9ed85fb2220abdadfab377a5f539f', '8e97d8e25cc1e04ec36f8b7449dc644e1d2d31ec5d6a8fe4071df35701806308', diff --git a/runtime/flybot-image/native-ds-bot.patch b/runtime/flybot-image/native-ds-bot.patch index b1a7fb94e..389159087 100644 --- a/runtime/flybot-image/native-ds-bot.patch +++ b/runtime/flybot-image/native-ds-bot.patch @@ -2049,3 +2049,110 @@ diff --git a/src/host/groups.js b/src/host/groups.js && (noticeOnly ? !round.starting : round.nudge !== undefined && !round.closed && !round.abort?.signal.aborted)) if (running !== undefined) { if (extra.failed !== undefined) { +diff --git a/src/host/tools.js b/src/host/tools.js +--- a/src/host/tools.js ++++ b/src/host/tools.js +@@ -477,7 +477,13 @@ + const served = new Set((await rt.catalog()).filter(entry => entry.needsKey !== true && rt.isLocalAgentRef?.(entry.ref) !== true).map(entry => entry.ref)) + const fallback = [state.prefs.defaultBotModel, creator?.model].find(ref => ref && served.has(ref)) + const model = args.model || fallback +- const bot = await rt.createBot({ ...args, avatar: avatar === undefined ? undefined : { image: avatar }, model, workDir, effort: args.effort, section: args.section, createdBy: creator?.id }) ++ const create = flybotWorkspace => rt.createBot({ ...args, avatar: avatar === undefined ? undefined : { image: avatar }, model, workDir, effort: args.effort, section: args.section, createdBy: creator?.id, flybotWorkspace }) ++ const workspace = rt.flybotWorkspaceTeam?.scope(exec.agent?.session?.id ?? exec.agent?.id) ++ if (workspace) { ++ const bot = await workspace.createBot({ name: name.slice(0, 40), role: String(args.role ?? '').trim().slice(0, 24), instructions: String(args.instructions ?? '').trim() }, create) ++ return `Created and added ${bot.name} to the user's FlyBot agent directory. Chat: ${bot.url}` ++ } ++ const bot = await create() + return `Created ${bot.name}${workDir ? `, working in ${workDir}` : ''}. It is greeting the user now.` + } catch (error) { + return `Could not create the Bot: ${error.message}` +@@ -631,9 +637,9 @@ + + rt.teamTools.push(defineTool({ + name: 'create_group', +- description: 'Main Bot only. Create a group chat with the user and some Bots. You join it as its admin unless you name another member.', ++ description: 'Main Bot only. Create a group with the user and the specified Bots. A FlyBot workspace group adds only the specified Bots. In DS Bot local groups you join as admin unless another is named.', + parameters: { +- members: { type: 'array', required: true, items: { type: 'string' }, description: 'Exact names of the other Bots to add; you are added automatically' }, ++ members: { type: 'array', required: true, items: { type: 'string' }, description: 'Exact names of the Bots to add' }, + name: { type: 'string', description: 'Group name; defaults to the member names' }, + notice: { type: 'string', description: 'Shared instructions every member reads before speaking in this group; at most 2000 characters' }, + admin: { type: 'string', description: 'Member who leads the group; defaults to you' }, +@@ -647,6 +653,15 @@ + if (!rt.isMain(self)) return 'Only a Main Bot can create group chats. Ask a Main Bot instead.' + const { bots, unknown } = resolveBots(args.members) + if (unknown.length > 0) return `No Bot named ${unknown.join(', ')}. Team: ${teamNames()}` ++ const workspace = rt.flybotWorkspaceTeam?.scope(exec.agent?.session?.id ?? exec.agent?.id) ++ if (workspace) { ++ try { ++ const group = await workspace.createGroup({ ...args, members: bots }) ++ return `Created group "${group.title}" with ${bots.map(bot => bot.name).join(', ')}. Open it in the FlyBot sidebar: ${group.url}${group.noticeSaved ? '' : ' (the notice could not be saved)'}` ++ } catch (error) { ++ return `Could not create the group: ${error.message}` ++ } ++ } + const admin = args.admin ? rt.findBot(args.admin) : rt.botOf(self) + if (admin === undefined) return `No Bot named ${args.admin}. Team: ${teamNames()}` + const members = [...new Set([self, ...bots.map(bot => bot.id), admin.id])] +@@ -1189,12 +1204,16 @@ + const filterBotAssembly = (agent, held) => { + if (held.filtered === true || typeof agent.ctx?.on !== 'function') return + const filterTools = agent.ctx.on('llm/stream', function filterBuiltinTools(options, next) { ++ // The LLM service waterfall is shared. A specialist's restrictions must ++ // never drop tools from the Chief's concurrent or following model call. ++ if (options.sessionId !== agent.session?.id) return next() + const hidden = rt.hiddenBuiltinTools(agent.session?.id) + if (!options.tools?.some(tool => hidden.has(tool.name))) return next() + return agent.ctx.llm.stream({ ...options, tools: options.tools.filter(tool => !hidden.has(tool.name)) }) + }) + if (typeof filterTools === 'function') held.disposers.push(filterTools) +- const dispose = agent.ctx.on('system-prompt/assemble', async (_assembly, _context, next) => { ++ const dispose = agent.ctx.on('system-prompt/assemble', async (_assembly, context, next) => { ++ if (context?.agent?.session?.id !== agent.session?.id) return next() + const assembled = await next() + const hidden = new Set([...HIDDEN_TOOLS, ...rt.hiddenBuiltinTools(agent.session?.id)]) + // DSH 0.2.2 adds the tool list after this waterfall (#814), so only an +diff --git a/src/host/roster.js b/src/host/roster.js +--- a/src/host/roster.js ++++ b/src/host/roster.js +@@ -190,7 +190,7 @@ + return holdName('bot', cleanName, () => buildBot(cleanName, options)) + } + +- async function buildBot(cleanName, { role = '', instructions = '', color, brief = '', createdBy, main = false, avatar, model, effort, workDir, copyOf, pickModel = false, section, sectionId }) { ++ async function buildBot(cleanName, { role = '', instructions = '', color, brief = '', createdBy, main = false, avatar, model, effort, workDir, copyOf, pickModel = false, section, sectionId, flybotWorkspace }) { + const cleanAvatarValue = cleanAvatar(avatar) + // The model is fixed at creation, so a later change of the DSH default leaves it alone. + const modelRef = model ? await rt.resolveModel(model) : pickModel ? undefined : await rt.defaultBotModel() +@@ -225,6 +225,7 @@ + createdBy: createdBy ?? null, + capabilities: [], + packs: [], ++ ...(flybotWorkspace ? { flybotWorkspace } : {}), + } + if (main) state.mainBotIds.push(id) + const creator = rt.botOf(createdBy) +diff --git a/src/host/prompt.js b/src/host/prompt.js +--- a/src/host/prompt.js ++++ b/src/host/prompt.js +@@ -51,12 +51,19 @@ + const bot = rt.botOf(self) + if (bot !== undefined) { + const main = rt.isMainForTurn?.(id) ?? rt.isMain(self) ++ const workspace = main && rt.flybotWorkspaceTeam?.scope(id) + return [ + '# Your identity', + `You are ${bot.name}, a Bot on the user's team in DS Bot.${bot.role ? ` Your role: ${bot.role}.` : ''}`, + bot.instructions ? `\n${bot.instructions}` : '', + '', + main ? `${MAIN_RULES}\n\n${TEAM_RULES}` : TEAM_RULES, ++ ...(workspace ? [ ++ '', ++ '## FlyBot personal workspace', ++ 'When the user asks you to create or assemble a team, use list_bots to reuse existing specialists, call create_bot for missing roles, and call create_group with their exact names. Use DS Bot tool discovery if these tools are not listed directly. You can do this from the current conversation.', ++ 'FlyBot shared groups include only the Bots you list. Include yourself only if the user asks. Supply the name and members, plus a notice if requested. Leave admin, reply mode, and section to group settings. After the tools confirm creation, name the actual Bots and link to the group using the returned link.', ++ ] : []), + ].join('\n') + } + const room = rt.roomOf(id) diff --git a/runtime/flybot-image/plugin/index.js b/runtime/flybot-image/plugin/index.js index 9b4d5bc46..88b88a5f8 100644 --- a/runtime/flybot-image/plugin/index.js +++ b/runtime/flybot-image/plugin/index.js @@ -90,10 +90,13 @@ export function apply(ctx, config = {}) { } if (stored.length) options.onStaged?.(stored) bridge.requireModel(botId) - return runTurn(rt, ctx, botId, text, requestId, undefined, parts, { + const turn = () => runTurn(rt, ctx, botId, text, requestId, undefined, parts, { sessionId, onProgress: options.onProgress, onPhase: options.onPhase, signal: options.signal, managedGroup: options.managedGroup, }) + return options.personalTeamScope && rt.flybotWorkspaceTeam + ? rt.flybotWorkspaceTeam.run({botId,sessionId,requestId,scope:options.personalTeamScope}, turn) + : turn() }, botId) const readNativeAttachment = async file => { const store = attachmentStore() diff --git a/runtime/flybot-image/test/container-gateway-isolation.py b/runtime/flybot-image/test/container-gateway-isolation.py index 14fd909b3..56b457be6 100644 --- a/runtime/flybot-image/test/container-gateway-isolation.py +++ b/runtime/flybot-image/test/container-gateway-isolation.py @@ -11,14 +11,16 @@ inside *their* DS-Bot (instance marker + the real FlyBot chat page); * ``POST /b/api/flybot-workspace``, ``POST /b/api/bot`` and a private workspace-agent turn execute in their own DS-Bot; +* a Personal Agent chat turn creates native Bots and one shared group, with the + same participants and room identity across the FlyBot and DS-Bot routes; * forged routing headers, a smuggled foreign DSH cookie, no session and a cross-site Origin never reach the other user's runtime; * a runtime's DSH cookie is useless against the other runtime; * no DSH cookie is ever sent to the browser. -A fixture model runs inside one runtime's loopback. No external provider, Bot -Social or published port is involved. The bridge and containers are removed -afterwards. Secrets (DSH tokens/cookies) are never printed. +A fixture model runs inside one runtime's loopback. A local Bot Social container +stores its shared group. No external provider or published port is involved. +The bridge and containers are removed afterwards. Secrets are never printed. """ from __future__ import annotations @@ -26,6 +28,7 @@ import json import os import re +import runpy import secrets import subprocess import sys @@ -41,7 +44,7 @@ sys.path.insert(0, str(ROOT)) from flybot_workspace import dsbot_gateway as gw # noqa: E402 -from flybot_workspace import lifecycle # noqa: E402 +from flybot_workspace import dsbot_bundle, lifecycle, personal # noqa: E402 from flybot_workspace.security import digest # noqa: E402 from flybot_workspace.server import QuietHandler, ThreadedWSGIServer # noqa: E402 from flybot_workspace.store import Store # noqa: E402 @@ -58,6 +61,33 @@ base_url: 'http://127.0.0.1:18799/v1', model: 'fake-model' }), { mode: 0o600 }) """ FAKE_MODEL_SERVER = r""" +const steps = [ + ['create_bot', { name: 'CI Team Builder', role: 'Dev', instructions: 'Build the fixture project.' }], + ['create_bot', { name: 'CI Team Reviewer', role: 'QA', instructions: 'Review the fixture project.' }], + ['create_group', { name: 'CI Shared Team', members: ['CI Team Builder', 'CI Team Reviewer'] }], +] + +function teamResponse(body) { + const messages = body.messages ?? [] + const request = messages.findLastIndex(message => + message.role === 'user' && JSON.stringify(message.content).includes('CI-CREATE-SHARED-TEAM')) + if (request < 0) return {} + const results = messages.slice(request + 1).filter(message => message.role === 'tool') + if (results.length >= steps.length) return { text: 'CI-TEAM-CREATED' } + const [name, args] = steps[results.length] + const available = new Set((body.tools ?? []).map(tool => tool.function?.name).filter(Boolean)) + if (available.has(name)) return { call: { name, arguments: JSON.stringify(args) }, step: results.length } + if (available.has('run_code')) { + return { call: { name: 'run_code', arguments: JSON.stringify({ + description: 'Create the fixture team', + code: `return await tools.${name}(${JSON.stringify(args)})`, + }) }, step: results.length } + } + const guidance = messages.some(message => message.role === 'system' && + JSON.stringify(message.content).includes('## FlyBot personal workspace')) + return { text: `CI-TEAM-TOOL-MISSING: ${name} (guide=${guidance}, tools=${[...available].sort().join(',')})` } +} + require('node:http').createServer((req, res) => { let raw = '' req.on('data', (c) => { raw += c }) @@ -66,18 +96,23 @@ if (req.headers.authorization !== 'Bearer ci-fake-model-key') { res.writeHead(401); res.end('{}'); return } let body = {} try { body = JSON.parse(raw) } catch {} - const text = 'CI-DSBOT-REPLY profile=' + (raw.includes('CI-PROFILE-MARK') ? 'yes' : 'no') + const team = teamResponse(body) + const text = team.text ?? 'CI-DSBOT-REPLY profile=' + (raw.includes('CI-PROFILE-MARK') ? 'yes' : 'no') + const call = team.call && { id: 'ci-team-call-' + team.step, type: 'function', function: team.call } + const finish = call ? 'tool_calls' : 'stop' const base = { id: 'chatcmpl-ci', object: 'chat.completion.chunk', created: Math.floor(Date.now() / 1000), model: 'fake-model' } + const usage = { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } if (body.stream) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' }) - res.write('data: ' + JSON.stringify({ ...base, choices: [{ index: 0, delta: { role: 'assistant', content: text }, finish_reason: null }] }) + '\n\n') - res.write('data: ' + JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } }) + '\n\n') + const delta = call ? { role: 'assistant', tool_calls: [{ index: 0, ...call }] } : { role: 'assistant', content: text } + res.write('data: ' + JSON.stringify({ ...base, choices: [{ index: 0, delta, finish_reason: null }] }) + '\n\n') + res.write('data: ' + JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: finish }], usage }) + '\n\n') res.end('data: [DONE]\n\n') return } res.writeHead(200, { 'Content-Type': 'application/json' }) - res.end(JSON.stringify({ ...base, object: 'chat.completion', choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }], - usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } })) + const message = call ? { role: 'assistant', content: null, tool_calls: [call] } : { role: 'assistant', content: text } + res.end(JSON.stringify({ ...base, object: 'chat.completion', choices: [{ index: 0, message, finish_reason: finish }], usage })) }) }).listen(18799, '127.0.0.1') """ @@ -131,11 +166,51 @@ def wait_for(fn, what, seconds=90): raise RuntimeError(f'timed out waiting for {what}: {redact(last)}') -def start_runtime(name, network, instance_id, volume_id): +def start_runtime(name, network, instance_id, volume_id, mounts=()): docker('run', '--detach', '--name', name, '--network', network, '--user', '1000:1000', '--read-only', '--tmpfs', '/tmp:rw,noexec,nosuid,size=67108864', '--mount', f'type=volume,src={name}-data,dst=/data', '-e', 'DSH_TELEMETRY_DISABLED=1', '-e', 'DSH_LISTEN_PORT=8080', - '-e', f'FLYBOT_WORKSPACE_INSTANCE_ID={volume_id}', '-e', f'FLYBOT_WORKSPACE_ROUTING_INSTANCE_ID={instance_id}', IMAGE) + '-e', f'FLYBOT_WORKSPACE_INSTANCE_ID={volume_id}', '-e', f'FLYBOT_WORKSPACE_ROUTING_INSTANCE_ID={instance_id}', + *mounts, IMAGE) + + +def start_bot_social(tmp, network, subnet, run, started): + make_tls = runpy.run_path(str(Path(__file__).with_name('container-social-two-dsbots.py')))['make_tls'] + host, app = f'ot-gw-{run}-social', f'ot-gw-{run}-social-app' + origin = f'https://{host}' + ca, key, cert = make_tls(tmp, host) + image = os.environ.get('FLYBOT_WORKSPACE_GATEWAY_BOT_SOCIAL_IMAGE') + if not image: + image = 'flybot-workspace-bot-social:ci-gateway' + docker('build', '-q', '-t', image, str(ROOT / 'services' / 'bot-social'), timeout=900) + docker('run', '--detach', '--name', app, '--network', network, '--tmpfs', '/data', + '-e', f'PUBLIC_BASE_URL={origin}', '-e', f'TRUST_PROXY={subnet}', image) + started.append(app) + conf = tmp / 'social-tls.conf' + conf.write_text(f'''server {{ + listen 443 ssl; + server_name {host}; + ssl_certificate /tls/tls.crt; + ssl_certificate_key /tls/tls.key; + location / {{ + proxy_pass http://{app}:8787; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto https; + }} +}}\n''') + os.chmod(conf, 0o644) + docker('run', '--detach', '--name', host, '--network', network, '--read-only', + '--tmpfs', '/var/cache/nginx', '--tmpfs', '/var/run', '--tmpfs', '/tmp', + '-v', f'{conf}:/etc/nginx/conf.d/default.conf:ro', '-v', f'{cert}:/tls/tls.crt:ro', + '-v', f'{key}:/tls/tls.key:ro', NGINX) + started.append(host) + config = tmp / 'bot-social.json' + config.write_text(json.dumps({'server': origin, 'displayName': 'CI Chief ' + run, 'source': 'platform'})) + os.chmod(config, 0o644) + return ['-v', f'{config}:/run/secrets/flybot-workspace-bot-social.json:ro', + '-v', f'{ca}:/run/flybot-workspace-ci-ca.pem:ro', + '-e', 'NODE_EXTRA_CA_CERTS=/run/flybot-workspace-ci-ca.pem'] def launch_url(name): @@ -155,14 +230,20 @@ def seed(store, runtimes, now): gw.ensure_schema(db) for n, rt in enumerate(runtimes): user, ws = uuid4().hex, uuid4().hex + username = f'ci-gateway-user-{n}' + db.execute('INSERT INTO users VALUES(?,?,?,?)', (user, username, 'x', now)) + if n == 0: + binding, _ = personal.ensure(db, {'id': user, 'username': username}, 2, 5, 1, now) + ws = binding['workspace_id'] + rt['personal_agent_id'] = binding['agent_id'] + rt['bootstrap'] = dsbot_bundle.build_personal_bootstrap(db, user, rt['id'], now) + else: + db.execute('INSERT INTO workspaces VALUES(?,?,?,?,?,?)', (ws, user, 'ci', now, f'k{n}', f'r{n}')) rt['workspace_id'] = ws - db.execute('INSERT INTO users VALUES(?,?,?,?)', (user, f'ci-gateway-user-{n}', 'x', now)) - db.execute('INSERT INTO workspaces VALUES(?,?,?,?,?,?)', (ws, user, 'ci', now, f'k{n}', f'r{n}')) db.execute("INSERT INTO instances(id,workspace_id,owner_id,profile,backend_mode,image_ref,volume_ref,desired,revision," "operation_id,operation_type,observed,observed_revision,health,process_ref,error_code,blocked,create_key,created) " "VALUES(?,?,?,'flybot','compose','ci',?,'running',1,'op','create','running',1,'healthy',NULL,NULL,0,?,?)", (rt['id'], ws, user, rt['name'], f'c{n}', now + n)) - gw.record_upstream(db, rt['id'], rt['address'], rt['cookie'], now) token = secrets.token_urlsafe(32) SECRETS.append(token) db.execute('INSERT INTO sessions VALUES(?,?,?,?,?)', (digest(token), digest('csrf'), user, now + 3600, now)) @@ -180,21 +261,32 @@ def main(): tmp = tempfile.TemporaryDirectory() try: docker('network', 'create', '--driver', 'bridge', '--label', 'io.flybot-workspace.ci=gateway', network) - gateway_ip = json.loads(docker('network', 'inspect', network).stdout)[0]['IPAM']['Config'][0]['Gateway'] - runtimes = [] - for index, name in enumerate(names): - rt = {'name': name, 'id': uuid4().hex} - rt['volume_id'] = uuid4().hex if index == 0 else rt['id'] - start_runtime(name, network, rt['id'], rt['volume_id']) - started.append(name) - runtimes.append(rt) + ipam = json.loads(docker('network', 'inspect', network).stdout)[0]['IPAM']['Config'][0] + gateway_ip = ipam['Gateway'] + runtimes = [{'name': name, 'id': uuid4().hex} for name in names] + a, b = runtimes + a['volume_id'], b['volume_id'] = uuid4().hex, b['id'] + os.chmod(tmp.name, 0o700) + store = Store(os.path.join(tmp.name, 'platform')) + now = int(time.time()) + token_a, token_b = seed(store, runtimes, now) + bootstrap_path = Path(tmp.name) / 'personal-bootstrap.json' + bootstrap_path.write_text(json.dumps({'agent_bootstrap': a['bootstrap']})) + os.chmod(bootstrap_path, 0o644) + social_mounts = start_bot_social(Path(tmp.name), network, ipam['Subnet'], run, started) + for rt in runtimes: + mounts = [*social_mounts, '-v', f'{bootstrap_path}:/run/secrets/flybot-workspace-runtime-key.json:ro'] if rt is a else [] + start_runtime(rt['name'], network, rt['id'], rt['volume_id'], mounts) + started.append(rt['name']) for rt in runtimes: url = launch_url(rt['name']) rt['address'] = gw.validate_address(ip_on(rt['name'], network) + ':8080') wait_for(lambda: request(rt['address'], 'GET', '/', {'Host': rt['address']})[0] in (200, 401), f'{rt["name"]} HTTP') rt['cookie'] = wait_for(lambda: gw.exchange_launch_url(url, rt['address']), f'{rt["name"]} DSH session') SECRETS.append(rt['cookie'].split('=', 1)[1]) - a, b = runtimes + with store.transaction() as db: + for rt in runtimes: + gw.record_upstream(db, rt['id'], rt['address'], rt['cookie'], int(time.time())) # A runtime's own cookie works on it, and is useless on the other runtime. ok = request(a['address'], 'POST', '/api/flybot-workspace', {'Host': a['address'], 'Cookie': a['cookie'], @@ -204,10 +296,6 @@ def main(): 'Content-Type': 'application/json'}, json.dumps({'endpoint': 'shell/identity'})) assert cross[0] == 401, f'A cookie must not open B runtime, got {cross[0]}' - os.chmod(tmp.name, 0o700) - store = Store(os.path.join(tmp.name, 'platform')) - now = int(time.time()) - token_a, token_b = seed(store, runtimes, now) key = secrets.token_urlsafe(32) SECRETS.append(key) httpd = make_server(gateway_ip, 0, lambda e, s: None, handler_class=QuietHandler, server_class=ThreadedWSGIServer) @@ -305,9 +393,7 @@ def api(token, method, path, payload=None, expected=200, timeout=20): assert status == expected, f'{method} {path}: {status} {redact(body[:300])}' return json.loads(body) - # Use the same workspace-agent routes as the real chat UI. An unseeded - # runtime has no personal binding; the Compose lifecycle test proves - # signup/manager bootstrapping separately. + # Use the same workspace-agent routes as the real chat UI. agents = f'/v1/workspaces/{a["workspace_id"]}/agents' agent = api(token_a, 'POST', agents, {'name': 'CI assistant', 'instructions': 'CI-PROFILE-MARK'}, expected=201)['agent'] @@ -326,6 +412,41 @@ def api(token, method, path, payload=None, expected=200, timeout=20): assert [m['role'] for m in history['items']] == ['user', 'assistant'] assert api(token_b, 'GET', agents)['items'] == [], "B never sees A's agents" api(token_b, 'GET', chat, expected=404) + + def plugin(token, endpoint, payload=None, kind='flybot-workspace'): + status, _h, response = browse(token, 'POST', f'/b/api/{kind}', + json.dumps({'endpoint': endpoint, 'payload': payload})) + body = json.loads(response) + assert status == 200 and body.get('ok'), f'{endpoint}: {status} {redact(body.get("error"))}' + return body['value'] + + wait_for(lambda: plugin(token_a, 'social/status').get('connected'), 'Bot Social onboarding') + chief = api(token_a, 'GET', f'{agents}/{a["personal_agent_id"]}')['agent'] + chief_conversations = f'{agents}/{chief["id"]}/conversations' + chief_conversation = api(token_a, 'POST', chief_conversations, {'title': 'CI Chief team setup'}, + expected=201)['conversation'] + chief_chat = f'{chief_conversations}/{chief_conversation["id"]}' + acted = api(token_a, 'POST', f'{chief_chat}/messages', + {'body': 'CI-CREATE-SHARED-TEAM: Create a builder, a reviewer, and their shared group.'}, + expected=201, timeout=150)['reply'] + assert acted['status'] == 'succeeded' and acted['body'] == 'CI-TEAM-CREATED', redact(acted.get('body')) + # Reload the actual pages and read the same backing API data as the UI. + assert browse(token_a, 'GET', '/agents')[0] == 200 + names_created = {'CI Team Builder', 'CI Team Reviewer'} + created = [row for row in api(token_a, 'GET', agents)['items'] if row['name'] in names_created] + assert len(created) == 2 and {row['name'] for row in created} == names_created + assert all(row['native_bot_id'] for row in created) + assert browse(token_a, 'GET', '/chat')[0] == 200 + groups = f'/v1/workspaces/{a["workspace_id"]}/social/conversations' + found = [row for row in api(token_a, 'GET', groups)['items'] if row['title'] == 'CI Shared Team'] + assert len(found) == 1 and found[0]['kind'] == 'group' and found[0]['account_group'] + group = api(token_a, 'GET', f'{groups}/{found[0]["id"]}')['conversation'] + assert group['native_room_id'] and group['native_session_id'] == group['native_room_id'] + assert {agent['id'] for agent in group['agent_members']} == {row['id'] for row in created} + native = plugin(token_a, 'flybot-workspace-group-open', {'conversation_id': group['id']}, kind='bot') + assert native['conversation_id'] == group['id'] and native['room']['id'] == group['native_room_id'] + assert set(native['room']['members']) == {row['native_bot_id'] for row in created} + assert api(token_b, 'GET', agents)['items'] == [], "B never sees the Bots created by A's Personal Agent" # An old volume can retain its native identity while using its # canonical manager-issued ID in external Agent API keys. external_key = api(token_a, 'POST', f'{agents}/{agent["id"]}/api-keys', @@ -349,7 +470,7 @@ def invocation_done(): assert result['status'] == 'succeeded' and result['engine'] == 'ds-bot' assert result['reply'].startswith('CI-DSBOT-REPLY') print(json.dumps({'gateway_isolation': 'ok', 'runtimes': 2, 'served_by': 'ds-bot', 'chat': 'ds-bot-native', - 'instances': [a['id'], b['id']]})) + 'chief_team_creation': 'ok', 'instances': [a['id'], b['id']]})) except Exception as error: for name in started: logs = docker('logs', '--tail', '80', name, check=False) diff --git a/runtime/flybot-image/test/recipe.test.js b/runtime/flybot-image/test/recipe.test.js index fd16ea832..8e9182cbb 100644 --- a/runtime/flybot-image/test/recipe.test.js +++ b/runtime/flybot-image/test/recipe.test.js @@ -130,7 +130,14 @@ test('the image overlay checks pinned inputs before adding native group and skil const copy = mkdtempSync(join(tmpdir(), 'ot-native-overlay-')) t.after(() => rmSync(copy, {recursive:true, force:true})) const upstream = join(repo, 'runtime', 'ds-bot-upstream', 'ds-bot') - for (const path of ['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/capabilities.js', 'src/host/channel.js', 'src/host/groups.js', 'src/host/bot-tasks.js', 'src/host/parts.js', 'src/host/store.js', 'src/host/threads.js', 'src/shared/mentions.js']) { + 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/prompt.js', 'src/host/roster.js', 'src/host/store.js', 'src/host/threads.js', + 'src/host/tools.js', 'src/shared/mentions.js', + ] + for (const path of files) { mkdirSync(dirname(join(copy, path)), {recursive:true}) copyFileSync(join(upstream, path), join(copy, path)) } diff --git a/runtime/flybot-workspace-web/features/agents/index.js b/runtime/flybot-workspace-web/features/agents/index.js index 60ebe88b0..f70c4e78b 100644 --- a/runtime/flybot-workspace-web/features/agents/index.js +++ b/runtime/flybot-workspace-web/features/agents/index.js @@ -1,6 +1,7 @@ import { loadPersonalAgentBootstrap } from '../../../flybot-image/agent-bootstrap.mjs' import { nativeAgents } from './native.js' import { nativeHistoryProjection } from './native-history-projection.js' +import { attachPersonalTeamCreation } from './team-creation.js' import { importPending } from '../../src/pending-import.js' // Workspace agents inside the user's own DS-Bot (batch B2; moved from // flybot_workspace/agents.py + the agent conversation dispatch in app.py). @@ -122,6 +123,13 @@ export function createAgents({ db, host }) { const one = (sql, ...a) => db.prepare(sql).get(...a) const all = (sql, ...a) => db.prepare(sql).all(...a) const run = (sql, ...a) => db.prepare(sql).run(...a) + const personalBinding = () => one('SELECT workspace_id,agent_id FROM native_personal_binding WHERE singleton=1') + function personalTeamScope(agent) { + const binding = personalBinding() + if (binding?.agent_id === agent.id && binding.workspace_id === agent.workspace_id) { + return {workspaceId:agent.workspace_id,agentId:agent.id} + } + } const ws = (p) => { if (typeof p?.workspace_id !== 'string' || !ID.test(p.workspace_id)) fail('invalid', 'workspace_id required', 400); return p.workspace_id } async function requireAgentManager(workspaceId, message = 'Only workspace owners and admins can manage archived agents') { const binding = await host.call('agents/personal-binding', {}) @@ -486,7 +494,7 @@ export function createAgents({ db, host }) { const {context, refs, personalWorkspace, remember} = await privateContext(agent, convo, text, extra) const requestId = attempt === 1 ? `ot-agent:${userId}` : `ot-agent:${userId}:retry:${attempt}` const reply = await turn({agent_id:agent.id,key:convo.id,text,request_id:requestId,reply_language:userMeta.replyLanguage,context}, - {onProgress,onPhase,signal}) + {onProgress,onPhase,signal,personalTeamScope:personalTeamScope(agent)}) if (signal?.aborted) return sentPair(userId, replyId) run('UPDATE agent_messages SET meta=? WHERE id=?', JSON.stringify({...userMeta,session_id:reply.session_id}), userId) run('UPDATE agent_messages SET text=?, status=?, meta=? WHERE id=?', reply.text, 'succeeded', @@ -586,6 +594,7 @@ export function createAgents({ db, host }) { reply_language:p.reply_language, context}, { files, onProgress,onPhase, + personalTeamScope:text ? personalTeamScope(agent) : undefined, onStaged(value) { staged = value.map((file, index) => ({ ...file, ...(files[index]?.resource ? {resource:files[index].resource} : {}), ...(stickerId ? {sticker:true} : {}), @@ -658,6 +667,24 @@ export function createAgents({ db, host }) { return {status: 201, row: load(workspaceId, id)} } + function attachTeam({rt}) { + attachPersonalTeamCreation(rt, { + host, binding:personalBinding, + publishBot: (profile, createNativeBot) => native.write(async ({ensure}) => { + const {status,row} = reserveAgent(profile, false, null) + return view(await ensure(row, async link => { + try { return await createNativeBot(link) } + catch (error) { + if (status === 201 && !Object.values(rt.state.bots).some(bot => bot.flybotWorkspace?.agent_id === row.id)) { + run('DELETE FROM agents WHERE id=?', row.id) + } + throw error + } + })) + }), + }) + } + const templateRoleConflict = (roleName) => Object.assign(new Error('Template role is unavailable'), {code: 'agents/template-role-conflict', status: 409, roleName}) @@ -667,7 +694,7 @@ export function createAgents({ db, host }) { } const endpoints = { - async 'personal-binding'() { return one('SELECT workspace_id,agent_id FROM native_personal_binding WHERE singleton=1') || null }, + async 'personal-binding'() { return personalBinding() || null }, async 'adopt-personal-chat'(p, materialize = true) { const agent = load(ws(p), p.id) const binding = one('SELECT * FROM native_personal_binding WHERE singleton=1') @@ -784,7 +811,7 @@ export function createAgents({ db, host }) { } // The reservations are durable for retry. Keep the roster lock until all // independent native Sessions finish, even if one fails. - const settled = await Promise.allSettled(reservations.map(ensure)) + const settled = await Promise.allSettled(reservations.map(row => ensure(row))) const items = settled.map((result, index) => { const {name} = roles[index] if (result.status === 'rejected') checkTemplateRoleError(result.reason, name) @@ -1513,12 +1540,12 @@ export function createAgents({ db, host }) { } const migrate = async (bundle) => (bundle?.format === 'flybot-workspace-dsbot-import' ? importOfficialBundle(endpoints, bundle) : endpoints.import(bundle)) - return { endpoints, migrate, rebrandBuiltinAssistant, attachHistory:historyProjection.attach } + return { endpoints, migrate, rebrandBuiltinAssistant, attachHistory:historyProjection.attach, attachTeam } } export default async function agents(host) { const db = await openDatabase(host, 'agents.sqlite3') - const { endpoints, migrate, rebrandBuiltinAssistant, attachHistory } = createAgents({ db, host }) + const { endpoints, migrate, rebrandBuiltinAssistant, attachHistory, attachTeam } = createAgents({ db, host }) await importPending({ host, db, migrate }) const binding = await endpoints['personal-binding']() if (!binding) { @@ -1548,8 +1575,12 @@ export default async function agents(host) { }, 10000) timer.unref?.() const runtime = host.currentRuntime?.() - if (runtime) attachHistory(runtime) - else void host.runtime().then(attachHistory, () => {}) + const attach = services => { + attachHistory(services) + attachTeam(services) + } + if (runtime) attach(runtime) + else void host.runtime().then(attach, () => {}) const wrapped = {} for (const [name, fn] of Object.entries(endpoints)) wrapped[name] = async (payload) => fn(payload ?? {}) wrapped.replyStream = async (payload, call) => { diff --git a/runtime/flybot-workspace-web/features/agents/native.js b/runtime/flybot-workspace-web/features/agents/native.js index 0115b4da8..88e19d89c 100644 --- a/runtime/flybot-workspace-web/features/agents/native.js +++ b/runtime/flybot-workspace-web/features/agents/native.js @@ -124,7 +124,7 @@ export function nativeAgents({ host, db }) { const taken = Object.values(rt.state.bots).some(b => b.name === plain && b.flybotWorkspace?.agent_id !== row.id) return taken || row.name.length > 40 ? row.name.slice(0, 29) + '-' + row.id.slice(0, 10) : plain } - async function ensure(row) { + async function ensure(row, createNativeBot) { const s = await services(), { rt } = s row = one('SELECT * FROM agents WHERE id=?', row.id) let mapping = one('SELECT * FROM native_agent_objects WHERE agent_id=?', row.id) @@ -141,15 +141,21 @@ export function nativeAgents({ host, db }) { return { ...row, archived: 1, native_bot_id: mapping.bot_id, native_deleted: true } } if (!bot) { - bot = await rt.createBot({ name: nativeName(rt, row), instructions: row.instructions, role: row.summary.slice(0, 24), pickModel: true }) - // Importing/creating an object is not permission to send a greeting. - delete bot.kickoff - const main = rt.botOf(await s.mainBot()) - bot.model = main?.model - bot.capabilities = row.inherit_capabilities === 0 ? [] : [...(main?.capabilities || [])] - bot.flybotWorkspace = { agent_id: row.id, workspace_id: row.workspace_id, summary: row.summary, category: row.category, quick_starts: JSON.parse(row.quick_starts), portrait: row.portrait } + const link = { agent_id: row.id, workspace_id: row.workspace_id, summary: row.summary, + category: row.category, quick_starts: JSON.parse(row.quick_starts), portrait: row.portrait } + if (createNativeBot) { + bot = await createNativeBot(link) + } else { + bot = await rt.createBot({ name: nativeName(rt, row), instructions: row.instructions, role: row.summary.slice(0, 24), pickModel: true }) + // Importing/creating an object is not permission to send a greeting. + delete bot.kickoff + const main = rt.botOf(await s.mainBot()) + bot.model = main?.model + bot.capabilities = row.inherit_capabilities === 0 ? [] : [...(main?.capabilities || [])] + } + bot.flybotWorkspace = { ...bot.flybotWorkspace, ...link } if (row.archived) bot.hidden = true - await rt.save() + await rt.save(createNativeBot ? {required:true} : undefined) } if (!mapping) run('INSERT OR IGNORE INTO native_agent_objects VALUES(?,?,?)', row.id, bot.id, bot.name) const lastName = mapping?.last_name || bot.name diff --git a/runtime/flybot-workspace-web/features/agents/team-creation.js b/runtime/flybot-workspace-web/features/agents/team-creation.js new file mode 100644 index 000000000..804f737bd --- /dev/null +++ b/runtime/flybot-workspace-web/features/agents/team-creation.js @@ -0,0 +1,86 @@ +import { createHash } from 'node:crypto' +import { livePrivateChat } from '../../lib/native-chat.js' +import { sharedBotSocial } from '../../lib/c/bot-social.js' + +export function attachPersonalTeamCreation(rt, { host, binding, publishBot }) { + if (rt.flybotWorkspaceTeam) return + const active = new Map() + const allowed = ({botId, workspaceId, agentId}) => { + const personal = binding() + const link = rt.botOf(botId)?.flybotWorkspace + return rt.isMain(botId) && personal?.workspace_id === workspaceId && + personal.agent_id === agentId && link?.workspace_id === workspaceId && link.agent_id === agentId + } + const key = (requestId, ...parts) => + createHash('sha256').update(JSON.stringify([requestId, ...parts])).digest('hex') + const chatUrl = (workspaceId, target) => '/chat#' + new URLSearchParams({workspace:workspaceId,...target}) + + async function includeBots(members, workspaceId) { + for (const bot of members) { + const link = bot.flybotWorkspace + if (rt.botOf(bot.id) !== bot || bot.private || bot.hidden || + (link?.agent_id && link.workspace_id !== workspaceId)) { + throw new Error(`Bot "${bot.name}" is not available in this workspace.`) + } + } + for (const bot of members) { + if (bot.flybotWorkspace?.agent_id) continue + await publishBot({workspace_id:workspaceId, name:bot.name, summary:bot.role, instructions:bot.instructions, + idempotency_key:key('existing-native-bot',bot.id)}, link => { + if (rt.botOf(bot.id) !== bot || bot.private || bot.hidden || bot.flybotWorkspace?.agent_id) { + throw new Error(`Bot "${bot.name}" changed. Check the team before trying again.`) + } + bot.flybotWorkspace = {...bot.flybotWorkspace,...link} + return bot + }) + } + } + + rt.flybotWorkspaceTeam = { + async run({botId,sessionId,requestId,scope}, runTurn) { + const turn = {...scope,botId,sessionId,requestId} + if (!allowed(turn) || livePrivateChat(rt,botId,sessionId) !== sessionId) return runTurn() + active.set(botId,turn) + try { return await runTurn() } + finally { active.delete(botId) } + }, + scope(sessionId) { + const turn = active.get(rt.chatOwners.get(sessionId)) + if (!turn || !allowed(turn) || livePrivateChat(rt,turn.botId,turn.sessionId) !== sessionId) return null + const {workspaceId,requestId} = turn + return { + async createBot({name,role,instructions}, createNativeBot) { + const agent = await publishBot({workspace_id:workspaceId, name, summary:role, instructions, + idempotency_key:key(requestId,'bot',name.toLowerCase())}, createNativeBot) + return {name:agent.name, url:chatUrl(workspaceId,{agent:agent.id})} + }, + async createGroup({name,members,admin,notice,mode,section}) { + if (!members.length || members.length > 10) throw new Error('Choose one to ten Bots by exact name.') + if (admin || mode || section) throw new Error('Create the shared group with members and a name first. Set its leader, reply mode, or section in group settings.') + const title = String(name ?? '').trim() || members.map(bot => bot.name).join(' ยท ').slice(0,80).toWellFormed() + const announcement = typeof notice === 'string' ? notice.trim() : '' + if (title.length > 80 || /[\u0000-\u001f\u007f]/.test(title) || announcement.length > 2000) { + throw new Error('The group name must be at most 80 characters and the notice at most 2000.') + } + await includeBots(members,workspaceId) + const botIds = members.map(bot => bot.id) + const social = sharedBotSocial(host) + const group = await social.createNativeGroup({workspace_id:workspaceId,title,bot_ids:botIds, + request_key:key(requestId,'group',title,...botIds.slice().sort())}) + let noticeSaved = true + if (announcement) { + const path = '/v1/ot/conversations/' + group.conversation_id + '/announcement' + try { + const current = (await social.get(path)).announcement + if (current.revision === 0) await social.post(path,{revision:0,body:announcement}) + else noticeSaved = current.body === announcement + } catch { + noticeSaved = false + } + } + return {title, noticeSaved, url:chatUrl(workspaceId,{social:group.conversation_id})} + }, + } + }, + } +} diff --git a/runtime/flybot-workspace-web/lib/c/native-groups.js b/runtime/flybot-workspace-web/lib/c/native-groups.js index 2a0c98f79..c7fced5ee 100644 --- a/runtime/flybot-workspace-web/lib/c/native-groups.js +++ b/runtime/flybot-workspace-web/lib/c/native-groups.js @@ -319,7 +319,7 @@ export function nativeGroupClient(host, raw) { pendingSave.delete(cid) }) } - const api = { sync, archive, relay } + const api = { sync, archive, relay, create: create.create } installed.set(rt, api) return api } @@ -352,5 +352,10 @@ export function nativeGroupClient(host, raw) { if (result?.kind === 'group' && result.id) return syncForPlugin(api, result) return result } - return { ...raw, request, get: (path,options) => request('GET',path,undefined,options), post: (path,b={}) => request('POST',path,b), put: (path,b={}) => request('PUT',path,b), patch: (path,b={}) => request('PATCH',path,b), del: path => request('DELETE',path) } + async function createNativeGroup(payload) { + const api = await install() + if (!api) throw new Error('The native group service is not ready') + return api.create(payload) + } + return { ...raw, request, createNativeGroup, get: (path,options) => request('GET',path,undefined,options), post: (path,b={}) => request('POST',path,b), put: (path,b={}) => request('PUT',path,b), patch: (path,b={}) => request('PATCH',path,b), del: path => request('DELETE',path) } } diff --git a/runtime/flybot-workspace-web/test/agents.test.js b/runtime/flybot-workspace-web/test/agents.test.js index 10b19511d..cdef55cc6 100644 --- a/runtime/flybot-workspace-web/test/agents.test.js +++ b/runtime/flybot-workspace-web/test/agents.test.js @@ -21,7 +21,8 @@ function fixture(options) { } } const db = new DatabaseSync(join(mkdtempSync(join(tmpdir(), 'ot-agents-')), 'a.sqlite3')) const created = createAgents({ db, host }) - return { e: created.endpoints, migrate: created.migrate, rebrandBuiltinAssistant: created.rebrandBuiltinAssistant, db, ...runtime } + return { e: created.endpoints, migrate: created.migrate, rebrandBuiltinAssistant: created.rebrandBuiltinAssistant, + attachTeam:created.attachTeam, db, ...runtime } } test('categories stay in step with the Python source', () => { @@ -230,6 +231,53 @@ test('existing Personal Agent binds Chief without replacing native IDs, private assert.equal((await e.messages(scope)).items.length,4) }) +test('a Personal Agent chat can publish its actual native Bot id once', async () => { + const {e, db, services, attachTeam, bots} = fixture() + const {rt} = services + rt.isMain = id => id === 'main' + rt.pastOwners = new Map() + const {agent:personal} = await e.create({workspace_id:W,name:'Personal Agent',idempotency_key:'native-team-personal'}) + db.prepare('INSERT INTO native_personal_binding VALUES(1,?,?)').run(W,personal.id) + const address = {workspace_id:W,id:personal.id} + const owner = (await e.get(address)).agent + assert.equal(owner.native_bot_id,'main') + const {conversation} = await e['conversation-create'](address) + const direct = services.nativeTurn.bind(services) + attachTeam(services) + let builds = 0 + let managedSession + services.nativeTurn = async (botId,sessionId,text,requestId,options) => { + const out = () => direct(botId,sessionId,text,requestId) + if (!options?.personalTeamScope) { + assert.equal(rt.flybotWorkspaceTeam.scope(sessionId),null) + return out() + } + managedSession = sessionId + return rt.flybotWorkspaceTeam.run({botId,sessionId,requestId,scope:options.personalTeamScope},async () => { + const tools = rt.flybotWorkspaceTeam.scope(sessionId) + assert.ok(tools) + const profile = {name:'Test Engineer',role:'QA',instructions:'Review the release.'} + const build = link => { + builds++ + return rt.createBot({...profile,model:'flybot/default',flybotWorkspace:link}) + } + const first = await tools.createBot(profile,build) + assert.deepEqual(await tools.createBot(profile,build),first) + assert.match(first.url,/agent=[a-f0-9]{32}$/) + return out() + }) + } + await e.send({...address,conversation_id:conversation.id,text:'Create a test engineer',idempotency_key:'native-team-direct-send'}) + assert.equal(rt.flybotWorkspaceTeam.scope(managedSession),null) + await e.turn({agent_id:personal.id,key:conversation.id,text:'External call'}) + const roster = (await e.list({workspace_id:W})).items.filter(row => row.name === 'Test Engineer') + assert.equal(roster.length,1) + const bot = bots[roster[0].native_bot_id] + assert.equal(bot.model,'flybot/default') + assert.equal(bot.flybotWorkspace.agent_id,roster[0].id) + assert.equal(builds,1) +}) + test('without the DS-Bot chat service a send fails closed and is recorded', async () => { const { e, turns } = fixture({ available: false }) const { agent } = await e.create({ workspace_id: W, name: 'A', idempotency_key: 'b'.repeat(16) })