Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Import agents from OpenBot and Grok Bot (#91)
Eduardo Machado8b7c069ab8e6
diff --git a/docs/spec-mvp.md b/docs/spec-mvp.mdindex 45f6bd9..6134db1 100644--- a/docs/spec-mvp.md+++ b/docs/spec-mvp.md@@ -337,6 +337,19 @@ Quem abre o app pela primeira vez sai dele com um agente trabalhando, não com u- **Primeiros passos:** uma lista na barra lateral com nove recursos (time, conector, memória, rotina, projeto, aprovação, celular…). Cada item se marca sozinho pelo estado do app, e o próximo leva à tela certa. Ela some com "Esconder a lista".- Em Configurações: **Rever a introdução** e **Mostrar os primeiros passos**. Uma instalação que já existia não vê nada disso até pedir.+### 26. Importar de outro app++Quem chega de outro app de agentes traz o time em vez de montar de novo, sem que um arquivo de fora ganhe acesso a nada.++- **Onde:** Configurações → Time e backup → **Importar de outro app…**, que lê um `.zip`.+- **OpenBot:** a exportação dele (Server settings → Transfer → Export from this server, `openbot-transfer.json`, formato `openbot-instance-transfer` v1). Só o formato documentado é lido; nenhum código do OpenBot (PolyForm Noncommercial) entra no Tucano.+- **Apps sem exportação (Grok Bot):** o botão **Skill pro Grok Bot (experimental)** baixa uma skill nossa; um agente de lá a segue e escreve um `.zip` no formato do Tucano (`tucano-import.json`, `tucano-agent-import` v1). Experimental até alguém testar dentro do Grok Bot.+- **O que vem:** nome, papel, instruções, foto, cor, esforço, skills (só o `SKILL.md`), rotinas, memórias e, no Grok Bot, os grupos. O modelo vem quando o CLI dele está pronto aqui; senão, o agente recebe um modelo que roda, com aviso.+- **Governança:** os agentes chegam **sem nenhum conector, com a busca na web desligada e sem computador**; as rotinas chegam desligadas; as memórias esperam confirmação. Os servidores MCP do outro app só aparecem pelo nome no resumo, nunca viram conectores (um arquivo poderia mandar rodar qualquer comando). Um agente importado **nunca entra num canal que já existe**: o grupo vira um canal novo (`#nome-2` se o nome estiver ocupado), e nele entram **só os agentes criados nesta importação**. Um agente que já estava aqui (mesmo que pareça igual, como uma cópia do Tuca) nunca é posto pelo arquivo numa sala com um estranho; o resumo diz quem ficou de fora.+- **Limites por arquivo:** 40 agentes, 30 canais e, por agente, 20 skills, 20 rotinas e 40 memórias de até 300 caracteres. O que passa disso, ou não dá pra ler, fica de fora sozinho (uma skill ruim não derruba o agente) e aparece no resumo, que mostra até 40 linhas.+- **Importar de novo** não duplica: o mesmo agente (nome, papel e instruções), a mesma skill e o mesmo canal (nome e agentes) ficam como estão.+- **O zip** é lido em partes, só com o `zlib` do Node: caminhos com `..` ou fora da pasta do agente são ignorados, entradas criptografadas são ignoradas, ZIP64 é recusado, e cada entrada tem um teto de tamanho conferido depois de descompactar.+## Acceptance criteria1. **Chat básico:** crio um agente no Claude Code, abro DM, mando uma mensagem e vejo a resposta em streaming, com rodapé de modelo/tokens/duração. O mesmo funciona com um agente no Codex.diff --git a/src/core/agent-import.ts b/src/core/agent-import.tsnew file mode 100644index 0000000..85c4194--- /dev/null+++ b/src/core/agent-import.ts@@ -0,0 +1,550 @@+// Agents from another app (spec §26). Each source becomes one `ForeignTeam`, and `applyForeignTeam`+// adds it the same way for all: the agents come in with no connector granted, web search off, their+// routines off and their memories waiting for the person to confirm. Nothing that can run comes in by+// itself: an MCP server of the other app is named in the summary, never added as a connector. A file+// never puts an agent in a channel that's already here: its group chats become channels of their own.+//+// OpenBot: the .zip of Server settings → Transfer → Export from this server (`openbot-transfer.json`,+// format "openbot-instance-transfer", version 1). Only its documented format is read here; none of+// OpenBot's code is used.+//+// Apps with no export of their own (Grok Bot): the person gives one of their agents there our skill+// (assets/tucano-export-skill.md), and it writes a .zip in Tucano's own format (`tucano-import.json`,+// format "tucano-agent-import", version 1), read by `readTucanoImport`.+import { randomUUID } from 'node:crypto'+import { L } from '../shared/lang'+import { channelName, codexValue, customModel, MAX_AGENT_ROUTINES, type Agent, type Effort, type EngineId, type Memory, type Routine, type Schedule } from '../shared/types'+import { cleanLook } from './agent-look'+import type { Db } from './db'+import { frontmatter } from './local-skills'+import { skillName } from './skills'+import type { Zip } from './zip'++export interface ForeignSkill {+ name: string+ description: string+ body: string+ extraFiles: number // files beside SKILL.md, which stay out+}++export interface ForeignAgent {+ key: string // the agent's id inside the file, which channels name+ name: string+ role: string+ instructions: string+ modelId?: string // undefined: this app's default+ effort: Effort+ customColor?: string+ picture?: string+ skills: ForeignSkill[]+ routines: { name: string; prompt: string; schedule: Schedule }[]+ memories: string[]+ notes: string[] // what of this agent stayed out, and why+}++export interface ForeignTeam {+ source: string // "OpenBot", "Grok Bot"+ agents: ForeignAgent[]+ channels: { name: string; topic?: string; members: string[] }[] // members by agent key+ servers: string[] // MCP servers there, by name, to add by hand+ notes: string[]+}++const MAX_MANIFEST = 20_000_000+const MAX_TEXT = 1_000_000+const MAX_INSTRUCTIONS = 32_000+const MAX_PICTURE_BYTES = 145_000 // as a data URL it stays under cleanLook's cap+const MAX_MEMORY = 300+const MAX_SKILL_BODY = 20_000+// What one file brings at most; the rest is counted in the summary.+export const IMPORT_CAPS = { agents: 40, channels: 30, skills: 20, routines: 20, memories: 40 }+const SUMMARY_LINES = 40++const str = (v: unknown, max = 10_000): string => (typeof v === 'string' ? v.trim().slice(0, max) : '')+const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : [])+const obj = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {})+const time = (v: unknown): string | undefined => (typeof v === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(v) ? v : undefined)+const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6]++// The first `cap` items of a list; the summary says how many stayed out.+function capped(v: unknown, cap: number, what: (n: number) => string, notes: string[]): unknown[] {+ const list = arr(v)+ if (list.length > cap) notes.push(what(list.length - cap))+ return list.slice(0, cap)+}+// A part that can't be read (too big, broken) stays out alone, not with the whole agent.+function attempt<T>(read: () => T, fallback: T, note: string, notes: string[]): T {+ try {+ return read()+ } catch {+ notes.push(note)+ return fallback+ }+}++// A path the manifest names must be inside the agent's own folder, without "..".+const inside = (path: unknown, prefix: string): string | undefined =>+ typeof path === 'string' && path.startsWith(prefix) && !path.split('/').some((p) => p === '..' || p === '') ? path : undefined+const KEY = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/ // OpenBot's agent keys+const OUR_KEY = /^[a-z][a-z0-9-]{0,39}$/ // tucano-import.json's++// The picture, as a data URL, when it's a kind and a size this app shows.+function readPicture(zip: Zip, path: unknown, prefix: string, notes: string[]): string | undefined {+ const avatar = inside(path, prefix)+ if (!avatar) return undefined+ const type = ({ png: 'png', jpg: 'jpeg', jpeg: 'jpeg', webp: 'webp' } as Record<string, string>)[avatar.split('.').pop()!.toLowerCase()]+ if (!type) {+ notes.push(L('a foto (formato que o Tucano não mostra)', "the picture (a format Tucano doesn't show)"))+ return undefined+ }+ const entry = zip.entries.get(avatar)+ if (!entry) return undefined+ if (entry.size > MAX_PICTURE_BYTES) {+ notes.push(L('a foto (grande demais)', 'the picture (too big)'))+ return undefined+ }+ const bytes = attempt(() => zip.read(avatar, MAX_PICTURE_BYTES), undefined, L('a foto (não deu pra ler)', "the picture (it couldn't be read)"), notes)+ return bytes && `data:image/${type};base64,${bytes.toString('base64')}`+}++// Each skill is a folder with a SKILL.md; only the recipe comes, the files beside it are counted.+function readSkills(zip: Zip, paths: unknown, prefix: string, notes: string[]): ForeignSkill[] {+ const list = capped(paths, IMPORT_CAPS.skills, (n) => L(`${n} skill${n > 1 ? 's' : ''} além de ${IMPORT_CAPS.skills}`, `${n} skill${n > 1 ? 's' : ''} beyond ${IMPORT_CAPS.skills}`), notes)+ return list.flatMap((path) => {+ const folder = inside(path, `${prefix}skills/`)+ const where = folder?.split('/').pop() ?? ''+ const text = folder && attempt(() => zip.read(`${folder}/SKILL.md`, MAX_TEXT)?.toString('utf8'), undefined, L(`a skill ${where} (não deu pra ler)`, `the ${where} skill (it couldn't be read)`), notes)+ if (!folder || !text) return []+ const fm = frontmatter(text)+ const nm = skillName(fm.name || folder.split('/').pop()!)+ const body = fm.body.trim()+ if (!nm || !body) return []+ if (body.length > MAX_SKILL_BODY) {+ notes.push(L(`a skill ${nm} (receita longa demais)`, `the ${nm} skill (recipe too long)`))+ return []+ }+ const extraFiles = [...zip.entries.keys()].filter((f) => f.startsWith(`${folder}/`) && f !== `${folder}/SKILL.md`).length+ return [{ name: nm, description: str(fm.description, 1_000) || nm, body, extraFiles }]+ })+}++const memoriesOf = (v: unknown, notes: string[]): string[] =>+ capped(v, IMPORT_CAPS.memories, (n) => L(`${n} memória${n > 1 ? 's' : ''} além de ${IMPORT_CAPS.memories}`, `${n} memor${n > 1 ? 'ies' : 'y'} beyond ${IMPORT_CAPS.memories}`), notes).flatMap(+ (item) => str(typeof item === 'string' ? item : obj(item)['text'], MAX_MEMORY) || []+ )+const routinesOver = (n: number): string => L(`${n} rotina${n > 1 ? 's' : ''} além de ${IMPORT_CAPS.routines}`, `${n} routine${n > 1 ? 's' : ''} beyond ${IMPORT_CAPS.routines}`)+const agentsOver = (n: number): string => L(`${n} agente${n > 1 ? 's' : ''} além de ${IMPORT_CAPS.agents} (importe de novo com menos)`, `${n} agent${n > 1 ? 's' : ''} beyond ${IMPORT_CAPS.agents} (import again with fewer)`)+const channelsOver = (n: number): string => L(`${n} ${n > 1 ? 'canais' : 'canal'} além de ${IMPORT_CAPS.channels}`, `${n} channel${n > 1 ? 's' : ''} beyond ${IMPORT_CAPS.channels}`)++// A routine's own time zone isn't this computer's: the time stays the same, and the summary says so.+function zoneNote(tz: string, name: string, notes: string[]): void {+ if (tz && tz !== Intl.DateTimeFormat().resolvedOptions().timeZone)+ notes.push(L(`o fuso da rotina "${name}" (${tz}): o horário ficou como estava, no fuso deste computador`, `the time zone of the routine "${name}" (${tz}): the time stayed as it was, in this computer's zone`))+}++// ---------- OpenBot ----------++export const isOpenBotTransfer = (zip: Zip): boolean => zip.entries.has('openbot-transfer.json')++export function readOpenBot(zip: Zip): ForeignTeam {+ const raw = zip.read('openbot-transfer.json', MAX_MANIFEST)+ if (!raw) throw new Error(L('Esse .zip não é uma exportação do OpenBot.', "That .zip isn't an OpenBot export."))+ let m: Record<string, unknown>+ try {+ m = obj(JSON.parse(raw.toString('utf8')))+ } catch {+ throw new Error(L('O arquivo de exportação do OpenBot está corrompido.', "The OpenBot export file is corrupted."))+ }+ if (m['format'] !== 'openbot-instance-transfer') throw new Error(L('Esse .zip não é uma exportação do OpenBot.', "That .zip isn't an OpenBot export."))+ if (m['version'] !== 1) throw new Error(L('Essa exportação vem de uma versão do OpenBot que o Tucano ainda não lê.', "That export comes from an OpenBot version Tucano doesn't read yet."))++ const notes: string[] = []+ const agents = capped(m['agents'], IMPORT_CAPS.agents, agentsOver, notes).flatMap((item, i) => {+ try {+ const a = openBotAgent(zip, obj(item))+ return a ? [a] : []+ } catch {+ notes.push(L(`o agente nº ${i + 1}, que não deu pra ler`, `agent #${i + 1}, which couldn't be read`))+ return []+ }+ })+ const settings = obj(m['settings'])+ const servers = arr(settings['mcpServers']).flatMap((s) => str(obj(s)['name'], 128) || [])+ if (arr(settings['customProviders']).length) notes.push(L('os provedores de modelo próprios', 'the custom model providers'))+ if (arr(settings['routineFlows']).length) notes.push(L('os fluxos entre rotinas', 'the routine flows'))+ if (m['shared']) notes.push(L('a pasta Shared', 'the Shared folder'))+ return { source: 'OpenBot', agents, servers, notes, channels: [] }+}++function openBotAgent(zip: Zip, a: Record<string, unknown>): ForeignAgent | undefined {+ const key = str(a['key'], 128)+ const name = str(a['name'], 80)+ if (!key || !KEY.test(key) || !name) return undefined+ const prefix = `agents/${key}/`+ const notes: string[] = []++ // The standing rules live in the workspace's AGENTS.md (or CLAUDE.md), only there when the export took the files.+ const files = inside(a['files'], prefix)+ const fromFile = files+ ? attempt(() => ['AGENTS.md', 'CLAUDE.md'].map((f) => zip.read(`${files}/${f}`, MAX_TEXT)).find(Boolean)?.toString('utf8').trim() ?? '', '', L('o AGENTS.md (não deu pra ler)', "AGENTS.md (it couldn't be read)"), notes)+ : ''+ const description = str(a['description'], 2_000)+ const instructions = (fromFile || description).slice(0, MAX_INSTRUCTIONS)+ if (!fromFile) notes.push(description ? L('as instruções (só veio a descrição: exporte com os arquivos)', 'the instructions (only the description came: export with the files)') : L('as instruções (exporte com os arquivos)', 'the instructions (export with the files)'))+ if (files) notes.push(L('os outros arquivos do workspace', 'the other workspace files'))++ const { modelId, note } = openBotModel(str(a['provider'], 32), str(a['model'], 256))+ if (note) notes.push(note)++ const picture = readPicture(zip, a['avatar'], prefix, notes)+ const skills = readSkills(zip, a['skills'], prefix, notes)++ const routines = capped([...arr(a['routines']), ...arr(a['oneTimeRoutines'])], IMPORT_CAPS.routines, routinesOver, notes).flatMap((item) => {+ const r = obj(item)+ const rname = str(r['name'], 120)+ const prompt = str(r['instruction'], 20_000)+ if (!rname || !prompt) return []+ const schedule = openBotSchedule(obj(r['schedule']))+ if (!schedule) {+ notes.push(L(`a rotina "${rname}" (horário sem equivalente aqui)`, `the routine "${rname}" (a schedule with no match here)`))+ return []+ }+ zoneNote(str(r['timezone'], 64), rname, notes)+ return [{ name: rname, prompt, schedule }]+ })++ const memories = memoriesOf(a['memories'], notes)++ const hue = a['avatarHue']+ return {+ key,+ name,+ role: str(a['title'], 80),+ instructions,+ modelId,+ effort: openBotEffort(a['reasoningEffort']),+ customColor: typeof hue === 'number' && hue >= 0 && hue < 360 ? hueColor(hue) : undefined,+ picture,+ skills,+ routines,+ memories,+ notes+ }+}++// The same CLI keeps the model; a provider Tucano doesn't run leaves the agent on the default.+function openBotModel(provider: string, model: string): { modelId?: string; note?: string } {+ const engines: Record<string, EngineId> = { claude: 'claude', codex: 'codex', opencode: 'opencode', pi: 'pi', gemini: 'gemini', cursor: 'cursor' }+ const engine = engines[provider]+ if (engine === 'claude') return { modelId: /opus/i.test(model) ? 'opus' : /haiku/i.test(model) ? 'haiku' : 'sonnet' }+ if (engine === 'codex') return model ? { modelId: codexValue(model) } : {}+ if (engine) return model ? { modelId: customModel(engine, model) } : {}+ return { note: L(`o modelo ${model || provider} (${provider} não roda no Tucano: ficou o modelo padrão)`, `the ${model || provider} model (${provider} doesn't run on Tucano: it got the default model)`) }+}++function openBotEffort(v: unknown): Effort {+ if (v === 'medium') return 'medium'+ if (v === 'high') return 'high'+ if (v === 'xhigh' || v === 'max' || v === 'ultra') return 'xhigh'+ return v === 'none' || v === 'minimal' || v === 'low' ? 'low' : 'medium'+}++// Tucano runs a routine at a time on some weekdays; the rest (hourly, monthly, intervals, cron) has no match.+export function openBotSchedule(s: Record<string, unknown>): Schedule | undefined {+ const t = time(s['time'])+ switch (s['kind']) {+ case 'daily':+ return t ? { days: ALL_DAYS, time: t } : undefined+ case 'weekdays':+ return t ? { days: [1, 2, 3, 4, 5], time: t } : undefined+ case 'weekly': {+ const d = s['weekday']+ return t && typeof d === 'number' && Number.isInteger(d) && d >= 0 && d <= 6 ? { days: [d], time: t } : undefined+ }+ case 'once': {+ // Tucano's "once" runs at the next matching weekday: right only within the coming week.+ const date = typeof s['date'] === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s['date']) ? new Date(`${s['date']}T${t ?? '00:00'}:00`) : undefined+ const ahead = date ? date.getTime() - Date.now() : -1+ return t && date && ahead > 0 && ahead < 7 * 86_400_000 ? { days: [date.getDay()], time: t, once: true } : undefined+ }+ case 'advanced': {+ const months = arr(s['months'])+ const days = obj(s['days'])+ const at = obj(s['time'])+ const tt = at['kind'] === 'at-time' ? time(at['time']) : undefined+ if (months.length !== 12 || !tt) return undefined+ if (days['kind'] === 'every-day') return { days: ALL_DAYS, time: tt }+ const list = arr(days['days']).filter((d): d is number => typeof d === 'number' && Number.isInteger(d) && d >= 0 && d <= 6)+ return days['kind'] === 'days-of-week' && list.length ? { days: [...new Set(list)].sort(), time: tt } : undefined+ }+ default:+ return undefined+ }+}++// OpenBot keeps a hue (0, 30… 320); here a color is #rrggbb.+export function hueColor(h: number): string {+ const s = 0.6+ const l = 0.52+ const k = (n: number): number => (n + h / 30) % 12+ const f = (n: number): number => l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))+ return '#' + [f(0), f(8), f(4)].map((x) => Math.round(x * 255).toString(16).padStart(2, '0')).join('')+}++// ---------- Tucano's own format (Grok Bot, and any app with no export) ----------++export const TUCANO_IMPORT = 'tucano-import.json'+const SOURCES: Record<string, string> = { 'grok-bot': 'Grok Bot' }+const DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']++export function readTucanoImport(zip: Zip): ForeignTeam {+ const raw = zip.read(TUCANO_IMPORT, MAX_MANIFEST)+ if (!raw) throw new Error(L('Esse .zip não é uma exportação pro Tucano.', "That .zip isn't an export for Tucano."))+ let m: Record<string, unknown>+ try {+ m = obj(JSON.parse(raw.toString('utf8')))+ } catch {+ throw new Error(L('O arquivo tucano-import.json está corrompido.', 'The tucano-import.json file is corrupted.'))+ }+ if (m['format'] !== 'tucano-agent-import') throw new Error(L('Esse .zip não é uma exportação pro Tucano.', "That .zip isn't an export for Tucano."))+ if (m['version'] !== 1) throw new Error(L('Essa exportação é de uma versão mais nova do formato. Atualize o Tucano.', 'That export is from a newer version of the format. Update Tucano.'))+ const app = str(m['source'], 40)+ const source = SOURCES[app] ?? (app || L('outro app', 'another app'))++ const notes: string[] = []+ const keys = new Set<string>()+ const agents = capped(m['agents'], IMPORT_CAPS.agents, agentsOver, notes).flatMap((item, i) => {+ try {+ const a = tucanoAgent(zip, obj(item), source)+ if (!a || keys.has(a.key)) {+ notes.push(L(`o agente nº ${i + 1} (sem nome, ou com a chave inválida ou repetida)`, `agent #${i + 1} (no name, or a key that's invalid or repeated)`))+ return []+ }+ keys.add(a.key)+ return [a]+ } catch {+ notes.push(L(`o agente nº ${i + 1}, que não deu pra ler`, `agent #${i + 1}, which couldn't be read`))+ return []+ }+ })+ const channels = capped(m['channels'], IMPORT_CAPS.channels, channelsOver, notes).flatMap((item) => {+ const c = obj(item)+ const name = channelName(str(c['name'], 80))+ if (!name) return []+ const members = arr(c['members']).filter((k): k is string => typeof k === 'string' && keys.has(k))+ if (arr(c['routines']).length) notes.push(L(`as rotinas do canal #${name} (crie de novo no canal)`, `the routines of #${name} (make them again in the channel)`))+ return [{ name, topic: str(c['topic'], 200) || undefined, members: [...new Set(members)] }]+ })+ return { source, agents, servers: [], notes, channels }+}++function tucanoAgent(zip: Zip, a: Record<string, unknown>, source: string): ForeignAgent | undefined {+ const key = str(a['key'], 40)+ const name = str(a['name'], 80)+ if (!OUR_KEY.test(key) || !name) return undefined+ const prefix = `agents/${key}/`+ const notes: string[] = []+ const instructions = str(a['instructions'], MAX_INSTRUCTIONS)+ if (!instructions) notes.push(L('as instruções (não vieram no arquivo)', "the instructions (they weren't in the file)"))+ notes.push(L(`o modelo do ${source} (ficou o modelo padrão)`, `the ${source} model (it got the default model)`))++ const routines = capped(a['routines'], IMPORT_CAPS.routines, routinesOver, notes).flatMap((item) => {+ const r = obj(item)+ const rname = str(r['name'], 120)+ const prompt = str(r['prompt'], 20_000)+ if (!rname || !prompt) return []+ const schedule = tucanoSchedule(r)+ if (!schedule) {+ notes.push(L(`a rotina "${rname}" (horário sem equivalente aqui)`, `the routine "${rname}" (a schedule with no match here)`))+ return []+ }+ zoneNote(str(r['timezone'], 64), rname, notes)+ return [{ name: rname, prompt, schedule }]+ })++ return {+ key,+ name,+ role: str(a['role'], 80),+ instructions,+ effort: 'medium',+ picture: readPicture(zip, a['picture'], prefix, notes),+ skills: readSkills(zip, a['skills'], prefix, notes),+ routines,+ memories: memoriesOf(a['memories'], notes),+ notes+ }+}++// { days: ["mon", "wed"], time: "08:30", once?: true }: what a routine here already is, with day names.+export function tucanoSchedule(r: Record<string, unknown>): Schedule | undefined {+ const t = time(r['time'])+ const days = arr(r['days']).map((d) => (typeof d === 'string' ? DAYS.indexOf(d.toLowerCase().slice(0, 3)) : -1))+ if (!t || !days.length || days.some((d) => d < 0)) return undefined+ return { days: [...new Set(days)].sort(), time: t, ...(r['once'] === true ? { once: true } : {}) }+}++// ---------- adding it here ----------++// A @handle from a name: "Lúcia M." → "luciam", with a number when it's taken.+const handleFor = (name: string, taken: Set<string>): string => {+ const base =+ name+ .normalize('NFD')+ .replace(/[̀-ͯ]/g, '')+ .toLowerCase()+ .replace(/[^a-z0-9_-]/g, '')+ .slice(0, 28) || 'agente'+ let h = base+ for (let i = 2; taken.has(h) || h === 'tuca'; i++) h = `${base}${i}`+ return h+}++export interface ImportResult {+ summary: string+ agents: string[] // ids added+ memories: Memory[]+}++// `works`: whether a model runs here now (its harness chosen and signed in); `defaultModel` is one that does.+export function applyForeignTeam(db: Db, team: ForeignTeam, opts: { defaultLimit: number; defaultModel: string; works?: (modelId: string) => boolean }): ImportResult {+ const added = { agents: [] as string[], skills: 0, routines: 0, memories: [] as Memory[], same: [] as string[] }+ const left: string[] = [...team.notes]+ const skillsBefore = new Set(db.skills().filter((k) => k.state === 'active').map((k) => k.name))+ const createdSkills = new Map<string, string>() // name → id, made by this import+ const byKey = new Map<string, string>() // the file's agent key → the agent here++ for (const f of team.agents) {+ const existing = db.agents().filter((x) => !x.archived)+ // The same agent imported before: same name, role and instructions.+ const before = existing.find((x) => x.name === f.name && x.role === f.role && x.instructions === f.instructions)+ if (before) {+ added.same.push(f.name)+ byKey.set(f.key, before.id)+ continue+ }+ const handle = handleFor(f.name, new Set(db.agents().map((x) => x.handle)))+ // The other app's model when it runs here; else one that does.+ const ready = f.modelId && (!opts.works || opts.works(f.modelId))+ if (f.modelId && !ready) left.push(L(`@${handle}: o modelo ${f.modelId} (o CLI dele não está pronto aqui: ficou ${opts.defaultModel})`, `@${handle}: the ${f.modelId} model (its CLI isn't ready here: it got ${opts.defaultModel})`))+ const agent: Agent = cleanLook({+ id: randomUUID(),+ name: f.name,+ handle,+ role: f.role,+ color: 'sky',+ customColor: f.customColor,+ picture: f.picture,+ instructions: f.instructions,+ modelId: ready ? f.modelId! : opts.defaultModel,+ effort: f.effort,+ maxRoutines: MAX_AGENT_ROUTINES,+ limit: opts.defaultLimit,+ used: 0,+ grants: {}, // the other app's access doesn't come: each connector is given here, by hand+ memory: 'auto',+ // Instructions written somewhere else: no way out to the internet until the person turns it on.+ web: false,+ computer: false,+ archived: false+ })+ db.saveAgent(agent)+ added.agents.push(agent.id)+ byKey.set(f.key, agent.id)+ for (const n of f.notes) left.push(`@${handle}: ${n}`)++ for (const k of f.skills) {+ if (k.extraFiles) left.push(L(`@${handle}: ${k.extraFiles} arquivo${k.extraFiles > 1 ? 's' : ''} da skill ${k.name} além do SKILL.md`, `@${handle}: ${k.extraFiles} file${k.extraFiles > 1 ? 's' : ''} of the ${k.name} skill besides SKILL.md`))+ const mine = createdSkills.get(k.name)+ const same = mine ? db.skill(mine) : undefined+ if (same && same.body === k.body) {+ db.saveSkill({ ...same, agents: [...new Set([...same.agents, agent.id])], updatedAt: Date.now() })+ continue+ }+ let nm = k.name+ if (skillsBefore.has(nm) || createdSkills.has(nm)) nm = skillName(`${k.name}-${handle}`)+ if (skillsBefore.has(nm) || createdSkills.has(nm)) {+ left.push(L(`@${handle}: a skill ${k.name} (já existe uma com esse nome)`, `@${handle}: the ${k.name} skill (one with that name already exists)`))+ continue+ }+ const at = Date.now()+ const id = randomUUID()+ db.saveSkill({ id, name: nm, description: k.description, body: k.body, agents: [agent.id], state: 'active', createdAt: at, updatedAt: at })+ createdSkills.set(nm, id)+ added.skills+++ }++ if (f.routines.length) {+ let dm = db.conversations().find((c) => c.kind === 'dm' && c.name === agent.id)?.id+ if (!dm) {+ dm = randomUUID()+ db.createConversation({ id: dm, kind: 'dm', name: agent.id, members: [agent.id] })+ }+ for (const r of f.routines) {+ const routine: Routine = { id: randomUUID(), name: r.name, agentId: agent.id, conversationId: dm, prompt: r.prompt, schedule: r.schedule, enabled: false, createdAt: Date.now() }+ db.saveRoutine(routine)+ added.routines+++ }+ }++ // Waiting for a yes, like any memory an agent proposes.+ const seen = new Set<string>()+ for (const text of f.memories) {+ const key = text.toLowerCase().replace(/\s+/g, ' ')+ if (seen.has(key)) continue+ seen.add(key)+ const at = Date.now()+ const m: Memory = { id: randomUUID(), scope: agent.id, text, state: 'pending', origin: 'agent', agentId: agent.id, messageIds: [], createdAt: at, confirmedAt: at }+ db.saveMemory(m)+ added.memories.push(m)+ }+ }++ // Group chats become channels of their own: an imported agent never joins one that's already here,+ // where it would read the conversation. And only the agents made by this import go in: one that was+ // already here (it may only look the same, like a copy of Tuca) is never put in a room with a stranger+ // by a file. Imported again, the channel has no one new and is skipped.+ const made = new Set(added.agents)+ let channels = 0+ for (const c of team.channels) {+ const mapped = [...new Set(c.members.flatMap((k) => byKey.get(k) ?? []))]+ const members = mapped.filter((id) => made.has(id))+ if (!members.length) continue+ const kept = mapped.filter((id) => !made.has(id)).map((id) => db.agent(id)?.name).filter(Boolean)+ const all = db.conversations().filter((x) => x.kind === 'channel')+ const base = c.name.slice(0, 54) // room for "-<number>" within a channel name's 60+ const same = (x: { name: string; members: string[] }): boolean =>+ (x.name === c.name || (x.name.startsWith(`${base}-`) && /^\d+$/.test(x.name.slice(base.length + 1)))) && x.members.length === members.length && members.every((id) => x.members.includes(id))+ if (all.some(same)) continue+ let name = c.name+ for (let i = 2; all.some((x) => x.name === name); i++) name = `${base}-${i}`+ if (name !== c.name) left.push(L(`o canal #${c.name} já existia: os agentes entraram no #${name}, novo`, `#${c.name} already existed: the agents went into a new #${name}`))+ if (kept.length) left.push(L(`#${name}: ${kept.join(', ')} já ${kept.length > 1 ? 'estavam' : 'estava'} aqui e não ${kept.length > 1 ? 'entraram' : 'entrou'} (só os agentes importados agora entram)`, `#${name}: ${kept.join(', ')} ${kept.length > 1 ? 'were' : 'was'} already here and stayed out (only the agents imported now go in)`))+ db.createConversation({ id: randomUUID(), kind: 'channel', name, topic: c.topic, members })+ channels+++ }++ const n = added.agents.length+ const parts = [+ n && L(`${n} agente${n > 1 ? 's' : ''} sem nenhum conector e com a busca na web desligada`, `${n} agent${n > 1 ? 's' : ''} with no connector and web search off`),+ added.skills && `${added.skills} skill${added.skills > 1 ? 's' : ''}`,+ channels && L(`${channels} ${channels > 1 ? 'canais' : 'canal'}`, `${channels} channel${channels > 1 ? 's' : ''}`),+ added.routines && L(`${added.routines} rotina${added.routines > 1 ? 's' : ''} (desligadas)`, `${added.routines} routine${added.routines > 1 ? 's' : ''} (off)`),+ added.memories.length && L(`${added.memories.length} memória${added.memories.length > 1 ? 's' : ''} pra você confirmar`, `${added.memories.length} memor${added.memories.length > 1 ? 'ies' : 'y'} for you to confirm`)+ ].filter(Boolean)+ const done = parts.length ? L(`Do ${team.source}, importei ${parts.join(', ')}.`, `From ${team.source}, I imported ${parts.join(', ')}.`) : L(`Nada novo do ${team.source}.`, `Nothing new from ${team.source}.`)+ const same = added.same.length ? L(` Já existiam aqui: ${added.same.join(', ')}.`, ` Already here: ${added.same.join(', ')}.`) : ''+ const servers = team.servers.length ? L(` Conectores pra adicionar à mão, se quiser: ${team.servers.join(', ')}.`, ` Connectors to add by hand, if you want: ${team.servers.join(', ')}.`) : ''+ const shown = left.slice(0, SUMMARY_LINES).map((x) => `• ${x}`)+ if (left.length > SUMMARY_LINES) shown.push(L(`• e mais ${left.length - SUMMARY_LINES}`, `• and ${left.length - SUMMARY_LINES} more`))+ const out = left.length ? `\n\n${L('Fica pra você ver:', 'For you to check:')}\n${shown.join('\n')}` : ''+ return { summary: `${done}${same}${servers}${out}`, agents: added.agents, memories: added.memories }+}++// Reads whichever app the .zip came from.+export function readForeignZip(zip: Zip): ForeignTeam {+ if (isOpenBotTransfer(zip)) return readOpenBot(zip)+ if (zip.entries.has(TUCANO_IMPORT)) return readTucanoImport(zip)+ if (zip.entries.has('openbot-import.json')) throw new Error(L('Esse .zip foi feito pro OpenBot. Pra trazer do Grok Bot, use a skill de exportação do Tucano (botão "Skill pro Grok Bot").', 'That .zip was made for OpenBot. To bring agents from Grok Bot, use Tucano\'s export skill (the "Skill for Grok Bot" button).'))+ throw new Error(L('Não reconheci esse .zip. O Tucano importa a exportação do OpenBot (Configurações do servidor → Transfer → Export) e a do Grok Bot feita com a skill do Tucano.', "I didn't recognize that .zip. Tucano imports OpenBot's export (Server settings → Transfer → Export) and Grok Bot's, made with Tucano's skill."))+}diff --git a/src/core/index.ts b/src/core/index.tsindex c8f9bf7..f614525 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -34,6 +34,8 @@ import { report } from './report'import { usage } from './usage'import { Skills } from './skills'import { backup, backupIfDue, exportTeam, importTeam } from './team'+import { applyForeignTeam, readForeignZip } from './agent-import'+import { zipFromBuffer, zipFromFile } from './zip'import { Telegram } from './telegram'import { mainCipher, plainCipher, Secrets } from './secrets'import { Browser, type BrowserHost } from './browser'@@ -547,12 +549,22 @@ const demoPath = join(process.cwd(), 'scripts', 'demo-mcp-server.mjs')// even when archived. His model: the one given, else a plan's, else the router's// or the memory's, which the introduction made sure work.// `fresh` starts a new session: the builder screen opens with only his hello.-function ensureTuca(modelId?: string, fresh = false): { agentId: string; conversationId: string } {- const s = settings()- const works = (id: string): boolean => {+// A model runs here when its harness is chosen and signed in.+function worksWith(s: Settings): (id: string) => boolean {+ return (id) => {const m = modelInfo(id)return !!m?.id && s.engines[m.engine].loggedIn}+}+// The first that runs: the one given, a plan's, the router's or the memory's, or any a harness lists.+function readyModel(s: Settings, first?: string): string | undefined {+ const works = worksWith(s)+ return [first, 'sonnet', 'gpt-5.6-luna', s.routerModel, s.memoryModel, availableModels(s, listed)[0]?.id].find((id): id is string => !!id && id !== 'jev' && works(id))+}++function ensureTuca(modelId?: string, fresh = false): { agentId: string; conversationId: string } {+ const s = settings()+ const works = worksWith(s)let tuca = db.agents().find((a) => a.kind === 'tuca')// A harness turned off since: the model given now, if it works.if (tuca && !works(tuca.modelId) && modelId && works(modelId)) {@@ -561,7 +573,7 @@ function ensureTuca(modelId?: string, fresh = false): { agentId: string; conversemit({ type: 'agent', agent: tuca })}if (!tuca) {- const model = [modelId, 'sonnet', 'gpt-5.6-luna', s.routerModel, s.memoryModel, availableModels(s, listed)[0]?.id].find((id): id is string => !!id && id !== 'jev' && works(id))+ const model = readyModel(s, modelId)tuca = tucaAgent(model ?? 'sonnet', db.agents().map((a) => a.handle), s.defaultLimit)db.saveAgent(tuca)emit({ type: 'agent', agent: tuca })@@ -762,6 +774,22 @@ const api: Api = {for (const r2 of db.routines()) emit({ type: 'routine', routine: r2 })return r},+ importAgents: ({ path, data }) => {+ if (!path && !data) throw new Error(L('Escolha um arquivo .zip.', 'Choose a .zip file.'))+ const zip = path ? zipFromFile(path) : zipFromBuffer(Buffer.from(data!, 'base64'))+ try {+ const s = settings()+ const r = applyForeignTeam(db, readForeignZip(zip), { defaultLimit: s.defaultLimit, defaultModel: readyModel(s) ?? 'sonnet', works: worksWith(s) })+ for (const id of r.agents) emit({ type: 'agent', agent: db.agent(id)! })+ emitConversations()+ for (const k of db.skills()) emit({ type: 'skill', skill: k })+ for (const r2 of db.routines()) emit({ type: 'routine', routine: r2 })+ for (const m of r.memories) emit({ type: 'memory', memory: m })+ return r.summary+ } finally {+ zip.close()+ }+ },backupNow: () => backup(db, backups),openBackups: () => {mkdirSync(backups, { recursive: true })diff --git a/src/core/zip.ts b/src/core/zip.tsnew file mode 100644index 0000000..0fede62--- /dev/null+++ b/src/core/zip.ts@@ -0,0 +1,109 @@+// Reads a .zip without a library: the central directory for the list, then only the entries asked for,+// stored or deflated. Nothing is written to disk. Each entry has a cap, checked before inflating, so a+// small file that claims to unpack into gigabytes is refused. No ZIP64 (files over 4 GB), no encryption.+import { closeSync, fstatSync, openSync, readSync } from 'node:fs'+import { inflateRawSync } from 'node:zlib'+import { L } from '../shared/lang'++export interface ZipEntry {+ name: string+ size: number // uncompressed+ compressed: number+ method: number // 0 stored, 8 deflate+ offset: number // of its local header+}++export interface Zip {+ entries: Map<string, ZipEntry>+ // The entry's bytes; undefined when it isn't there. Throws over `max` bytes.+ read(name: string, max: number): Buffer | undefined+ close(): void+}++type At = (offset: number, length: number) => Buffer++const EOCD = 0x06054b50+const CENTRAL = 0x02014b50+const LOCAL = 0x04034b50+const MAX_ENTRIES = 100_000++const broken = (): Error => new Error(L('Esse arquivo .zip está corrompido ou não é um .zip.', "That .zip file is corrupted or isn't a .zip."))++function open(size: number, at: At, close: () => void): Zip {+ // The end record is in the last 22 bytes, or before a comment of up to 64 KB.+ const tail = Math.min(size, 22 + 0xffff)+ const end = at(size - tail, tail)+ let e = -1+ for (let i = end.length - 22; i >= 0; i--) if (end.readUInt32LE(i) === EOCD) { e = i; break }+ if (e < 0) throw broken()+ const count = end.readUInt16LE(e + 10)+ const dirSize = end.readUInt32LE(e + 12)+ const dirOffset = end.readUInt32LE(e + 16)+ if (count === 0xffff || dirOffset === 0xffffffff) throw new Error(L('Esse .zip é grande demais (ZIP64), e o Tucano ainda não lê esse tipo.', "That .zip is too big (ZIP64), and Tucano doesn't read that kind yet."))+ if (count > MAX_ENTRIES || dirOffset + dirSize > size) throw broken()+ const dir = at(dirOffset, dirSize)+ const entries = new Map<string, ZipEntry>()+ let p = 0+ for (let i = 0; i < count; i++) {+ if (p + 46 > dir.length || dir.readUInt32LE(p) !== CENTRAL) throw broken()+ const flags = dir.readUInt16LE(p + 8)+ const method = dir.readUInt16LE(p + 10)+ const compressed = dir.readUInt32LE(p + 20)+ const usize = dir.readUInt32LE(p + 24)+ const nameLen = dir.readUInt16LE(p + 28)+ const extraLen = dir.readUInt16LE(p + 30)+ const commentLen = dir.readUInt16LE(p + 32)+ const offset = dir.readUInt32LE(p + 42)+ const name = dir.subarray(p + 46, p + 46 + nameLen).toString(flags & 0x800 ? 'utf8' : 'latin1')+ p += 46 + nameLen + extraLen + commentLen+ if (flags & 1) continue // encrypted: never read+ if (!name.endsWith('/')) entries.set(name, { name, size: usize, compressed, method, offset })+ }+ return {+ entries,+ read(name, max) {+ const z = entries.get(name)+ if (!z) return undefined+ if (z.size > max) throw new Error(L(`"${name}" passa do tamanho que o Tucano lê.`, `"${name}" is over the size Tucano reads.`))+ const head = at(z.offset, 30)+ if (head.readUInt32LE(0) !== LOCAL) throw broken()+ const start = z.offset + 30 + head.readUInt16LE(26) + head.readUInt16LE(28)+ if (start + z.compressed > size) throw broken()+ const raw = at(start, z.compressed)+ if (z.method === 0) return raw+ if (z.method !== 8) throw new Error(L(`"${name}" usa uma compressão que o Tucano não lê.`, `"${name}" uses a compression Tucano doesn't read.`))+ try {+ return inflateRawSync(raw, { maxOutputLength: Math.max(1, z.size) })+ } catch {+ throw broken()+ }+ },+ close+ }+}++export function zipFromBuffer(buf: Buffer): Zip {+ return open(buf.length, (o, n) => buf.subarray(o, o + n), () => {})+}++// Reads only the parts it needs, so a big export (with the agents' files) isn't loaded whole.+export function zipFromFile(path: string): Zip {+ const fd = openSync(path, 'r')+ try {+ const size = fstatSync(fd).size+ const at: At = (o, n) => {+ const b = Buffer.alloc(n)+ let got = 0+ while (got < n) {+ const r = readSync(fd, b, got, n - got, o + got)+ if (r === 0) break+ got += r+ }+ return b.subarray(0, got)+ }+ return open(size, at, () => closeSync(fd))+ } catch (e) {+ closeSync(fd)+ throw e+ }+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 1659320..03bc220 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,4 +1,4 @@-import { contextBridge, ipcRenderer } from 'electron'+import { contextBridge, ipcRenderer, webUtils } from 'electron'// The page asks for a port to the core; it arrives here and is handed to the// page through window.postMessage, the only way to pass a port across@@ -10,6 +10,8 @@ ipcRenderer.on('core:port', (event) => {contextBridge.exposeInMainWorld('tucano', {connect: (): void => ipcRenderer.send('core:connect'),pickFolder: (): Promise<string | null> => ipcRenderer.invoke('pick-folder') as Promise<string | null>,+ // A picked file's path, so the core reads a big .zip in parts instead of through the page.+ pathOf: (file: File): string => webUtils.getPathForFile(file),// A click on a notification opens its conversation.onNavigate: (cb: (conversationId: string) => void): void => {ipcRenderer.on('navigate', (_e, id: unknown) => typeof id === 'string' && cb(id))diff --git a/src/renderer/src/assets/tucano-export-skill.md b/src/renderer/src/assets/tucano-export-skill.mdnew file mode 100644index 0000000..6653fc3--- /dev/null+++ b/src/renderer/src/assets/tucano-export-skill.md@@ -0,0 +1,105 @@+---+name: tucano-export+description: Writes a .zip that Tucano (tucano.sh) opens to recreate the user's agents from here, with their instructions, pictures, skills, scheduled tasks, remembered facts and group chats. Use when the user wants their agents in Tucano.+---++# Export to Tucano++The user is moving to Tucano, a desktop app where a team of agents runs on their own computer. Tucano+can't connect to this app. What it can do is open one file: a `.zip` holding `tucano-import.json` and a+few files per agent. Your job is to write that file and hand it to the user, who opens it in Tucano at+**Settings → Team and backup → Import from another app**.++Tucano reads only the fields and paths described here and ignores everything else. Logins, tool access+and connections never travel: every imported agent starts in Tucano with no tools, web search off and its+scheduled tasks paused, and the user turns each thing on there. So spend no effort on access.++## What goes in the zip++```+tucano-import.json at the root of the zip, not inside a folder+agents/<key>/picture.png optional; .png, .jpg or .webp, up to 140 KB+agents/<key>/skills/<name>/SKILL.md one folder per skill, with only that file in it+```++`<key>` is a short id you choose for each agent, used only inside this file: it starts with a lowercase+letter, then lowercase letters, digits or hyphens, 40 characters at most, and no two agents share one+(`writer`, `ops-2`).++## How to fill each field++Copy, don't compose. Whatever you can't read here, leave out and list in the report you give at the end.++**Agents** (40 at most). For each agent the user wants to bring:++- `key`: as above.+- `name`: the agent's name, up to 80 characters. Required.+- `role`: what it does, in two to five words, up to 80 characters.+- `instructions`: its standing instructions or system prompt, copied as they are, up to 32,000 characters.+ If a line holds a password, token, API key or any other credential, drop that line and say so in the+ report. Tucano asks for credentials through its own connectors.+- `picture`: the path of its picture in the zip, when it has one.+- `skills`: the paths of its skill folders (20 at most per agent). Each `SKILL.md` starts with a+ frontmatter block holding `name` and `description`, followed by the recipe, up to 20,000 characters.+ Tucano reads that file alone, so don't copy scripts, data or anything else into the folder.+- `routines`: its scheduled tasks (20 at most per agent), each with `name`, `prompt` (what the task+ asks), `days` (any of `sun mon tue wed thu fri sat`), `time` (`HH:MM`, 24-hour clock) and `timezone`+ (an IANA name, like `Europe/Lisbon`). Add `"once": true` to a task that runs a single time. Tucano runs+ tasks only at a time of day on chosen weekdays: a task that repeats every few minutes or hours, or on a+ date of the month, doesn't fit, so leave it out and report it.+- `memories`: what the agent knows about the user and the work, as plain statements of one fact each,+ up to 300 characters and 40 per agent. Prefer what still matters next month: preferences, people,+ decisions, ongoing projects. Each one waits in Tucano until the user confirms it, so a wrong fact costs+ them a click; a made-up one costs their trust. Never copy a credential into a memory.++**Group chats** (30 at most) go in `channels`: `name` (up to 80 characters), `topic` (one line,+optional) and `members` (the keys of the agents in it). Tucano always makes a new channel for each one.++## Before you write anything++Tell the user which agents and group chats you found and ask which to bring. Unless they say otherwise,+bring them all. Then write the agents' files, and `tucano-import.json` once those are in place.++## Example++```json+{+ "format": "tucano-agent-import",+ "version": 1,+ "source": "grok-bot",+ "agents": [+ {+ "key": "ledger",+ "name": "Ledger",+ "role": "Bookkeeping",+ "instructions": "You match each invoice against the bank statement and flag the ones that don't add up…",+ "picture": "agents/ledger/picture.png",+ "skills": ["agents/ledger/skills/reconcile"],+ "routines": [+ {+ "name": "Unpaid invoices",+ "prompt": "List the invoices still unpaid, with who owes each and since when.",+ "days": ["mon"],+ "time": "17:15",+ "timezone": "Europe/Lisbon"+ }+ ],+ "memories": ["Invoice numbers look like INV-2026-0042."]+ }+ ],+ "channels": [+ { "name": "finance-room", "topic": "Invoices and payments", "members": ["ledger"] }+ ]+}+```++`format`, `version` and `source` stay exactly as in the example. Tucano turns down a file whose+`format` or `version` differs, and skips an agent whose `key` or `name` breaks the rules above.++## Handing it over++Zip the contents of the folder, so `tucano-import.json` sits at the top of the zip, and name it+`tucano-export-<YYYY-MM-DD>.zip`. Send it to the user here as a file they can download.++With it, send a short report: for each agent, what went in (instructions, picture, how many skills,+tasks and memories) and what didn't, with the reason. End with where to open the file in Tucano.diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex d421daf..fe47f5f 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -29,6 +29,7 @@ import {unpairTelegram,setGithubToken,exportTeam,+ importAgents,importTeam,backupNow,openBackups,@@ -63,6 +64,7 @@ import { AppsCard } from './Apps'import { ApprovalCard } from './Conversation'import { AgentAvatar, AVATARS, Icon, NumberInput, SleepingToucan, time, tokens, UsageBar } from './ui'import { UpdateSettings } from './Update'+import exportSkill from '../assets/tucano-export-skill.md?raw'export function Page({ title, subtitle, actions, children }: { title: ReactNode; subtitle?: ReactNode; actions?: ReactNode; children: ReactNode }): ReactNode {return (@@ -1472,8 +1474,23 @@ function GithubCard({ info }: { info?: { user?: string; error?: string } }): Rea}// The team as a file, and backups of everything.+const MAX_UPLOAD = 40_000_000 // a browser's request has a cap (64 MB) and base64 grows a thirdfunction TeamCard(): ReactNode {const [note, setNote] = useState('')+ // Grok Bot has no export: one of the person's agents there runs this skill and writes our .zip.+ const grokSkill = (): void => {+ const a = document.createElement('a')+ a.href = URL.createObjectURL(new Blob([exportSkill], { type: 'text/markdown' }))+ a.download = 'SKILL.md'+ a.click()+ URL.revokeObjectURL(a.href)+ setNote(+ L(+ 'Baixei o SKILL.md. No Grok Bot, dê a skill a um dos seus agentes (ou cole o texto numa conversa com ele) e peça: "Exporte meus agentes pro Tucano". Ele te devolve um .zip, que você abre em "Importar de outro app…". É experimental: ainda não foi testada dentro do Grok Bot, então confira o resumo da importação.',+ 'I downloaded SKILL.md. In Grok Bot, give the skill to one of your agents (or paste its text in a chat with it) and ask: "Export my agents to Tucano". It gives you back a .zip, which you open with "Import from another app…". It\'s experimental: it hasn\'t been tried inside Grok Bot yet, so check the import summary.'+ )+ )+ }const download = (): void => {void exportTeam().then((md) => {const a = document.createElement('a')@@ -1483,16 +1500,31 @@ function TeamCard(): ReactNode {URL.revokeObjectURL(a.href)})}+ const failed = (e: unknown): void => setNote(e instanceof Error ? e.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(e))const upload = (file?: File): void => {if (!file) return+ void file.text().then(importTeam).then(setNote, failed)+ }+ // Another app's export: on the desktop the core reads the file where it is; in a browser it goes up whole.+ const fromApp = (file?: File): void => {+ if (!file) return+ setNote(L('Lendo o arquivo…', 'Reading the file…'))+ const path = window.tucano.pathOf?.(file)+ if (path) return void importAgents({ path }).then(setNote, failed)+ if (file.size > MAX_UPLOAD) return setNote(L('Arquivo grande demais pra mandar pelo navegador. Importe no app do computador, ou exporte sem os arquivos.', 'File too big to send through the browser. Import it in the desktop app, or export without the files.'))void file- .text()- .then(importTeam)- .then(setNote, (e: unknown) => setNote(e instanceof Error ? e.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(e)))+ .arrayBuffer()+ .then((b) => {+ const bytes = new Uint8Array(b)+ let bin = ''+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))+ return importAgents({ data: btoa(bin) })+ })+ .then(setNote, failed)}return (- <Card title={L('Time e backup', 'Team and backup')} lead={L('O time num arquivo .md (agentes, skills, canais e rotinas, sem credenciais nem conversas), pra guardar ou levar pra outro computador. E uma cópia de tudo uma vez por dia (as últimas 7).', 'The team in a .md file (agents, skills, channels and routines, without credentials or conversations), to keep or take to another computer. And a copy of everything once a day (the last 7).')}>- <div className="row">+ <Card title={L('Time e backup', 'Team and backup')} lead={L('O time num arquivo .md (agentes, skills, canais e rotinas, sem credenciais nem conversas), pra guardar ou levar pra outro computador. Os agentes do OpenBot e do Grok Bot também entram, sem nenhum conector e com a busca na web desligada. E uma cópia de tudo uma vez por dia (as últimas 7).', 'The team in a .md file (agents, skills, channels and routines, without credentials or conversations), to keep or take to another computer. Agents from OpenBot and Grok Bot come in too, with no connector and web search off. And a copy of everything once a day (the last 7).')}>+ <div className="row" style={{ flexWrap: 'wrap' }}><button className="btn btn--sm" onClick={download}>{L('Exportar time', 'Export team')}</button>@@ -1500,7 +1532,33 @@ function TeamCard(): ReactNode {{L('Importar time…', 'Import team…')}<input type="file" accept=".md,text/markdown" hidden onChange={(e) => upload(e.target.files?.[0])} /></label>- <span className="grow" />+ <label+ className="btn btn--sm"+ title={L(+ 'OpenBot: Configurações do servidor → Transfer → Export from this server, com os arquivos. Grok Bot: o .zip feito com a skill do Tucano.',+ "OpenBot: Server settings → Transfer → Export from this server, with the files. Grok Bot: the .zip made with Tucano's skill."+ )}+ >+ {L('Importar de outro app…', 'Import from another app…')}+ <input+ type="file"+ accept=".zip,application/zip"+ hidden+ onChange={(e) => {+ fromApp(e.target.files?.[0])+ e.target.value = ''+ }}+ />+ </label>+ <button+ className="btn btn--sm"+ onClick={grokSkill}+ title={L('Experimental: a skill que exporta seus agentes do Grok Bot pro Tucano. Ainda não foi testada dentro do Grok Bot.', "Experimental: the skill that exports your agents from Grok Bot to Tucano. It hasn't been tried inside Grok Bot yet.")}+ >+ {L('Skill pro Grok Bot (experimental)', 'Skill for Grok Bot (experimental)')}+ </button>+ </div>+ <div className="row" style={{ marginTop: 8 }}><button className="btn btn--sm" onClick={() => void backupNow().then((f) => setNote(L(`Backup feito: ${f.split('/').pop()}`, `Backup done: ${f.split('/').pop()}`)))}>{L('Fazer backup agora', 'Back up now')}</button>@@ -1508,7 +1566,7 @@ function TeamCard(): ReactNode {{L('Abrir pasta', 'Open folder')}</button></div>- {note && <p className="small muted">{note}</p>}+ {note && <p className="small muted" style={{ whiteSpace: 'pre-line' }}>{note}</p>}</Card>)}diff --git a/src/renderer/src/rpc.ts b/src/renderer/src/rpc.tsindex eff1a5d..a1db89b 100644--- a/src/renderer/src/rpc.ts+++ b/src/renderer/src/rpc.ts@@ -6,6 +6,7 @@ declare global {tucano: {connect: () => voidpickFolder: () => Promise<string | null>+ pathOf?: (file: File) => string // a dropped or picked file's path on this computer (desktop only)onNavigate: (cb: (conversationId: string) => void) => voidviewing: (conversationId: string | null) => voidupdateState: () => Promise<UpdateState>diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex aecc10e..41ebc4a 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -484,6 +484,7 @@ export const unpairTelegram = (): void => void call('unpairTelegram')export const setGithubToken = (token: string | null): Promise<void> => call('setGithubToken', { token })export const exportTeam = (): Promise<string> => call('exportTeam')export const importTeam = (text: string): Promise<string> => call('importTeam', { text })+export const importAgents = (p: { path?: string; data?: string }): Promise<string> => call('importAgents', p)export const backupNow = (): Promise<string> => call('backupNow')export const openBackups = (): void => void call('openBackups')export const loadReport = (week?: number): Promise<Report> => call('report', { week })diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex 2e32eae..8c85629 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -90,6 +90,7 @@ export interface Api {unpairTelegram(): voidexportTeam(): string // the team as MarkdownimportTeam(p: { text: string }): string // what was added; throws if it isn't a team file+ importAgents(p: { path?: string; data?: string }): string // agents from another app's .zip (a path on this computer, or base64); what was addedbackupNow(): string // where the copy wentopenBackups(): voidreport(p: { week?: number }): Report // the calendar week starting at `week` (a Monday); this one by defaultdiff --git a/test/agent-import.test.ts b/test/agent-import.test.tsnew file mode 100644index 0000000..2ddbd8d--- /dev/null+++ b/test/agent-import.test.ts@@ -0,0 +1,379 @@+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { deflateRawSync } from 'node:zlib'+import { describe, expect, it } from 'vitest'+import { Db } from '../src/core/db'+import { applyForeignTeam, hueColor, IMPORT_CAPS, openBotSchedule, readForeignZip, tucanoSchedule } from '../src/core/agent-import'+import { zipFromBuffer, zipFromFile } from '../src/core/zip'++const fresh = (): Db => new Db(join(mkdtempSync(join(tmpdir(), 'ad-import-')), 'test.db'))++// A small zip writer for the tests: stored or deflated entries, sizes only in the central directory+// (as a streaming writer leaves them), and an optional lie about one entry's size.+function zip(files: Record<string, string | Buffer>, opts: { deflate?: boolean; claim?: Record<string, number> } = {}): Buffer {+ const locals: Buffer[] = []+ const central: Buffer[] = []+ let offset = 0+ for (const [name, content] of Object.entries(files)) {+ const data = Buffer.isBuffer(content) ? content : Buffer.from(content)+ const body = opts.deflate ? deflateRawSync(data) : data+ const n = Buffer.from(name)+ const local = Buffer.alloc(30)+ local.writeUInt32LE(0x04034b50, 0)+ local.writeUInt16LE(0x808, 6) // utf-8 names, sizes after the data+ local.writeUInt16LE(opts.deflate ? 8 : 0, 8)+ local.writeUInt16LE(n.length, 26)+ locals.push(local, n, body)+ const c = Buffer.alloc(46)+ c.writeUInt32LE(0x02014b50, 0)+ c.writeUInt16LE(0x808, 8)+ c.writeUInt16LE(opts.deflate ? 8 : 0, 10)+ c.writeUInt32LE(body.length, 20)+ c.writeUInt32LE(opts.claim?.[name] ?? data.length, 24)+ c.writeUInt16LE(n.length, 28)+ c.writeUInt32LE(offset, 42)+ central.push(c, n)+ offset += 30 + n.length + body.length+ }+ const dir = Buffer.concat(central)+ const end = Buffer.alloc(22)+ end.writeUInt32LE(0x06054b50, 0)+ end.writeUInt16LE(Object.keys(files).length, 8)+ end.writeUInt16LE(Object.keys(files).length, 10)+ end.writeUInt32LE(dir.length, 12)+ end.writeUInt32LE(offset, 16)+ return Buffer.concat([...locals, dir, end])+}++const PNG = Buffer.from('89504e470d0a1a0a0000000d49484452', 'hex')++const lia = {+ key: 'lia',+ name: 'Lia',+ title: 'Pesquisadora',+ description: 'Acha fontes.',+ avatarSeed: 'plush:1',+ avatarHue: 215,+ avatar: 'agents/lia/avatar.png',+ provider: 'claude',+ model: 'claude-opus-5-5',+ reasoningEffort: 'max',+ notifications: true,+ skills: ['agents/lia/skills/fontes'],+ files: 'agents/lia/workspace',+ routines: [+ { key: 'r1', name: 'Resumo do dia', instruction: 'Resuma as notícias.', active: true, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, schedule: { kind: 'weekdays', time: '09:00' } },+ { key: 'r2', name: 'A cada hora', instruction: 'Olhe a caixa.', active: true, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, schedule: { kind: 'hourly', minute: 5 } }+ ],+ memories: [{ text: 'Eduardo prefere fontes primárias.' }, { text: 'Eduardo prefere fontes primárias.' }, { text: 'Responde em português.', inclusion: 'essential' }]+}+const gil = { ...lia, key: 'gil', name: 'Gil', title: 'Grok', description: '', avatar: null, avatarHue: null, provider: 'grok', model: 'grok-4.6', reasoningEffort: 'low', skills: ['agents/gil/skills/fontes'], files: null, routines: [], memories: [] }++const transfer = (agents: unknown[], extra: Record<string, unknown> = {}): string =>+ JSON.stringify({+ format: 'openbot-instance-transfer',+ version: 1,+ source: { appVersion: '0.59.0', exportedAt: '2026-11-03T12:00:00Z' },+ agents,+ settings: { mcpServers: [{ id: 'm', name: 'GitHub', transport: 'stdio', enabled: true, command: 'npx', args: [], env: [], envPassthrough: [], workingDirectory: '', url: '', headers: [] }], customProviders: [], customAgents: [], sidebarSections: [], routineFlows: [] },+ shared: null,+ signedIn: ['claude'],+ ...extra+ })++const skill = '---\nname: fontes\ndescription: Ao procurar uma fonte\n---\n\nUse a fonte primária.\n'+const files = (): Record<string, string | Buffer> => ({+ 'openbot-transfer.json': transfer([lia, gil]),+ 'agents/lia/avatar.png': PNG,+ 'agents/lia/skills/fontes/SKILL.md': skill,+ 'agents/lia/skills/fontes/check.sh': 'echo oi',+ 'agents/lia/workspace/AGENTS.md': '# Lia\n\nSempre cite a fonte.',+ 'agents/lia/workspace/notes.txt': 'x',+ 'agents/gil/skills/fontes/SKILL.md': skill+})+const opts = { defaultLimit: 2_000_000, defaultModel: 'sonnet' }++describe('importing agents from OpenBot', () => {+ it('brings the agents with no tool, routines off and memories to confirm', () => {+ const db = fresh()+ db.saveAgent({ id: 'x', name: 'Lia', handle: 'lia', role: 'Outra', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'medium', limit: 1, used: 0, grants: {}, memory: 'auto', computer: false, archived: false })+ const r = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip(files(), { deflate: true }))), opts)++ const imported = db.agents().filter((a) => a.id !== 'x')+ expect(imported.map((a) => a.handle).sort()).toEqual(['gil', 'lia2'])+ const l = imported.find((a) => a.name === 'Lia')!+ expect(l).toMatchObject({ role: 'Pesquisadora', instructions: '# Lia\n\nSempre cite a fonte.', modelId: 'opus', effort: 'xhigh', grants: {}, computer: false, web: false, limit: 2_000_000, customColor: hueColor(215) })+ expect(l.picture).toBe(`data:image/png;base64,${PNG.toString('base64')}`)+ const g = imported.find((a) => a.name === 'Gil')!+ expect(g).toMatchObject({ modelId: 'sonnet', effort: 'low', instructions: '' })++ // One skill for both, since it's the same recipe.+ expect(db.skills()).toHaveLength(1)+ expect(db.skills()[0]).toMatchObject({ name: 'fontes', description: 'Ao procurar uma fonte', body: 'Use a fonte primária.' })+ expect(db.skills()[0]!.agents.sort()).toEqual([l.id, g.id].sort())++ // The weekday routine comes in, off, in the agent's DM; the hourly one has no match.+ expect(db.routines()).toHaveLength(1)+ expect(db.routines()[0]).toMatchObject({ name: 'Resumo do dia', enabled: false, schedule: { days: [1, 2, 3, 4, 5], time: '09:00' } })+ expect(db.conversation(db.routines()[0]!.conversationId)).toMatchObject({ kind: 'dm', name: l.id })++ const mems = db.memories({ scope: l.id })+ expect(mems.map((m) => m.text)).toEqual(['Eduardo prefere fontes primárias.', 'Responde em português.'])+ expect(mems.every((m) => m.state === 'pending')).toBe(true)++ expect(r.summary).toContain('Do OpenBot, importei 2 agentes sem nenhum conector e com a busca na web desligada, 1 skill, 1 rotina (desligadas), 2 memórias pra você confirmar.')+ expect(r.summary).toContain('Conectores pra adicionar à mão, se quiser: GitHub.')+ expect(r.summary).toContain('a rotina "A cada hora"')+ expect(r.summary).toContain('grok não roda no Tucano')+ expect(r.summary).toContain('1 arquivo da skill fontes além do SKILL.md')+ expect(r.summary).toContain('@gil: as instruções')++ // Again: nothing doubles.+ const again = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip(files()))), opts)+ expect(again.summary).toContain('Nada novo do OpenBot. Já existiam aqui: Lia, Gil.')+ expect(db.agents()).toHaveLength(3)+ })++ it('reads the file from disk the same way', () => {+ const file = join(mkdtempSync(join(tmpdir(), 'ad-zip-')), 'export.zip')+ writeFileSync(file, zip(files()))+ const z = zipFromFile(file)+ expect(readForeignZip(z).agents.map((a) => a.name)).toEqual(['Lia', 'Gil'])+ z.close()+ })++ it('keeps out paths outside the agent, and a skill named like one already here', () => {+ const db = fresh()+ db.saveSkill({ id: 'k', name: 'fontes', description: 'minha', body: 'minha receita', agents: [], state: 'active', createdAt: 1, updatedAt: 1 })+ const sneaky = { ...lia, avatar: 'agents/lia/../../etc/passwd.png', files: 'agents/other/workspace', skills: ['agents/lia/skills/fontes', '/etc/skills/x'] }+ const r = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip({ ...files(), 'openbot-transfer.json': transfer([sneaky]), 'agents/other/workspace/AGENTS.md': 'not hers' }))), opts)+ const a = db.agents()[0]!+ expect(a.picture).toBeUndefined()+ expect(a.instructions).toBe('Acha fontes.')+ // Her skill comes under another name; mine stays as it was.+ expect(db.skills().map((k) => k.name).sort()).toEqual(['fontes', 'fontes-lia'])+ expect(db.skill('k')).toMatchObject({ body: 'minha receita', agents: [] })+ expect(r.summary).toContain('1 skill')+ })++ it('refuses what is not an OpenBot export, a newer version and an entry that unpacks too big', () => {+ expect(() => readForeignZip(zipFromBuffer(zip({ 'a.txt': 'x' })))).toThrow('Não reconheci esse .zip')+ expect(() => readForeignZip(zipFromBuffer(zip({ 'openbot-import.json': '{}' })))).toThrow('Grok Bot')+ expect(() => readForeignZip(zipFromBuffer(zip({ 'openbot-transfer.json': transfer([], { version: 2 }) })))).toThrow('versão do OpenBot')+ expect(() => readForeignZip(zipFromBuffer(zip({ 'openbot-transfer.json': '{nope' })))).toThrow('corrompido')+ expect(() => zipFromBuffer(Buffer.from('not a zip at all, just text'))).toThrow('corrompido')+ const bomb = zip({ ...files(), 'openbot-transfer.json': transfer([lia]) }, { deflate: true, claim: { 'agents/lia/workspace/AGENTS.md': 50_000_000 } })+ // The instructions are over the cap: only they stay out, and the agent comes with its description.+ const team = readForeignZip(zipFromBuffer(bomb))+ expect(team.agents).toHaveLength(1)+ expect(team.agents[0]).toMatchObject({ instructions: 'Acha fontes.', skills: [{ name: 'fontes' }] })+ expect(team.agents[0]!.notes).toContain("o AGENTS.md (não deu pra ler)")+ })++ it('drops only the part that cannot be read, not the agent', () => {+ const bad = zip({ ...files(), 'openbot-transfer.json': transfer([lia]) }, { deflate: true, claim: { 'agents/lia/skills/fontes/SKILL.md': 50_000_000, 'agents/lia/avatar.png': 50_000_000 } })+ const [a] = readForeignZip(zipFromBuffer(bad)).agents+ expect(a).toMatchObject({ name: 'Lia', instructions: '# Lia\n\nSempre cite a fonte.', skills: [], picture: undefined })+ expect(a!.notes).toEqual(expect.arrayContaining(['a skill fontes (não deu pra ler)', 'a foto (grande demais)']))+ })++ it('keeps a Gemini agent on Gemini, and moves a model whose CLI is not ready to one that is', () => {+ const gem = { ...gil, key: 'gem', name: 'Gem', provider: 'gemini', model: 'gemini-3-pro', skills: [] }+ const cur = { ...gil, key: 'cur', name: 'Cur', provider: 'cursor', model: 'composer-2', skills: [] }+ const db = fresh()+ const r = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip({ 'openbot-transfer.json': transfer([gem, cur]) }))), { ...opts, defaultModel: 'gemini:gemini-3-pro', works: (id) => id.startsWith('gemini:') })+ expect(db.agents().map((a) => [a.name, a.modelId])).toEqual([['Gem', 'gemini:gemini-3-pro'], ['Cur', 'gemini:gemini-3-pro']])+ expect(r.summary).not.toContain('não roda no Tucano')+ expect(r.summary).toContain('@cur: o modelo cursor:composer-2 (o CLI dele não está pronto aqui: ficou gemini:gemini-3-pro)')+ })++ it('brings at most so many agents, memories and routines, and says how many stayed out', () => {+ const many = Array.from({ length: 300 }, (_, i) => ({+ ...gil,+ key: `a${i}`,+ name: `A${i}`,+ skills: [],+ memories: Array.from({ length: i === 0 ? 5000 : 1 }, (_, j) => ({ text: `fato ${j}` })),+ routines: Array.from({ length: i === 0 ? 2000 : 0 }, (_, j) => ({ name: `r${j}`, instruction: 'x', schedule: { kind: 'daily', time: '09:00' } }))+ }))+ const db = fresh()+ const r = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip({ 'openbot-transfer.json': transfer(many) }))), opts)+ expect(db.agents()).toHaveLength(IMPORT_CAPS.agents)+ const first = db.agents().find((a) => a.name === 'A0')!+ expect(db.memories({ scope: first.id })).toHaveLength(IMPORT_CAPS.memories)+ expect(db.routines().filter((x) => x.agentId === first.id)).toHaveLength(IMPORT_CAPS.routines)+ expect(r.summary).toContain(`260 agentes além de ${IMPORT_CAPS.agents}`)+ expect(r.summary).toContain(`4960 memórias além de ${IMPORT_CAPS.memories}`)+ expect(r.summary).toContain(`1980 rotinas além de ${IMPORT_CAPS.routines}`)+ expect(r.summary).toContain('• e mais')+ expect(r.summary.length).toBeLessThan(6_000)+ })++ it('turns schedules into the ones Tucano runs', () => {+ expect(openBotSchedule({ kind: 'daily', time: '07:30' })).toEqual({ days: [0, 1, 2, 3, 4, 5, 6], time: '07:30' })+ expect(openBotSchedule({ kind: 'weekly', weekday: 0, time: '18:00' })).toEqual({ days: [0], time: '18:00' })+ expect(openBotSchedule({ kind: 'advanced', months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], days: { kind: 'days-of-week', days: [5, 1] }, time: { kind: 'at-time', time: '10:00' } })).toEqual({ days: [1, 5], time: '10:00' })+ expect(openBotSchedule({ kind: 'advanced', months: [1], days: { kind: 'every-day' }, time: { kind: 'at-time', time: '10:00' } })).toBeUndefined()+ expect(openBotSchedule({ kind: 'monthly', day: 1, time: '10:00' })).toBeUndefined()+ expect(openBotSchedule({ kind: 'custom', expression: '* * * * *' })).toBeUndefined()+ const soon = new Date(Date.now() + 2 * 86_400_000)+ const date = `${soon.getFullYear()}-${String(soon.getMonth() + 1).padStart(2, '0')}-${String(soon.getDate()).padStart(2, '0')}`+ expect(openBotSchedule({ kind: 'once', date, time: '12:00' })).toEqual({ days: [soon.getDay()], time: '12:00', once: true })+ expect(openBotSchedule({ kind: 'once', date: '2020-01-01', time: '12:00' })).toBeUndefined()+ expect(hueColor(0)).toMatch(/^#[0-9a-f]{6}$/)+ })+})++describe('importing agents from Grok Bot, through our skill', () => {+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone+ const manifest = (extra: Record<string, unknown> = {}): string =>+ JSON.stringify({+ format: 'tucano-agent-import',+ version: 1,+ source: 'grok-bot',+ agents: [+ {+ key: 'ledger',+ name: 'Ledger',+ role: 'Bookkeeping',+ instructions: 'You match invoices.',+ picture: 'agents/ledger/picture.png',+ skills: ['agents/ledger/skills/reconcile'],+ routines: [+ { name: 'Unpaid invoices', prompt: 'List unpaid invoices.', days: ['mon', 'tue', 'wed', 'thu', 'fri'], time: '08:30', timezone: zone },+ { name: 'Every hour', prompt: 'Check the inbox.', days: [], time: '00:00' }+ ],+ memories: ['Invoice numbers look like INV-2026-0042.', 'Invoice numbers look like INV-2026-0042.']+ },+ { key: 'sales', name: 'Sales', role: 'Outbound', instructions: '', routines: [], memories: [] },+ { key: 'sales', name: 'Twin', instructions: 'same key' },+ { key: 'Bad Key', name: 'Nope', instructions: 'x' }+ ],+ channels: [+ { name: 'Finance Room', topic: 'Invoices and payments', members: ['ledger', 'sales', 'ghost'], routines: [{ name: 'Friday' }] },+ { name: 'geral', members: ['sales'] }+ ],+ ...extra+ })+ const files = (): Record<string, string | Buffer> => ({+ 'tucano-import.json': manifest(),+ 'agents/ledger/picture.png': PNG,+ 'agents/ledger/skills/reconcile/SKILL.md': '---\nname: reconcile\ndescription: When reconciling\n---\n\nKeep it short.\n',+ 'agents/ledger/skills/reconcile/template.txt': 'x'+ })++ it('brings agents, skills, routines off, memories to confirm and group chats as channels', () => {+ const db = fresh()+ db.createConversation({ id: 'g', kind: 'channel', name: 'geral', members: [] })+ const r = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip(files(), { deflate: true }))), opts)++ expect(db.agents().map((a) => a.handle).sort()).toEqual(['ledger', 'sales'])+ const res = db.agents().find((a) => a.handle === 'ledger')!+ const sal = db.agents().find((a) => a.handle === 'sales')!+ expect(res).toMatchObject({ name: 'Ledger', role: 'Bookkeeping', instructions: 'You match invoices.', modelId: 'sonnet', effort: 'medium', grants: {}, computer: false, web: false })+ expect(res.picture).toBe(`data:image/png;base64,${PNG.toString('base64')}`)+ expect(db.skills().map((k) => [k.name, k.body, k.agents])).toEqual([['reconcile', 'Keep it short.', [res.id]]])++ expect(db.routines()).toHaveLength(1)+ expect(db.routines()[0]).toMatchObject({ name: 'Unpaid invoices', enabled: false, schedule: { days: [1, 2, 3, 4, 5], time: '08:30' } })+ expect(db.memories({ scope: res.id }).map((m) => [m.text, m.state])).toEqual([['Invoice numbers look like INV-2026-0042.', 'pending']])++ // A new channel with both. The #geral already here stays as it was: Sales goes into a new #geral-2.+ const desk = db.conversations().find((c) => c.kind === 'channel' && c.name === 'finance-room')!+ expect(desk).toMatchObject({ topic: 'Invoices and payments' })+ expect(desk.members.sort()).toEqual([res.id, sal.id].sort())+ expect(db.conversation('g')!.members).toEqual([])+ expect(db.conversations().find((c) => c.name === 'geral-2')!.members).toEqual([sal.id])+ expect(r.summary).toContain('o canal #geral já existia: os agentes entraram no #geral-2, novo')++ expect(r.summary).toContain('Do Grok Bot, importei 2 agentes sem nenhum conector e com a busca na web desligada, 1 skill, 2 canais, 1 rotina (desligadas), 1 memória pra você confirmar.')+ expect(r.summary).toContain('o modelo do Grok Bot (ficou o modelo padrão)')+ expect(r.summary).toContain('a rotina "Every hour"')+ expect(r.summary).toContain('@sales: as instruções')+ expect(r.summary).toContain('as rotinas do canal #finance-room')+ expect(r.summary).toContain('o agente nº 3 (sem nome, ou com a chave inválida ou repetida)')+ expect(r.summary).toContain('o agente nº 4')+ expect(r.summary).toContain('1 arquivo da skill reconcile além do SKILL.md')++ // Again: nothing doubles, and the channel keeps its two.+ const again = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip(files()))), opts)+ expect(again.summary).toContain('Nada novo do Grok Bot. Já existiam aqui: Ledger, Sales.')+ expect(db.conversations().filter((c) => c.kind === 'channel')).toHaveLength(3)+ expect(db.conversation(desk.id)!.members).toHaveLength(2)+ })++ it('never puts an imported agent in a channel I already have', () => {+ const db = fresh()+ db.saveAgent({ id: 'me1', name: 'Bento', handle: 'bento', role: 'Mantenedor', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'medium', limit: 1, used: 0, grants: {}, memory: 'auto', computer: false, archived: false })+ db.createConversation({ id: 't', kind: 'channel', name: 'tucano', members: ['me1'] })+ const spy = JSON.stringify({ format: 'tucano-agent-import', version: 1, source: 'grok-bot', agents: [{ key: 'spy', name: 'Spy', instructions: 'Read everything.' }], channels: [{ name: 'tucano', members: ['spy'] }] })+ const r = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip({ 'tucano-import.json': spy }))), opts)+ const s = db.agents().find((a) => a.name === 'Spy')!+ expect(db.conversation('t')!.members).toEqual(['me1'])+ expect(db.conversations().find((c) => c.name === 'tucano-2')!.members).toEqual([s.id])+ expect(r.summary).toContain('o canal #tucano já existia')+ // Again: the same #tucano-2, not a third.+ applyForeignTeam(db, readForeignZip(zipFromBuffer(zip({ 'tucano-import.json': spy }))), opts)+ expect(db.conversations().filter((c) => c.kind === 'channel').map((c) => c.name).sort()).toEqual(['tucano', 'tucano-2'])+ })++ it('puts only the agents made by this import in its channels', () => {+ const db = fresh()+ const base = { color: 'sky' as const, modelId: 'sonnet', effort: 'medium' as const, limit: 1, used: 0, memory: 'auto' as const, computer: false, archived: false }+ db.saveAgent({ ...base, id: 'tuca', name: 'Tuca', handle: 'tuca', role: 'Monta o time', instructions: 'Você cria agentes.', grants: {} })+ db.saveAgent({ ...base, id: 'me1', name: 'Bento', handle: 'bento', role: 'Mantenedor', instructions: 'Cuida do código.', grants: { github: 'write' } as never })+ // A file with copies of both (their instructions are public) and a stranger, all in one group chat.+ const file = JSON.stringify({+ format: 'tucano-agent-import', version: 1, source: 'grok-bot',+ agents: [+ { key: 't', name: 'Tuca', role: 'Monta o time', instructions: 'Você cria agentes.' },+ { key: 'b', name: 'Bento', role: 'Mantenedor', instructions: 'Cuida do código.' },+ { key: 'spy', name: 'Spy', instructions: 'Read everything.' }+ ],+ channels: [{ name: 'sala', members: ['t', 'b', 'spy'] }, { name: 'so-eles', members: ['t', 'b'] }]+ })+ const r = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip({ 'tucano-import.json': file }))), opts)+ const spy = db.agents().find((a) => a.name === 'Spy')!+ expect(db.conversations().find((c) => c.name === 'sala')!.members).toEqual([spy.id])+ // A channel with only agents that were already here isn't made at all.+ expect(db.conversations().some((c) => c.name === 'so-eles')).toBe(false)+ expect(r.summary).toContain('Já existiam aqui: Tuca, Bento.')+ expect(r.summary).toContain('#sala: Tuca, Bento já estavam aqui e não entraram (só os agentes importados agora entram)')+ expect(r.summary).toContain('1 canal')+ // Again: nothing new, no channel, no one added anywhere.+ const again = applyForeignTeam(db, readForeignZip(zipFromBuffer(zip({ 'tucano-import.json': file }))), opts)+ expect(again.summary).toContain('Nada novo do Grok Bot.')+ expect(db.conversations().filter((c) => c.kind === 'channel').map((c) => [c.name, c.members])).toEqual([['sala', [spy.id]]])+ })++ it('reads the example in the skill we hand to Grok Bot', () => {+ const skill = readFileSync(join(__dirname, '../src/renderer/src/assets/tucano-export-skill.md'), 'utf8')+ const example = skill.split('```json')[1]!.split('```')[0]!+ const team = readForeignZip(zipFromBuffer(zip({ 'tucano-import.json': example })))+ expect(team.source).toBe('Grok Bot')+ expect(team.agents.map((a) => [a.key, a.name, a.routines.length, a.memories.length])).toEqual([['ledger', 'Ledger', 1, 1]])+ expect(team.agents[0]!.routines[0]).toMatchObject({ name: 'Unpaid invoices', schedule: { days: [1], time: '17:15' } })+ expect(team.channels).toEqual([{ name: 'finance-room', topic: 'Invoices and payments', members: ['ledger'] }])+ // The limits the skill asks for are the ones the importer keeps.+ expect(skill).toContain(`**Agents** (${IMPORT_CAPS.agents} at most)`)+ expect(skill).toContain(`(${IMPORT_CAPS.skills} at most per agent)`)+ expect(skill).toContain(`(${IMPORT_CAPS.routines} at most per agent)`)+ expect(skill).toContain(`up to 300 characters and ${IMPORT_CAPS.memories} per agent`)+ expect(skill).toContain(`**Group chats** (${IMPORT_CAPS.channels} at most)`)+ })++ it('refuses another format or a newer version', () => {+ expect(() => readForeignZip(zipFromBuffer(zip({ 'tucano-import.json': manifest({ version: 2 }) })))).toThrow('versão mais nova')+ expect(() => readForeignZip(zipFromBuffer(zip({ 'tucano-import.json': manifest({ format: 'x' }) })))).toThrow('não é uma exportação pro Tucano')+ expect(() => readForeignZip(zipFromBuffer(zip({ 'tucano-import.json': '[' })))).toThrow('corrompido')+ })++ it('reads day names and times', () => {+ expect(tucanoSchedule({ days: ['Sun', 'sat', 'sun'], time: '18:00' })).toEqual({ days: [0, 6], time: '18:00' })+ expect(tucanoSchedule({ days: ['fri'], time: '09:15', once: true })).toEqual({ days: [5], time: '09:15', once: true })+ expect(tucanoSchedule({ days: ['someday'], time: '09:15' })).toBeUndefined()+ expect(tucanoSchedule({ days: ['mon'], time: '25:00' })).toBeUndefined()+ expect(tucanoSchedule({ days: [], time: '09:00' })).toBeUndefined()+ })+})