Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: import bots from Grok Bot and other apps' exports

leepokai55a73740ae22
diff --git a/README.md b/README.md
index b799bbfd..137badf3 100644
--- a/README.md
+++ b/README.md
@@ -163,6 +163,7 @@ and computer identity; do not use **Reset all data**, a cleanup utility, or Home
| `codync-host install` / `uninstall` | background service (launchd on macOS, systemd `--user` on Linux, the sign-in Run key on Windows) |
| `codync-host tui [--url … --token …]` | message your bots from a terminal (this computer by default; SSH-friendly) |
| `codync-host send --bot <id-or-name> [--wait] [--json] <text>...` | send from a script, optionally waiting for the final reply |
+| `codync-host import <file> [--dry-run] [--only a,b] [--skill]` | import bots from another app's export file; `--skill` prints the skill that writes one |
| `codync-host pair [--json]` | pairing QR code / link |
| `codync-host status` | installed? running? |
| `codync-host serve [--port 19222]` | run in the foreground |
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 333d492a..3fb4af0b 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -3,7 +3,7 @@ import { registerAppearance } from './appearance'
import { execFileSync } from 'node:child_process'
import { hostname } from 'node:os'
import { join } from 'node:path'
-import { app, autoUpdater, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeTheme, session, shell } from 'electron'
+import { app, autoUpdater, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeTheme, session, shell, type IpcMainInvokeEvent, type OpenDialogOptions } from 'electron'
import type { HostSnapshot, WindowCommand } from '../shared/ipc'
import { devPort, HostController } from './host-controller'
import { registerFileSaves } from './file-saves'
@@ -175,12 +175,13 @@ function registerIPC(tray: Tray) {
})
ipcMain.on('app:copy', (_e, text: string) => clipboard.writeText(text))
ipcMain.handle('app:pickFiles', async (e) => {
- const window = BrowserWindow.fromWebContents(e.sender)
- const result = window
- ? await dialog.showOpenDialog(window, { properties: ['openFile', 'multiSelections'] })
- : await dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] })
+ const result = await openDialog(e, { properties: ['openFile', 'multiSelections'] })
return result.canceled ? [] : readFiles(result.filePaths)
})
+ ipcMain.handle('app:pickExport', async (e) => {
+ const result = await openDialog(e, { defaultPath: app.getPath('downloads'), properties: ['openFile'], filters: [{ name: 'Bot export', extensions: ['zip'] }] })
+ return result.canceled ? null : (result.filePaths[0] ?? null)
+ })
ipcMain.handle('app:clipboardFiles', () => readClipboardFiles())
ipcMain.on('app:traySummary', (_e, summary) => tray.update(summary))
ipcMain.handle('app:showInDock', () => showInDock())
@@ -209,6 +210,12 @@ function registerIPC(tray: Tray) {
})
}
+/** An open panel on the window that asked (a sheet on macOS), or a free one when it has none. */
+function openDialog(e: IpcMainInvokeEvent, options: OpenDialogOptions) {
+ const window = BrowserWindow.fromWebContents(e.sender)
+ return window ? dialog.showOpenDialog(window, options) : dialog.showOpenDialog(options)
+}
+
if (yieldsToInstall()) {
app.exit(0)
} else if (!app.requestSingleInstanceLock()) {
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 04ea45dd..b8ae69b3 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -134,6 +134,7 @@ const bridge: CodyncBridge = {
openExternal: (url) => ipcRenderer.send('app:openExternal', url),
copy: (text) => ipcRenderer.send('app:copy', text),
pickFiles: () => ipcRenderer.invoke('app:pickFiles'),
+ pickExport: () => ipcRenderer.invoke('app:pickExport'),
readClipboardFiles: () => ipcRenderer.invoke('app:clipboardFiles'),
setTraySummary: (summary: TraySummary) => ipcRenderer.send('app:traySummary', summary),
onCommand: (cb: (c: WindowCommand) => void) => listen('app:command', cb),
diff --git a/apps/desktop/src/renderer/components/icon-fallbacks.ts b/apps/desktop/src/renderer/components/icon-fallbacks.ts
index b8fb6297..7ea1528c 100644
--- a/apps/desktop/src/renderer/components/icon-fallbacks.ts
+++ b/apps/desktop/src/renderer/components/icon-fallbacks.ts
@@ -162,6 +162,7 @@ const map: Record<string, IconNode> = {
'speaker.slash.fill': L.VolumeX,
'speaker.wave.2': L.Volume2,
'speaker.wave.2.fill': L.Volume2,
+ 'square.and.arrow.down': L.Import,
'square.and.arrow.up': L.Share,
'square.and.pencil': L.SquarePen,
'square.grid.2x2': L.LayoutGrid,
diff --git a/apps/desktop/src/renderer/components/symbols.json b/apps/desktop/src/renderer/components/symbols.json
index cd84f19d..0b6aa42d 100644
--- a/apps/desktop/src/renderer/components/symbols.json
+++ b/apps/desktop/src/renderer/components/symbols.json
@@ -140,6 +140,7 @@
"speaker.slash.fill",
"speaker.wave.2",
"speaker.wave.2.fill",
+"square.and.arrow.down",
"square.and.arrow.up",
"square.and.pencil",
"square.grid.2x2",
diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.ts
index fab51f19..2f2a6460 100644
--- a/apps/desktop/src/renderer/demo/bridge.ts
+++ b/apps/desktop/src/renderer/demo/bridge.ts
@@ -99,6 +99,7 @@ const bridge: CodyncBridge = {
openExternal: (url) => void window.open(url, '_blank', 'noopener'),
copy: (text) => void navigator.clipboard?.writeText(text).catch(() => {}),
pickFiles: async () => [],
+ pickExport: async () => null,
readClipboardFiles: async () => [],
setTraySummary() {},
onCommand: none,
diff --git a/apps/desktop/src/renderer/store/bot-import.ts b/apps/desktop/src/renderer/store/bot-import.ts
new file mode 100644
index 00000000..3d86d4e7
--- /dev/null
+++ b/apps/desktop/src/renderer/store/bot-import.ts
@@ -0,0 +1,97 @@
+import { Observable } from '../lib/observable'
+import type { BotStore } from './bot-store'
+
+/** What an export file holds, as the host reads it (`previewImport`). */
+export interface ImportPlan {
+ source: string
+ bots: { key: string; name: string; description: string; skills: string[]; routines: unknown[]; memories: string[]; files: string | null }[]
+ groups: { key: string; name: string; members: string[] }[]
+ warnings: string[]
+}
+
+export interface ImportResult {
+ bots: { key: string; id: string; name: string; skills: number; routines: number; memories: number; files: number }[]
+ groups: { key: string; id: string; name: string }[]
+ warnings: string[]
+}
+
+export type ImportStep =
+ | { kind: 'start' }
+ | { kind: 'review'; path: string; plan: ImportPlan; skipped: string[] }
+ | { kind: 'done'; result: ImportResult }
+
+/** Bringing bots over from another app's export file on this computer (the host's `import`). */
+export class BotImport extends Observable {
+ step: ImportStep = { kind: 'start' }
+ /** Bot and group keys left out by the user. */
+ off = new Set<string>()
+ busy = false
+ copied = false
+ error: string | null = null
+
+ constructor(private store: BotStore) { super() }
+
+ /** The skill that writes the export in Grok Bot, on the clipboard. */
+ async copySkill() {
+ await this.run(async () => {
+ const { text } = await (await this.store.ready()).call<{ text: string }>('importSkill', {})
+ window.codync.app.copy(text)
+ this.copied = true
+ })
+ }
+
+ async choose() {
+ const path = await window.codync.app.pickExport()
+ if (!path) return
+ await this.run(async () => {
+ const read = await (await this.store.ready()).call<{ plan: ImportPlan; skipped: string[] }>('previewImport', { path }, 120_000)
+ this.off = new Set()
+ this.step = { kind: 'review', path, ...read }
+ })
+ }
+
+ picked(key: string) {
+ return !this.off.has(key)
+ }
+
+ toggle(key: string) {
+ if (this.off.has(key)) this.off.delete(key)
+ else this.off.add(key)
+ this.changed()
+ }
+
+ /** A group can come along only with one of its bots. */
+ groupAvailable(members: string[]) {
+ return members.some((key) => this.picked(key))
+ }
+
+ get canImport() {
+ return this.step.kind === 'review' && this.step.plan.bots.some((b) => this.picked(b.key)) && !this.busy
+ }
+
+ async importPicked() {
+ const step = this.step
+ if (step.kind !== 'review' || !this.canImport) return
+ const bots = step.plan.bots.map((b) => b.key).filter((k) => this.picked(k))
+ const groups = step.plan.groups.filter((g) => this.picked(g.key) && this.groupAvailable(g.members)).map((g) => g.key)
+ await this.run(async () => {
+ const result = await (await this.store.ready()).call<ImportResult>('importBots', { path: step.path, bots, groups }, 600_000)
+ this.step = { kind: 'done', result }
+ })
+ }
+
+ private async run(work: () => Promise<void>) {
+ if (this.busy) return
+ this.busy = true
+ this.error = null
+ this.changed()
+ try {
+ await work()
+ } catch (e) {
+ this.error = e instanceof Error ? e.message : String(e)
+ } finally {
+ this.busy = false
+ this.changed()
+ }
+ }
+}
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 49aaa640..177883ca 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -23,6 +23,7 @@ import { ComputerFilterHeader, computerSelection } from './ComputerFilterHeader'
import { ThreadView } from './thread/ThreadView'
import { queueVoiceKey } from './thread/voice-shortcut-keys'
import { NewBotView, NewGroupView } from './bots/NewBotView'
+import { ImportBotsSheet } from './bots/ImportBotsView'
import { BotEditorView } from './bots/BotEditorView'
import { MarketplaceView } from './marketplace/MarketplaceView'
import { SettingsView, type SettingsPage } from './settings/SettingsView'
@@ -202,6 +203,7 @@ function ChatSplitView() {
const [hidden, setHidden] = usePref(prefs.hiddenComputers)
const [searching, setSearching] = useState(false)
const [creating, setCreating] = useState<CreateTarget | null>(null)
+ const [importing, setImporting] = useState(false)
const [newMenu, setNewMenu] = useState(false)
const [railNewMenu, setRailNewMenu] = useState(false)
const [context, setContext] = useState<{ items: ActionItem[]; x: number; y: number } | null>(null)
@@ -233,6 +235,7 @@ function ChatSplitView() {
const onlineStores = stores.filter((s) => shown.has(s.computer.id) && s.connection.kind === 'online' && !s.mismatch)
const selectedStore = app.selectedStore
const createStore = creating ? app.store(creating.computerId) : null
+ const localOnline = !!app.local && onlineStores.includes(app.local)
const roster = useComputerRoster(app, shown)
const visibleRoster = roster.items
@@ -268,6 +271,10 @@ function ChatSplitView() {
if (!onlineStores.length) return
debugOpened.current = true
create(target === 'newBot' ? 'bot' : 'group')
+ } else if (target === 'importBots') {
+ if (!localOnline) return
+ debugOpened.current = true
+ setImporting(true)
} else if (target === 'plugins') {
if (!app.local) return
debugOpened.current = true
@@ -286,6 +293,7 @@ function ChatSplitView() {
const newItems = (): MenuItem[] => [
{ title: 'New bot', icon: 'plus', action: () => create('bot') },
{ title: 'New group chat', icon: 'person.2', action: () => create('group') },
+ ...(localOnline ? [{ title: 'Import bots…', icon: 'square.and.arrow.down', action: () => setImporting(true) }] : []),
]
const openMarketplace = () => setMarketplace((selectedStore ?? app.local ?? onlineStores[0])?.computer.id ?? null)
@@ -464,6 +472,7 @@ function ChatSplitView() {
</StoreContext.Provider>
) : null}
</Sheet>
+ <ImportBotsSheet store={localOnline ? app.local : null} open={importing} onClose={() => setImporting(false)} maxHeight={sheetHeight} />
<Sheet open={marketplace !== null} onClose={() => setMarketplace(null)} width={Math.min(920, windowSize.width - 80)} height={sheetHeight} dismissOnDim>
{marketplace && app.store(marketplace) ? (
<StoreContext.Provider value={app.store(marketplace)!}>
diff --git a/apps/desktop/src/renderer/views/bots/ImportBotsView.tsx b/apps/desktop/src/renderer/views/bots/ImportBotsView.tsx
new file mode 100644
index 00000000..3460c605
--- /dev/null
+++ b/apps/desktop/src/renderer/views/bots/ImportBotsView.tsx
@@ -0,0 +1,143 @@
+import { useState } from 'react'
+import { BotImport, type ImportPlan, type ImportResult } from '../../store/bot-import'
+import type { BotStore } from '../../store/bot-store'
+import { StoreContext, useStore } from '../../store/context'
+import { useModel } from '../../lib/observable'
+import { useTr } from '../../lib/use-language'
+import { Button, CardForm, CardSection, RowLabel, Spinner, Switch } from '../../components/Controls'
+import { ModalHeader, Sheet, useDismiss } from '../../components/Overlay'
+import { HStack, Spacer, VStack } from '../../components/Stack'
+import { Text } from '../../components/Text'
+import './bots.css'
+
+/** The import as a sheet. `store` is this computer's host: the export file is on this computer, so its bots go there. */
+export function ImportBotsSheet({ store, open, onClose, maxHeight }: {
+ store: BotStore | null
+ open: boolean
+ onClose: () => void
+ maxHeight?: number
+}) {
+ return (
+ <Sheet open={open && !!store} onClose={onClose} maxHeight={maxHeight}>
+ {open && store ? (
+ <StoreContext.Provider value={store}>
+ <ImportBotsView />
+ </StoreContext.Provider>
+ ) : null}
+ </Sheet>
+ )
+}
+
+/** Bots from another app: the export steps, the bots and group chats in the file, then what came over. */
+function ImportBotsView() {
+ const store = useStore()
+ const [model] = useState(() => new BotImport(store))
+ useModel(model)
+ const step = model.step
+
+ return (
+ <VStack className="import-sheet">
+ <ModalHeader icon="square.and.arrow.down" title="Import bots" subtitle="Bring your agents over from Grok Bot" />
+ <VStack gap={16} className="import-body">
+ {step.kind === 'start' ? <Start model={model} /> : null}
+ {step.kind === 'review' ? <Review model={model} plan={step.plan} skipped={step.skipped} /> : null}
+ {step.kind === 'done' ? <Done result={step.result} /> : null}
+ {model.error ? <Text size="footnote" tone="danger" className="fade-in">{model.error}</Text> : null}
+ </VStack>
+ <Footer model={model} />
+ </VStack>
+ )
+}
+
+function Start({ model }: { model: BotImport }) {
+ const tr = useTr()
+ return (
+ <CardForm>
+ <CardSection title="How it works" footer="Chats aren’t copied: the export keeps what matters in them as memories. Exports other apps make from Grok Bot work too.">
+ <RowLabel label="1. Add the Codync export skill to an agent in Grok Bot" detail="Copy it, then paste it as a new skill or into the agent’s instructions." />
+ <RowLabel label={`2. ${tr(`Send it: “Export my agents for Codync”`)}`} detail="It saves one .zip file to Downloads." />
+ <RowLabel label="3. Choose that file here" detail="Read on this computer; nothing is uploaded." />
+ </CardSection>
+ <HStack gap={8}>
+ <Button kind="secondary" onClick={() => void model.copySkill()} disabled={model.busy}>{model.copied ? 'Copied' : 'Copy export skill'}</Button>
+ </HStack>
+ </CardForm>
+ )
+}
+
+function Review({ model, plan, skipped }: { model: BotImport; plan: ImportPlan; skipped: string[] }) {
+ const tr = useTr()
+ const notes = [...plan.warnings, ...skipped.map((path) => `${tr(`Left out`)} ${path}`)]
+ return (
+ <CardForm>
+ <CardSection title="Bots">
+ {plan.bots.map((bot) => (
+ <Switch key={bot.key} on={model.picked(bot.key)} onChange={() => model.toggle(bot.key)}>
+ <RowLabel label={bot.name} detail={summary(tr, bot.skills.length, bot.routines.length, bot.memories.length, bot.files !== null)} />
+ </Switch>
+ ))}
+ </CardSection>
+ {plan.groups.length ? (
+ <CardSection title="Group chats">
+ {plan.groups.map((group) => (
+ <Switch key={group.key} on={model.picked(group.key) && model.groupAvailable(group.members)} disabled={!model.groupAvailable(group.members)} onChange={() => model.toggle(group.key)}>
+ <RowLabel label={group.name} detail={members(plan, group.members)} />
+ </Switch>
+ ))}
+ </CardSection>
+ ) : null}
+ {notes.length ? (
+ <CardSection title="Notes">
+ {notes.map((note) => <Text key={note} size="caption" tone="secondary">{note}</Text>)}
+ </CardSection>
+ ) : null}
+ </CardForm>
+ )
+}
+
+function Done({ result }: { result: ImportResult }) {
+ const tr = useTr()
+ return (
+ <CardForm>
+ <CardSection title="Imported">
+ {result.bots.map((bot) => <RowLabel key={bot.id} label={bot.name} detail={summary(tr, bot.skills, bot.routines, bot.memories, bot.files > 0)} />)}
+ {result.groups.map((group) => <RowLabel key={group.id} label={group.name} detail="Group chat" />)}
+ </CardSection>
+ {result.warnings.length ? (
+ <CardSection title="Notes">
+ {result.warnings.map((note) => <Text key={note} size="caption" tone="secondary">{note}</Text>)}
+ </CardSection>
+ ) : null}
+ </CardForm>
+ )
+}
+
+function Footer({ model }: { model: BotImport }) {
+ const dismiss = useDismiss()
+ const step = model.step
+ return (
+ <HStack gap={8} className="create-footer">
+ {model.busy ? <Spinner /> : null}
+ <Spacer />
+ {step.kind === 'done' ? (
+ <Button onClick={dismiss}>Done</Button>
+ ) : (
+ <>
+ <Button kind="secondary" onClick={dismiss}>Cancel</Button>
+ {step.kind === 'start' ? <Button onClick={() => void model.choose()} disabled={model.busy}>Choose file…</Button> : null}
+ {step.kind === 'review' ? <Button onClick={() => void model.importPicked()} disabled={!model.canImport}>Import</Button> : null}
+ </>
+ )}
+ </HStack>
+ )
+}
+
+function summary(tr: (s: string) => string, skills: number, routines: number, memories: number, files: boolean) {
+ const parts = [`${skills} ${tr(`skills`)}`, `${routines} ${tr(`routines`)}`, `${memories} ${tr(`memories`)}`]
+ if (files) parts.push(tr(`workspace files`))
+ return parts.join(' · ')
+}
+
+function members(plan: ImportPlan, keys: string[]) {
+ return keys.map((key) => plan.bots.find((b) => b.key === key)?.name ?? key).join(', ')
+}
diff --git a/apps/desktop/src/renderer/views/bots/bots.css b/apps/desktop/src/renderer/views/bots/bots.css
index 3f514a36..3d99e1df 100644
--- a/apps/desktop/src/renderer/views/bots/bots.css
+++ b/apps/desktop/src/renderer/views/bots/bots.css
@@ -153,6 +153,16 @@ textarea.field-box {
.create-footer {
padding: 12px 20px 20px;
}
+.import-sheet {
+ width: 480px;
+ min-height: 0;
+}
+.import-body {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 4px 20px 8px;
+}
/* Folder levels slide in from the side they were opened toward. */
.level-slide {
diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.ts
index fb655ee5..4a6f9b84 100644
--- a/apps/desktop/src/shared/ipc.ts
+++ b/apps/desktop/src/shared/ipc.ts
@@ -248,6 +248,8 @@ export interface CodyncBridge {
copy(text: string): void
/** Files picked in the system dialog: name and bytes. */
pickFiles(): Promise<{ name: string; data: Uint8Array }[]>
+ /** A bot export (.zip) picked in the system dialog: its path on this computer, or null. */
+ pickExport(): Promise<string | null>
readClipboardFiles(): Promise<{ name: string; data: Uint8Array }[]>
setTraySummary(summary: TraySummary): void
onCommand(cb: (command: WindowCommand) => void): () => void
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index a32898c5..eb7d714d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1445,5 +1445,26 @@
"Enter folder path": "Enter folder path",
"Folder path": "Folder path",
"Paste an absolute path": "Paste an absolute path",
- "Go to folder": "Go to folder"
+ "Go to folder": "Go to folder",
+ "Import bots…": "Bots importieren…",
+ "Import bots": "Bots importieren",
+ "Bring your agents over from Grok Bot": "Hol deine Agenten aus Grok Bot",
+ "How it works": "So geht’s",
+ "Chats aren’t copied: the export keeps what matters in them as memories. Exports other apps make from Grok Bot work too.": "Chats werden nicht kopiert: Der Export behält das Wichtige daraus als Erinnerungen. Grok-Bot-Exporte anderer Apps funktionieren auch.",
+ "1. Add the Codync export skill to an agent in Grok Bot": "1. Füge einem Agenten in Grok Bot den Codync-Export-Skill hinzu",
+ "Copy it, then paste it as a new skill or into the agent’s instructions.": "Kopiere ihn und füge ihn als neuen Skill oder in die Anweisungen des Agenten ein.",
+ "Send it: “Export my agents for Codync”": "Sende ihm: „Export my agents for Codync“",
+ "It saves one .zip file to Downloads.": "Er speichert eine .zip-Datei in „Downloads“.",
+ "3. Choose that file here": "3. Wähle die Datei hier aus",
+ "Read on this computer; nothing is uploaded.": "Wird auf diesem Computer gelesen; nichts wird hochgeladen.",
+ "Copy export skill": "Export-Skill kopieren",
+ "Choose file…": "Datei auswählen…",
+ "Import": "Importieren",
+ "Group chats": "Gruppenchats",
+ "Imported": "Importiert",
+ "Left out": "Ausgelassen",
+ "skills": "Skills",
+ "routines": "Routinen",
+ "memories": "Erinnerungen",
+ "workspace files": "Arbeitsbereich-Dateien"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index 67e34832..8e741293 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1445,5 +1445,26 @@
"Enter folder path": "Enter folder path",
"Folder path": "Folder path",
"Paste an absolute path": "Paste an absolute path",
- "Go to folder": "Go to folder"
+ "Go to folder": "Go to folder",
+ "Import bots…": "Importar bots…",
+ "Import bots": "Importar bots",
+ "Bring your agents over from Grok Bot": "Trae tus agentes desde Grok Bot",
+ "How it works": "Cómo funciona",
+ "Chats aren’t copied: the export keeps what matters in them as memories. Exports other apps make from Grok Bot work too.": "Los chats no se copian: la exportación guarda lo importante como recuerdos. También sirven las exportaciones de Grok Bot de otras apps.",
+ "1. Add the Codync export skill to an agent in Grok Bot": "1. Añade la habilidad de exportación de Codync a un agente en Grok Bot",
+ "Copy it, then paste it as a new skill or into the agent’s instructions.": "Cópiala y pégala como nueva habilidad o en las instrucciones del agente.",
+ "Send it: “Export my agents for Codync”": "Envíale: «Export my agents for Codync»",
+ "It saves one .zip file to Downloads.": "Guarda un archivo .zip en Descargas.",
+ "3. Choose that file here": "3. Elige ese archivo aquí",
+ "Read on this computer; nothing is uploaded.": "Se lee en este ordenador; no se sube nada.",
+ "Copy export skill": "Copiar habilidad de exportación",
+ "Choose file…": "Elegir archivo…",
+ "Import": "Importar",
+ "Group chats": "Chats de grupo",
+ "Imported": "Importados",
+ "Left out": "Omitido",
+ "skills": "habilidades",
+ "routines": "rutinas",
+ "memories": "recuerdos",
+ "workspace files": "archivos del espacio de trabajo"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 28e36d8e..d8d38fc5 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1445,5 +1445,26 @@
"Enter folder path": "Enter folder path",
"Folder path": "Folder path",
"Paste an absolute path": "Paste an absolute path",
- "Go to folder": "Go to folder"
+ "Go to folder": "Go to folder",
+ "Import bots…": "Importer des bots…",
+ "Import bots": "Importer des bots",
+ "Bring your agents over from Grok Bot": "Transférez vos agents depuis Grok Bot",
+ "How it works": "Comment faire",
+ "Chats aren’t copied: the export keeps what matters in them as memories. Exports other apps make from Grok Bot work too.": "Les conversations ne sont pas copiées : l’export en garde l’essentiel sous forme de souvenirs. Les exports Grok Bot d’autres apps fonctionnent aussi.",
+ "1. Add the Codync export skill to an agent in Grok Bot": "1. Ajoutez la compétence d’export Codync à un agent dans Grok Bot",
+ "Copy it, then paste it as a new skill or into the agent’s instructions.": "Copiez-la, puis collez-la comme nouvelle compétence ou dans les instructions de l’agent.",
+ "Send it: “Export my agents for Codync”": "Envoyez-lui : « Export my agents for Codync »",
+ "It saves one .zip file to Downloads.": "Il enregistre un fichier .zip dans Téléchargements.",
+ "3. Choose that file here": "3. Choisissez ce fichier ici",
+ "Read on this computer; nothing is uploaded.": "Lu sur cet ordinateur ; rien n’est envoyé.",
+ "Copy export skill": "Copier la compétence d’export",
+ "Choose file…": "Choisir un fichier…",
+ "Import": "Importer",
+ "Group chats": "Discussions de groupe",
+ "Imported": "Importés",
+ "Left out": "Ignoré",
+ "skills": "compétences",
+ "routines": "routines",
+ "memories": "souvenirs",
+ "workspace files": "fichiers de l’espace de travail"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index eae4f1cd..4e74f005 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1445,5 +1445,26 @@
"Enter folder path": "Enter folder path",
"Folder path": "Folder path",
"Paste an absolute path": "Paste an absolute path",
- "Go to folder": "Go to folder"
+ "Go to folder": "Go to folder",
+ "Import bots…": "Bot をインポート…",
+ "Import bots": "Bot をインポート",
+ "Bring your agents over from Grok Bot": "Grok Bot のエージェントを移行",
+ "How it works": "手順",
+ "Chats aren’t copied: the export keeps what matters in them as memories. Exports other apps make from Grok Bot work too.": "チャットはコピーされません。大事な内容はメモリとして残ります。他のアプリが Grok Bot から書き出したファイルも使えます。",
+ "1. Add the Codync export skill to an agent in Grok Bot": "1. Grok Bot のエージェントに Codync エクスポートスキルを追加",
+ "Copy it, then paste it as a new skill or into the agent’s instructions.": "コピーして、新しいスキルかエージェントの指示に貼り付けます。",
+ "Send it: “Export my agents for Codync”": "送信:「Export my agents for Codync」",
+ "It saves one .zip file to Downloads.": "ダウンロードに .zip ファイルを 1 つ保存します。",
+ "3. Choose that file here": "3. そのファイルをここで選択",
+ "Read on this computer; nothing is uploaded.": "このコンピュータで読み込み、アップロードはしません。",
+ "Copy export skill": "エクスポートスキルをコピー",
+ "Choose file…": "ファイルを選択…",
+ "Import": "インポート",
+ "Group chats": "グループチャット",
+ "Imported": "インポート済み",
+ "Left out": "除外",
+ "skills": "スキル",
+ "routines": "ルーティン",
+ "memories": "メモリ",
+ "workspace files": "ワークスペースのファイル"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index aa00393b..9e82f173 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1445,5 +1445,26 @@
"Enter folder path": "Enter folder path",
"Folder path": "Folder path",
"Paste an absolute path": "Paste an absolute path",
- "Go to folder": "Go to folder"
+ "Go to folder": "Go to folder",
+ "Import bots…": "봇 가져오기…",
+ "Import bots": "봇 가져오기",
+ "Bring your agents over from Grok Bot": "Grok Bot의 에이전트 옮기기",
+ "How it works": "방법",
+ "Chats aren’t copied: the export keeps what matters in them as memories. Exports other apps make from Grok Bot work too.": "채팅은 복사되지 않으며, 중요한 내용은 기억으로 남습니다. 다른 앱이 Grok Bot에서 내보낸 파일도 사용할 수 있습니다.",
+ "1. Add the Codync export skill to an agent in Grok Bot": "1. Grok Bot 에이전트에 Codync 내보내기 스킬 추가",
+ "Copy it, then paste it as a new skill or into the agent’s instructions.": "복사해서 새 스킬이나 에이전트 지침에 붙여넣으세요.",
+ "Send it: “Export my agents for Codync”": "보내기: “Export my agents for Codync”",
+ "It saves one .zip file to Downloads.": "다운로드 폴더에 .zip 파일 하나를 저장합니다.",
+ "3. Choose that file here": "3. 여기서 그 파일 선택",
+ "Read on this computer; nothing is uploaded.": "이 컴퓨터에서 읽으며 업로드하지 않습니다.",
+ "Copy export skill": "내보내기 스킬 복사",
+ "Choose file…": "파일 선택…",
+ "Import": "가져오기",
+ "Group chats": "그룹 채팅",
+ "Imported": "가져옴",
+ "Left out": "제외됨",
+ "skills": "스킬",
+ "routines": "루틴",
+ "memories": "기억",
+ "workspace files": "작업 공간 파일"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index f8b29ec4..d898e1f6 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1445,5 +1445,26 @@
"Enter folder path": "Enter folder path",
"Folder path": "Folder path",
"Paste an absolute path": "Paste an absolute path",
- "Go to folder": "Go to folder"
+ "Go to folder": "Go to folder",
+ "Import bots…": "导入 Bot…",
+ "Import bots": "导入 Bot",
+ "Bring your agents over from Grok Bot": "把你在 Grok Bot 的 agent 搬过来",
+ "How it works": "怎么做",
+ "Chats aren’t copied: the export keeps what matters in them as memories. Exports other apps make from Grok Bot work too.": "对话不会复制过来:导出时会把重要内容整理成记忆。其他 App 从 Grok Bot 导出的文件也能用。",
+ "1. Add the Codync export skill to an agent in Grok Bot": "1. 在 Grok Bot 的一个 agent 加上 Codync 导出技能",
+ "Copy it, then paste it as a new skill or into the agent’s instructions.": "复制后贴成新技能,或贴进该 agent 的指示。",
+ "Send it: “Export my agents for Codync”": "发给它:「Export my agents for Codync」",
+ "It saves one .zip file to Downloads.": "它会在“下载”里存一个 .zip 文件。",
+ "3. Choose that file here": "3. 在这里选择那个文件",
+ "Read on this computer; nothing is uploaded.": "只在这台电脑读取,不会上传。",
+ "Copy export skill": "复制导出技能",
+ "Choose file…": "选择文件…",
+ "Import": "导入",
+ "Group chats": "群聊",
+ "Imported": "已导入",
+ "Left out": "已略过",
+ "skills": "个技能",
+ "routines": "个例行任务",
+ "memories": "条记忆",
+ "workspace files": "工作区文件"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index eb65595c..b13cf5e8 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1445,5 +1445,26 @@
"PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.": "PNG、JPEG、WebP 最大 5 MiB;SVG 最大 256 KiB。",
"Saved immediately. Custom images stay still.": "立即儲存。自訂圖片維持靜態。",
"Sign in required": "需要登入",
- "Sign in to use custom images.": "使用自訂圖片需要登入帳號。"
+ "Sign in to use custom images.": "使用自訂圖片需要登入帳號。",
+ "Import bots…": "匯入 Bot…",
+ "Import bots": "匯入 Bot",
+ "Bring your agents over from Grok Bot": "把你在 Grok Bot 的 agent 搬過來",
+ "How it works": "怎麼做",
+ "Chats aren’t copied: the export keeps what matters in them as memories. Exports other apps make from Grok Bot work too.": "對話不會複製過來:匯出時會把重要內容整理成記憶。其他 App 從 Grok Bot 匯出的檔案也能用。",
+ "1. Add the Codync export skill to an agent in Grok Bot": "1. 在 Grok Bot 的一個 agent 加上 Codync 匯出技能",
+ "Copy it, then paste it as a new skill or into the agent’s instructions.": "複製後貼成新技能,或貼進該 agent 的指示。",
+ "Send it: “Export my agents for Codync”": "傳給它:「Export my agents for Codync」",
+ "It saves one .zip file to Downloads.": "它會在「下載項目」存一個 .zip 檔。",
+ "3. Choose that file here": "3. 在這裡選擇那個檔案",
+ "Read on this computer; nothing is uploaded.": "只在這台電腦讀取,不會上傳。",
+ "Copy export skill": "複製匯出技能",
+ "Choose file…": "選擇檔案…",
+ "Import": "匯入",
+ "Group chats": "群組聊天",
+ "Imported": "已匯入",
+ "Left out": "已略過",
+ "skills": "個技能",
+ "routines": "個例行任務",
+ "memories": "則記憶",
+ "workspace files": "工作區檔案"
}
diff --git a/docs/README.md b/docs/README.md
index 61300948..da8f0dd8 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -39,6 +39,7 @@ Source review, a passing build, local integration tests and production acceptanc
- [Bot memory and compaction](design/bot-memory.md) (design; storage, gate and dreaming built, compaction to come)
- [Bot memory research](design/bot-memory-research.md) (files vs. database, embeddings, open-source systems, harness instructions)
- [Bot workspaces](features/bot-workspaces.md)
+- [Bot import](features/bot-import.md) (agents from a Grok Bot export file become bots)
- [Agent fallbacks](features/agent-fallback.md) (the next agent carries a turn on when the bot's own runs out of usage)
- [Routines](features/routines.md)
- [Voice calls](features/voice-call.md)
diff --git a/docs/features/bot-import.md b/docs/features/bot-import.md
new file mode 100644
index 00000000..fce62ed5
--- /dev/null
+++ b/docs/features/bot-import.md
@@ -0,0 +1,62 @@
+# Bot import
+
+People coming from Grok Bot (or from an app that already imported their Grok Bot agents) bring their agents
+over in one step: an export file (`.zip`) on this computer becomes bots and group chats with their
+instructions, avatars, skills, routines, memories and workspace files. Chats aren't copied; the export
+keeps what matters in them as memories.
+
+## Flow
+
+1. The user adds the export skill to an agent in Grok Bot. The skill is `host/src/import/export-skill.md`
+ (`EXPORT_SKILL`); the desktop app copies it (**+ → Import bots… → Copy export skill**, host method
+ `importSkill`) and `codync-host import --skill` prints it.
+2. They ask that agent "Export my agents for Codync". It writes `~/Downloads/codync-export-<date>.zip`.
+3. They choose the file: desktop **+ → Import bots…** (`app:pickExport` opens the dialog in the main
+ process and returns a path), or `codync-host import <file>` (`--dry-run` lists it, `--only a,b` picks
+ agents). Both call `previewImport` then `importBots` with the path; both methods are loopback only
+ (`LOCAL_ONLY`), since the path is on this computer.
+
+Phones and the terminal UI have no import screen: the export file is on the computer, and the CLI covers
+the terminal.
+
+## Formats (`host/src/import/manifest.rs`)
+
+| Manifest | `format` | Written by |
+| --- | --- | --- |
+| `codync-import.json` | `codync-bot-import` | Codync's export skill |
+| `openbot-import.json` | `openbot-agent-import` | Other apps' Grok Bot export agents |
+| `openbot-transfer.json` | `openbot-instance-transfer` | Those apps' own transfer files (agents, memories, sections) |
+
+The three share one shape (agents with `key`, `name`, `title`, `description`, `avatar`, `skills`,
+`routines`, `memories`, `files`; optional `channels`). `version` above 1 is refused. A manifest inside one
+top-level folder is found too. An agent, group or routine that doesn't check out is left out with a
+warning; the rest imports.
+
+## What each part becomes (`host/src/import/mod.rs`)
+
+- **Bot**: `createBot` with defaults; `description` = title, then instructions. A transfer file's
+ `provider` is kept when that agent runs on this computer, else the bot gets the default agent and a
+ warning; its model isn't (other apps' model ids aren't ACP ids).
+ Colors and shapes cycle through the avatar choices.
+- **Avatar**: `setIcon` for `bot:<id>`; needs the computer signed in, else a warning and the default face.
+- **Skills**: each folder becomes a skill of that bot's own (`add_custom_skill` written by the bot, on for
+ it only), with the folder's other files beside `SKILL.md`.
+- **Routines**: schedules map to cron, interval or one-time triggers (`schedule.rs`) in the routine's time
+ zone (else this computer's).
+- **Memories**: into the bot's `MEMORY.md` as imported facts, through the same path as the old memory move
+ (`chat::memory::add_facts`): checked, capped, the rest into `earlier.md`. The count reported is what was
+ written.
+- **Workspace files**: copied to `imported/` in the bot's workspace.
+- **Group chats**: a group of the imported members; its routines and memories go to its lead (or first
+ member), since Codync keeps them per bot. A group whose bots already share one (two channels of the same
+ members, or one the user made) isn't made again: a warning says it joins that group.
+
+A bot whose skills or files fail is deleted again with the skills and `imported/` files it got; the others
+carry on. Import counts as `bots_imported` in analytics (source and counts only).
+
+## Safety (`host/src/import/archive.rs`)
+
+Entries are listed before anything is read: at most 5,000 entries and 500 MB inflated. Paths that leave the
+archive and links are skipped; so are `.env*`, `*private*key*`, nested archives, `.git` and `node_modules`
+(reported back), and Mac zip noise (silently). Every manifest path of an agent must sit in
+`agents/<key>/`, and keys are lowercase letters, digits and hyphens.
diff --git a/docs/guides/user-docs.md b/docs/guides/user-docs.md
index 2a40ff75..3cf39254 100644
--- a/docs/guides/user-docs.md
+++ b/docs/guides/user-docs.md
@@ -18,7 +18,7 @@ the change.
| Page | Covers | Sources |
| --- | --- | --- |
| `getting-started` | Install, pair, first bot | `README.md`, [updates](updates.md), [dev app](dev-app.md) for names only |
-| `bots` | Creating, settings, workspaces, hiding, permissions, new session | [bot workspaces](../features/bot-workspaces.md), [conversation runtime](../architecture/conversation-runtime.md) |
+| `bots` | Creating, settings, workspaces, hiding, permissions, new session, importing from Grok Bot | [bot workspaces](../features/bot-workspaces.md), [conversation runtime](../architecture/conversation-runtime.md), [bot import](../features/bot-import.md) |
| `agents` | Known agents, registry, custom command, Extensions, sign-in, models | [extensions](../features/marketplace.md), `host/src/agent/backends.rs` |
| `conversations` | Messages, files, approval cards, stop, replies, reactions, commands, fresh conversations, notifications, sending from a script (`codync-host send`) | `README.md` (`codync-host send`), [chat messages](../features/chat-messages.md), [file attachments](../features/file-attachments.md), [context and memory](../features/context-and-memory.md), [notifications](../design/push-and-live-activity.md) |
| `groups` | Group chats | [groups and replies](../features/groups-and-replies.md) |
diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.md
index f54f0646..c94d5f27 100644
--- a/docs/reference/analytics-events.md
+++ b/docs/reference/analytics-events.md
@@ -64,6 +64,7 @@ host answers and sends it once the host is up.
|---|---|---|---|
| `screen_viewed` | host `track` (desktop, TUI), iOS, Android | A screen, sheet or tab is shown | `screen` (see *Screens*) |
| `bot_created` | host | `createBot` | `kind` (`bot`/`group`), `agent`, `model` or `members` (count) |
+| `bots_imported` | host | `importBots` (bots it makes send no `bot_created`) | `source` (`grok-bot`/`openbot`/`other`), `bots`, `groups` (counts) |
| `bot_updated` | host | `updateBot` | `fields`: the settings that changed, as the bot config's own camelCase keys (`model`, `permission`, `pinned`, `section`, `modelOptions`, `fastMode`, …), never their values |
| `bots_reordered` | host | `reorderBots` | — |
| `section_renamed` | host | `renameSection` | `removed`: whether it removed the section (`to` empty or `null`); never the names |
diff --git a/host/Cargo.lock b/host/Cargo.lock
index f6def0c7..cf942c4d 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -781,6 +781,7 @@ dependencies = [
"windows-sys 0.61.2",
"x25519-dalek",
"zeroize",
+ "zip",
]
[[package]]
@@ -3109,6 +3110,18 @@ dependencies = [
"memoffset",
]
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases 0.2.2",
+ "libc",
+]
+
[[package]]
name = "noq"
version = "1.4.0"
@@ -5371,6 +5384,12 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "typed-path"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
+
[[package]]
name = "typenum"
version = "1.20.1"
@@ -6343,6 +6362,23 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "zip"
+version = "9.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f5b58784007ff6e5f280ec82c8596686a3b9b5dd5836c63288d4479f84728b9"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "getrandom 0.4.3",
+ "indexmap",
+ "memchr",
+ "nix 0.31.3",
+ "typed-path",
+ "windows-sys 0.61.2",
+ "zopfli",
+]
+
[[package]]
name = "zlib-rs"
version = "0.6.8"
@@ -6355,6 +6391,18 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+[[package]]
+name = "zopfli"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
+
[[package]]
name = "zune-core"
version = "0.5.3"
diff --git a/host/Cargo.toml b/host/Cargo.toml
index e7efda24..b4802f79 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -66,6 +66,7 @@ x25519-dalek = { version = "3.0.0", features = ["static_secrets"] }
zeroize = "1"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
resvg = { version = "0.49", default-features = false }
+zip = { version = "9.2.0", default-features = false, features = ["deflate"] }
[target.'cfg(target_os = "macos")'.dependencies]
keyring = { version = "3.6.3", features = ["apple-native"] }
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index 4f0278d1..b2173d5a 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -85,6 +85,7 @@ pub enum Event {
ScreenTakenOver,
ConnectorInstalled,
ConnectorsImported,
+ BotsImported,
ConnectorRemoved,
ConnectorSigninStarted,
SkillInstalled,
@@ -151,6 +152,7 @@ impl Event {
Self::ScreenTakenOver => "screen_taken_over",
Self::ConnectorInstalled => "connector_installed",
Self::ConnectorsImported => "connectors_imported",
+ Self::BotsImported => "bots_imported",
Self::ConnectorRemoved => "connector_removed",
Self::ConnectorSigninStarted => "connector_signin_started",
Self::SkillInstalled => "skill_installed",
diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rs
index 346ea0a5..ba3df2e8 100644
--- a/host/src/analytics/observe.rs
+++ b/host/src/analytics/observe.rs
@@ -126,6 +126,7 @@ fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<Eve
Event::ConnectorInstalled
}
"importConnectors" => Event::ConnectorsImported,
+ "importBots" => Event::BotsImported,
"removeConnector" => Event::ConnectorRemoved,
"connectorSignIn" => Event::ConnectorSigninStarted,
"installSkill" => {
@@ -202,7 +203,7 @@ pub fn observe_call(hub: &Hub, caller: &Caller, method: &str, b: &Value) -> Opti
Some((event, p))
}
-/// What only the answer tells: how many connectors an import added, whether a Composio app is
+/// What only the answer tells: how many connectors or bots an import added, whether a Composio app is
/// connected yet (its sign-in is polled until the connection is active), and whether a published
/// artifact's card went into its bot's chat. `None`: not an event.
pub fn answered(event: Event, mut p: Map<String, Value>, answer: &Value) -> Option<Map<String, Value>> {
@@ -210,6 +211,14 @@ pub fn answered(event: Event, mut p: Map<String, Value>, answer: &Value) -> Opti
Event::ConnectorsImported => {
p.insert("count".into(), answer["items"].as_array().map_or(0, Vec::len).into());
}
+ // The file names its app: only the ones Codync reads leave the computer.
+ Event::BotsImported => {
+ let source = answer["source"].as_str().filter(|s| matches!(*s, "grok-bot" | "openbot"));
+ p.insert("source".into(), source.unwrap_or("other").into());
+ for key in ["bots", "groups"] {
+ p.insert(key.into(), answer[key].as_array().map_or(0, Vec::len).into());
+ }
+ }
// A routine run, a room or a bot request gets no card (`card` says why).
Event::ArtifactPublished => {
p.insert("card".into(), answer["card"].is_null().into());
diff --git a/host/src/api/bots.rs b/host/src/api/bots.rs
index d84529df..c12aa05b 100644
--- a/host/src/api/bots.rs
+++ b/host/src/api/bots.rs
@@ -84,6 +84,10 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
let hub = hub.clone();
json!({"bot": tokio::task::spawn_blocking(move || hub.create_bot(cfg)).await??})
}
+ // Bots from another app's export file on this computer (`import`).
+ "previewImport" => crate::import::preview(&b).await?,
+ "importBots" => crate::import::apply(hub, &b).await?,
+ "importSkill" => json!({"name": "codync-export", "text": crate::import::EXPORT_SKILL}),
"updateBot" => {
let hub = hub.clone();
json!({"bot": tokio::task::spawn_blocking(move || hub.update_bot(&b)).await??})
diff --git a/host/src/api/devices.rs b/host/src/api/devices.rs
index abb372b8..1932d842 100644
--- a/host/src/api/devices.rs
+++ b/host/src/api/devices.rs
@@ -41,6 +41,9 @@ const LOCAL_ONLY: &[&str] = &[
"reportError",
// Voice keys are entered on the computer itself; phones only use them.
"setVoiceKey",
+ // An export file is a path on this computer.
+ "previewImport",
+ "importBots",
"pairing",
"computerCall",
"computerTools",
diff --git a/host/src/chat/memory/import.rs b/host/src/chat/memory/import.rs
index ed1c2425..0588d1b4 100644
--- a/host/src/chat/memory/import.rs
+++ b/host/src/chat/memory/import.rs
@@ -18,6 +18,9 @@ const NOTE_PREFIX: &str = "[note] ";
/// The note the facts that don't fit `MEMORY.md` go to.
const EARLIER: &str = "earlier.md";
+/// `earlier.md`'s description when Codync's own old memory starts it.
+const EARLIER_OLD: &str = "Older facts about the user from Codync's previous memory; read when one comes up";
+
/// A fact from the Engram or Markdown memory.
struct Old {
text: String,
@@ -90,7 +93,7 @@ fn move_entries(hub: &Hub) -> Result<()> {
if entry.active { active.push(entry.fact) } else { archived.push(entry.fact) }
}
for (layer, (active, archived)) in layers {
- move_in(hub, layer.as_deref(), active, archived)?;
+ move_in(hub, layer.as_deref(), active, archived, EARLIER_OLD)?;
}
hub.store.memory_write(|c, _, _| codync_mem::legacy::finish(c))?;
tracing::info!("moved the memory entries into files");
@@ -100,8 +103,8 @@ fn move_entries(hub: &Hub) -> Result<()> {
/// Writes facts into a layer's `MEMORY.md` as far as its cap allows, each with who wrote it, and the rest (with
/// `rest`, and any too long for one line) into `earlier.md`. Facts memory may not hold (secrets, planted
/// instructions, hidden characters) stay out. Facts a file already holds aren't written twice, so a move cut short
-/// can run again.
-fn move_in(hub: &Hub, layer: Option<&str>, facts: Vec<Fact>, rest: Vec<Fact>) -> Result<()> {
+/// can run again. `about` describes `earlier.md` when it's new. Returns how many facts it wrote.
+fn move_in(hub: &Hub, layer: Option<&str>, facts: Vec<Fact>, rest: Vec<Fact>, about: &str) -> Result<usize> {
let writer = Writer { author: Author::Imported, bot: None, cause: Cause::Edit, message: None };
let main = files::read(layer, MAIN)?;
let mut lines = main.clone().unwrap_or_default();
@@ -136,20 +139,29 @@ fn move_in(hub: &Hub, layer: Option<&str>, facts: Vec<Fact>, rest: Vec<Fact>) ->
Ok(())
})?;
}
+ let mut written = kept.len();
if !earlier.is_empty() {
let before = files::read(layer, EARLIER)?;
- let mut note = before.clone().unwrap_or_else(|| {
- "---\ndescription: Older facts about the user from Codync's previous memory; read when one comes up\n---\n"
- .to_owned()
- });
+ let mut note = before.clone().unwrap_or_else(|| format!("---\ndescription: {about}\n---\n"));
for fact in &earlier {
if !mf::facts(&note).iter().any(|f| f.eq_ignore_ascii_case(&fact.text)) {
note = format!("{note}- {}\n", fact.text);
+ written += 1;
}
}
files::write(hub, layer, EARLIER, Some(&note), before.as_deref().map(mf::hash).as_deref(), writer)?;
}
- Ok(())
+ Ok(written)
+}
+
+/// Facts brought from another app (`import`) into `bot`'s memory, the same way the old memory moved in.
+/// Returns how many it wrote: the checks refuse some, and a fact the bot already has isn't written again.
+pub fn add_facts(hub: &Hub, bot: &str, texts: &[String]) -> Result<usize> {
+ let at = crate::store::now_ms();
+ let fact =
+ |text: &String| Fact { text: text.clone(), author: Author::Imported, author_bot: None, message: None, at };
+ let about = "Older facts the bot brought from the app it was imported from; read when one comes up";
+ move_in(hub, Some(bot), texts.iter().map(fact).collect(), Vec::new(), about)
}
/// Old facts as one line each, without those the checks on what memory may say refuse.
@@ -174,7 +186,7 @@ fn import_bot(hub: &Hub, bot: &str, dir: &Path) -> Result<()> {
.into_iter()
.map(|old| Fact { text: old.text, author: Author::Imported, author_bot: None, message: None, at: old.at })
.collect();
- move_in(hub, Some(bot), facts, Vec::new())?;
+ move_in(hub, Some(bot), facts, Vec::new(), EARLIER_OLD)?;
// Dreaming starts from now: what came before is in the moved memory already.
super::dream::set_bookmark(store, bot, store.last_seq(bot))?;
store.kv_set(&marker, &count.to_string())?;
diff --git a/host/src/chat/memory/mod.rs b/host/src/chat/memory/mod.rs
index 344c7768..8775976c 100644
--- a/host/src/chat/memory/mod.rs
+++ b/host/src/chat/memory/mod.rs
@@ -16,7 +16,7 @@ pub mod turns;
pub use api::call;
pub use dates::ymd;
pub use dream::{DreamEvent, spawn_dreamer};
-pub use import::import_old_memory;
+pub use import::{add_facts, import_old_memory};
pub use tools::{INSTRUCTIONS, call as tool_call, tools};
use crate::hub::Hub;
diff --git a/host/src/cloud_cli.rs b/host/src/cloud_cli.rs
index f7adec13..060a8a84 100644
--- a/host/src/cloud_cli.rs
+++ b/host/src/cloud_cli.rs
@@ -1,6 +1,6 @@
//! `codync-host cloud`: the relay this computer uses, its registration token and account approval.
-use crate::local_call;
+use crate::local_api::local_call;
use anyhow::Result;
use serde_json::json;
diff --git a/host/src/import/archive.rs b/host/src/import/archive.rs
new file mode 100644
index 00000000..6b94cb4f
--- /dev/null
+++ b/host/src/import/archive.rs
@@ -0,0 +1,177 @@
+//! The export file: a zip whose entries are listed and checked before anything is read. Paths that leave the
+//! archive, links, secrets, nested archives and version-control or package folders are never extracted.
+
+use anyhow::{Context, Result, bail};
+use std::collections::BTreeMap;
+use std::fs::File;
+use std::io::Read as _;
+use std::ops::Bound;
+use std::path::{Component, Path};
+use zip::ZipArchive;
+
+/// More entries than this, or more bytes once inflated, and the file is refused.
+const MAX_ENTRIES: usize = 5_000;
+const MAX_BYTES: u64 = 500 * 1024 * 1024;
+
+pub struct Archive {
+ zip: ZipArchive<File>,
+ /// Each safe file's path (below the archive's root folder, if it has one) → its zip index and size.
+ files: BTreeMap<String, (usize, u64)>,
+ /// Entries left out because of what they are (a secret, a nested archive…).
+ pub skipped: Vec<String>,
+}
+
+impl Archive {
+ pub fn open(path: &Path) -> Result<Self> {
+ let file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
+ let mut zip = ZipArchive::new(file).context("this isn't a zip file")?;
+ if zip.len() > MAX_ENTRIES {
+ bail!("the file has more than {MAX_ENTRIES} entries");
+ }
+ let (mut files, mut skipped, mut total) = (BTreeMap::new(), Vec::new(), 0u64);
+ for index in 0..zip.len() {
+ let entry = zip.by_index(index)?;
+ if entry.is_dir() {
+ continue;
+ }
+ let name = entry.name()?.into_owned();
+ let Some(path) = entry.enclosed_name().filter(|_| !entry.is_symlink()) else {
+ skipped.push(name);
+ continue;
+ };
+ let path = path.to_string_lossy().replace('\\', "/");
+ if is_noise(&path) {
+ continue;
+ }
+ if is_refused(&path) {
+ skipped.push(path);
+ continue;
+ }
+ total = total.saturating_add(entry.size());
+ if total > MAX_BYTES {
+ bail!("the file holds more than 500 MB");
+ }
+ files.insert(path, (index, entry.size()));
+ }
+ Ok(Self { zip, files, skipped })
+ }
+
+ /// Whether the archive holds `manifest`; from then on every path is relative to the folder that holds it
+ /// (the root, or the one top-level folder an export zipped with its folder has).
+ pub fn rooted_at(&mut self, manifest: &str) -> bool {
+ if self.files.contains_key(manifest) {
+ return true;
+ }
+ let prefix =
+ self.files.keys().find_map(|p| p.strip_suffix(manifest).filter(|r| is_folder(r))).map(str::to_owned);
+ let Some(prefix) = prefix else { return false };
+ self.files = std::mem::take(&mut self.files)
+ .into_iter()
+ .filter_map(|(path, at)| path.strip_prefix(&prefix).map(|p| (p.to_owned(), at)))
+ .collect();
+ true
+ }
+
+ pub fn has(&self, path: &str) -> bool {
+ self.files.contains_key(path)
+ }
+
+ /// One file, at most `max` bytes.
+ pub fn read(&mut self, path: &str, max: u64) -> Result<Vec<u8>> {
+ let &(index, size) = self.files.get(path).with_context(|| format!("the file has no {path}"))?;
+ if size > max {
+ bail!("{path} is larger than {} KB", max / 1024);
+ }
+ let mut bytes = Vec::new();
+ self.zip.by_index(index)?.take(max + 1).read_to_end(&mut bytes)?;
+ if bytes.len() as u64 > max {
+ bail!("{path} is larger than {} KB", max / 1024);
+ }
+ Ok(bytes)
+ }
+
+ /// The paths of the files in folder `dir`, below it.
+ pub fn under(&self, dir: &str) -> Vec<String> {
+ let prefix = format!("{}/", dir.trim_end_matches('/'));
+ self.files.keys().filter_map(|p| p.strip_prefix(&prefix)).map(str::to_owned).collect()
+ }
+
+ /// Copies folder `dir` into `dest`, keeping the paths below it; returns how many files it copied.
+ pub fn extract(&mut self, dir: &str, dest: &Path) -> Result<usize> {
+ let prefix = format!("{}/", dir.trim_end_matches('/'));
+ let mut copied = 0;
+ let from = (Bound::Included(prefix.as_str()), Bound::Unbounded);
+ let below = self.files.range::<str, _>(from).take_while(|(path, _)| path.starts_with(&prefix));
+ for (path, &(index, size)) in below {
+ let target = dest.join(&path[prefix.len()..]);
+ if let Some(parent) = target.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let mut out = File::create(&target).with_context(|| format!("writing {}", target.display()))?;
+ let written = std::io::copy(&mut self.zip.by_index(index)?.take(size), &mut out)?;
+ if written != size {
+ bail!("{path} is cut short");
+ }
+ copied += 1;
+ }
+ Ok(copied)
+ }
+}
+
+/// `rest` (what's before a manifest's name) is one top-level folder.
+fn is_folder(rest: &str) -> bool {
+ rest.strip_suffix('/').is_some_and(|f| !f.is_empty() && !f.contains('/'))
+}
+
+/// What a Mac's zip adds, left out without a word.
+fn is_noise(path: &str) -> bool {
+ path.starts_with("__MACOSX/") || path.rsplit('/').next() == Some(".DS_Store")
+}
+
+/// Secrets, nested archives and version-control or package folders: never copied onto this computer.
+fn is_refused(path: &str) -> bool {
+ let parts: Vec<&str> = Path::new(path)
+ .components()
+ .filter_map(|c| match c {
+ Component::Normal(p) => p.to_str(),
+ _ => None,
+ })
+ .collect();
+ let file = parts.last().copied().unwrap_or_default().to_lowercase();
+ let archive = [".zip", ".tar", ".gz", ".tgz", ".7z", ".rar"].iter().any(|ext| file.ends_with(ext));
+ // Case-insensitive file systems (APFS, NTFS) treat `.GIT` as `.git`.
+ parts.iter().any(|p| p.eq_ignore_ascii_case(".git") || p.eq_ignore_ascii_case("node_modules"))
+ || file.starts_with(".env")
+ || (file.contains("private") && file.contains("key"))
+ || archive
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn secrets_and_nested_archives_are_refused() {
+ for path in [
+ "a/.env",
+ "a/.env.local",
+ "a/id_private_key",
+ "a/repo/.git/HEAD",
+ "a/.GIT/config",
+ "a/node_modules/x/i.js",
+ "a/b.zip",
+ ] {
+ assert!(is_refused(path), "{path}");
+ }
+ for path in ["a/notes.md", "a/keys.md", "a/environment.txt"] {
+ assert!(!is_refused(path), "{path}");
+ }
+ assert!(is_noise("__MACOSX/a/._b") && is_noise("a/.DS_Store"));
+ }
+
+ #[test]
+ fn a_manifest_in_one_folder_counts() {
+ assert!(is_folder("export/"));
+ assert!(!is_folder("") && !is_folder("a/b/") && !is_folder("export"));
+ }
+}
diff --git a/host/src/import/export-skill.md b/host/src/import/export-skill.md
new file mode 100644
index 00000000..4f947343
--- /dev/null
+++ b/host/src/import/export-skill.md
@@ -0,0 +1,132 @@
+---
+name: codync-export
+description: Pack the user's Grok Bot agents and group chats into one .zip file that Codync imports as bots, with their instructions, avatars, skills, scheduled tasks, memories and (if the user wants) workspace files. Use when the user asks to export, move or migrate their agents to Codync.
+---
+
+# Export agents for Codync
+
+You write one `.zip` file. The user opens it in Codync (**Settings → Import bots** in the desktop app, or
+`codync-host import <file>` in a terminal) on the same computer. Codync reads it there; nothing is uploaded.
+Codync checks the manifest strictly, so keep to the format below.
+
+## Steps
+
+1. **Collect.** For every agent the user has, gather its name, a one-line role, its full instructions, its
+ avatar image, its skills (each skill folder with `SKILL.md` and the files it uses) and its scheduled tasks
+ (name, prompt, schedule, time zone, on or off). Read its chats only to write memories (step 3). Gather
+ every group chat too: name, one-line topic, shared instructions, its agents (lead first) and its
+ scheduled tasks.
+
+ Leave out the agent running this skill and this skill itself (`codync-export`). If you can't read
+ something, say so to the user later; never make up its contents.
+
+2. **Ask.** Show the agents, the group chats and the size of the workspace files. Ask which agents and group
+ chats to export (default: all) and "Include workspace files? (yes / no)". Wait for the answer.
+
+3. **Memories.** From each agent's chats, write up to 50 facts it should keep: the user's preferences,
+ names, recurring work, decisions, open tasks. One short statement per fact ("The user reports in EUR."),
+ 500 characters at most, never a copied message, never a secret. Up to 32 facts per group chat.
+
+4. **No secrets.** Leave out `.env` files, keys, tokens, passwords and cookies, in files and in
+ instructions; in instructions write `<ask the user for …>` instead. Codync skips files named `.env*` or
+ `*private*key*`, nested archives (`.zip`, `.tar`, `.gz`, `.tgz`, `.7z`, `.rar`) and `.git` or
+ `node_modules` folders, so don't include them.
+
+5. **Write the folder** in the format below, `codync-import.json` last.
+
+6. **Zip** the folder's contents (the manifest at the root of the zip) to
+ `~/Downloads/.codync-export-<YYYY-MM-DD>.zip.part`, then rename it to
+ `~/Downloads/codync-export-<YYYY-MM-DD>.zip` so Codync never sees half a file.
+
+7. **Report** the file's path, how many agents and group chats it holds, and what you left out. Tell the
+ user to open Codync's **Settings → Import bots** and choose the file.
+
+## Format
+
+```
+codync-import.json
+agents/<key>/avatar.png optional; PNG, JPEG or WebP, 5 MB at most
+agents/<key>/skills/<skill>/SKILL.md one folder per skill, with the files it uses
+agents/<key>/files/… optional workspace files
+```
+
+`<key>` names one agent: lowercase letters, digits and hyphens, 64 characters at most, not starting or ending
+with a hyphen (`research`, `sales-outbound`). Every path of an agent starts with `agents/<key>/`.
+
+```json
+{
+ "format": "codync-bot-import",
+ "version": 1,
+ "source": { "app": "grok-bot", "exportedAt": "2026-10-31T10:00:00Z" },
+ "agents": [
+ {
+ "key": "research",
+ "name": "Research",
+ "title": "Market research analyst",
+ "description": "You find sources, compare competitors and write short cited briefs.",
+ "avatar": "agents/research/avatar.png",
+ "skills": ["agents/research/skills/web-brief"],
+ "routines": [
+ {
+ "name": "Morning digest",
+ "instruction": "Summarize yesterday's news about our competitors.",
+ "active": true,
+ "timezone": "Asia/Taipei",
+ "schedule": { "kind": "weekdays", "time": "08:30" }
+ }
+ ],
+ "memories": ["The user reports in EUR."],
+ "files": "agents/research/files"
+ }
+ ],
+ "channels": [
+ {
+ "key": "market-desk",
+ "name": "Market desk",
+ "title": "Weekly competitor review",
+ "instructions": "Research brings the news; Sales says what it means for open deals.",
+ "members": ["research", "sales"],
+ "lead": "research",
+ "routines": [],
+ "memories": ["The user wants actions, not summaries."]
+ }
+ ]
+}
+```
+
+- `name` (required, 80 characters at most) and `description` (required: the agent's full instructions) are
+ text; `title` is optional. Very long instructions can go in `agents/<key>/files/INSTRUCTIONS.md` with a
+ `description` that says to read `imported/INSTRUCTIONS.md`: Codync copies `files` to `imported/` in the
+ bot's workspace.
+- `avatar` and `files` are a path or `null`; `skills` lists skill folders, each with a `SKILL.md` that starts
+ with front matter holding `name` and `description`.
+- `routines`: up to 64 per agent; `timezone` is an IANA name. `memories`: plain strings.
+- `channels` is optional. Each `members` entry is the `key` of an agent in this file; `lead` is one of them
+ or `null`. A group chat's scheduled tasks and memories go to its lead in Codync.
+- The whole zip stays under 500 MB and 5,000 files.
+
+### Schedules
+
+Times are 24-hour `HH:MM` in the routine's time zone; weekdays run from 0 (Sunday) to 6 (Saturday).
+
+| Schedule | JSON |
+| --- | --- |
+| Hourly at minute 15 | `{ "kind": "hourly", "minute": 15 }` |
+| Every day | `{ "kind": "daily", "time": "09:00" }` |
+| Monday to Friday | `{ "kind": "weekdays", "time": "09:00" }` |
+| Every week | `{ "kind": "weekly", "weekday": 1, "time": "09:00" }` |
+| Every month | `{ "kind": "monthly", "day": 1, "time": "09:00" }` |
+| Every N minutes, hours or days | `{ "kind": "interval", "amount": 30, "unit": "minutes" }` |
+| Once | `{ "kind": "once", "date": "2026-12-01", "time": "09:00" }` |
+| Anything else | `{ "kind": "custom", "expression": "0 9 * * 1-5" }` (five-field cron) |
+
+Codync skips a routine whose schedule it can't read and tells the user; the agent still imports.
+
+## Before zipping
+
+- [ ] `codync-import.json` is at the zip's root, with `format` `codync-bot-import` and `version` `1`.
+- [ ] Keys are unique and every path starts with `agents/<key>/`.
+- [ ] Every skill folder has a `SKILL.md` with front matter; none is `codync-export`.
+- [ ] The agent running this skill isn't in the file.
+- [ ] Each group chat's `members` are agents in this file.
+- [ ] No secrets; workspace files only if the user said yes.
diff --git a/host/src/import/manifest.rs b/host/src/import/manifest.rs
new file mode 100644
index 00000000..13cefc5a
--- /dev/null
+++ b/host/src/import/manifest.rs
@@ -0,0 +1,319 @@
+//! The export's manifest, read into a [`Plan`]. Three formats share one shape: Codync's own
+//! (`codync-import.json`, written by the export skill), the agent export other apps import from Grok Bot
+//! (`openbot-import.json`) and those apps' own transfer file (`openbot-transfer.json`). A bot, group or
+//! routine that doesn't check out is left out with a warning; the rest still imports.
+
+use super::archive::Archive;
+use super::schedule;
+use crate::routines::Trigger;
+use anyhow::{Result, bail};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+/// Each manifest file and the `format` it must name.
+const FORMATS: [(&str, &str); 3] = [
+ ("codync-import.json", "codync-bot-import"),
+ ("openbot-import.json", "openbot-agent-import"),
+ ("openbot-transfer.json", "openbot-instance-transfer"),
+];
+const VERSION: u64 = 1;
+const MAX_MANIFEST: u64 = 8 * 1024 * 1024;
+const MAX_BOTS: usize = 200;
+const MAX_ROUTINES: usize = 64;
+const MAX_MEMORIES: usize = 512;
+const MAX_MEMORY_CHARS: usize = 2_000;
+
+#[derive(Serialize, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct Plan {
+ /// The app the agents come from, as the file names it (`grok-bot`…).
+ pub source: String,
+ pub bots: Vec<Bot>,
+ pub groups: Vec<Group>,
+ pub warnings: Vec<String>,
+}
+
+#[derive(Serialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct Bot {
+ pub key: String,
+ pub name: String,
+ /// The bot's description: its role, then its instructions.
+ pub description: String,
+ /// The agent it ran on, when Codync knows it (the import keeps it only if it runs on this computer).
+ pub backend: Option<String>,
+ pub avatar: Option<String>,
+ pub skills: Vec<String>,
+ pub routines: Vec<Routine>,
+ pub memories: Vec<String>,
+ /// The folder copied into its workspace as `imported/`.
+ pub files: Option<String>,
+ pub section: Option<String>,
+}
+
+#[derive(Serialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct Group {
+ pub key: String,
+ pub name: String,
+ pub description: String,
+ /// Bot keys; the lead first.
+ pub members: Vec<String>,
+ pub routines: Vec<Routine>,
+ pub memories: Vec<String>,
+}
+
+#[derive(Serialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct Routine {
+ pub name: String,
+ pub instruction: String,
+ pub enabled: bool,
+ pub triggers: Vec<Trigger>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct RawAgent {
+ key: String,
+ name: String,
+ #[serde(default)]
+ title: String,
+ #[serde(default)]
+ description: String,
+ #[serde(default)]
+ avatar: Option<String>,
+ #[serde(default)]
+ provider: Option<String>,
+ #[serde(default)]
+ skills: Vec<String>,
+ #[serde(default)]
+ routines: Vec<Value>,
+ #[serde(default)]
+ one_time_routines: Vec<Value>,
+ #[serde(default)]
+ memories: Vec<RawMemory>,
+ #[serde(default)]
+ files: Option<String>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct RawChannel {
+ key: String,
+ name: String,
+ #[serde(default)]
+ title: String,
+ #[serde(default)]
+ instructions: String,
+ members: Vec<String>,
+ #[serde(default)]
+ lead: Option<String>,
+ #[serde(default)]
+ routines: Vec<Value>,
+ #[serde(default)]
+ memories: Vec<RawMemory>,
+}
+
+/// A memory is a string in the agent export and `{text}` in the transfer file.
+#[derive(Deserialize)]
+#[serde(untagged)]
+enum RawMemory {
+ Text(String),
+ Item { text: String },
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct RawRoutine {
+ name: String,
+ instruction: String,
+ #[serde(default = "yes")]
+ active: bool,
+ #[serde(default)]
+ timezone: String,
+ schedule: Value,
+}
+
+fn yes() -> bool {
+ true
+}
+
+/// Reads whichever manifest `archive` holds (making its folder the root) and checks it.
+pub fn read(archive: &mut Archive, now: i64) -> Result<Plan> {
+ let Some((file, format)) = FORMATS.into_iter().find(|(file, _)| archive.rooted_at(file)) else {
+ bail!("this isn't a bot export: it has no codync-import.json");
+ };
+ let manifest: Value = serde_json::from_slice(&archive.read(file, MAX_MANIFEST)?)
+ .map_err(|e| anyhow::anyhow!("{file} isn't valid JSON: {e}"))?;
+ if manifest["format"] != format {
+ bail!("{file} names the format {}, not {format}", manifest["format"]);
+ }
+ if manifest["version"].as_u64().is_none_or(|v| v > VERSION) {
+ bail!("this export is from a newer version: update Codync to import it");
+ }
+ let mut plan = Plan {
+ source: manifest["source"]["app"]
+ .as_str()
+ .unwrap_or(if format == FORMATS[2].1 { "openbot" } else { "" })
+ .into(),
+ ..Plan::default()
+ };
+ let agents = manifest["agents"].as_array().map_or(&[][..], Vec::as_slice);
+ for raw in agents.iter().take(MAX_BOTS) {
+ match bot(archive, raw, now, &mut plan.warnings) {
+ Ok(bot) if plan.bots.iter().any(|b| b.key == bot.key) => {
+ plan.warnings.push(format!("Left out a second agent with the key {}", bot.key));
+ }
+ Ok(bot) => plan.bots.push(bot),
+ Err(e) => plan.warnings.push(format!("Left out the agent {}: {e:#}", label(raw))),
+ }
+ }
+ sections(&manifest["settings"]["sidebarSections"], &mut plan.bots);
+ for raw in manifest["channels"].as_array().into_iter().flatten().take(MAX_BOTS) {
+ match group(raw, &plan.bots, now, &mut plan.warnings) {
+ Ok(group) => plan.groups.push(group),
+ Err(e) => plan.warnings.push(format!("Left out the group chat {}: {e:#}", label(raw))),
+ }
+ }
+ if plan.bots.is_empty() {
+ bail!("the export has no agent Codync can import{}", first_warning(&plan.warnings));
+ }
+ Ok(plan)
+}
+
+fn first_warning(warnings: &[String]) -> String {
+ warnings.first().map(|w| format!(" ({w})")).unwrap_or_default()
+}
+
+fn label(raw: &Value) -> String {
+ raw["name"].as_str().or_else(|| raw["key"].as_str()).unwrap_or("without a name").to_owned()
+}
+
+fn bot(archive: &Archive, raw: &Value, now: i64, warnings: &mut Vec<String>) -> Result<Bot> {
+ let raw: RawAgent = serde_json::from_value(raw.clone())?;
+ let key = checked_key(&raw.key)?;
+ let name = one_line(&raw.name);
+ if name.is_empty() {
+ bail!("it has no name");
+ }
+ let own = |path: Option<String>, what: &str, warnings: &mut Vec<String>| {
+ let path = path.map(|p| p.trim_end_matches('/').to_owned()).filter(|p| !p.is_empty())?;
+ if path.starts_with(&format!("agents/{key}/")) {
+ Some(path)
+ } else {
+ warnings.push(format!("{name}: left out its {what} {path}, which isn't in its own folder"));
+ None
+ }
+ };
+ let avatar = own(raw.avatar, "avatar", warnings).filter(|p| archive.has(p));
+ let files = own(raw.files, "files", warnings).filter(|p| !archive.under(p).is_empty());
+ let mut skills = Vec::new();
+ for path in raw.skills {
+ let Some(path) = own(Some(path), "skill", warnings) else { continue };
+ if archive.has(&format!("{path}/SKILL.md")) {
+ skills.push(path);
+ } else {
+ warnings.push(format!("{name}: left out the skill {path}, which has no SKILL.md"));
+ }
+ }
+ let routines = raw.routines.iter().chain(&raw.one_time_routines);
+ Ok(Bot {
+ description: described(&raw.title, &raw.description),
+ backend: raw.provider.filter(|p| crate::agent::backends::is_known(p)),
+ avatar,
+ skills,
+ routines: routines.take(MAX_ROUTINES).filter_map(|r| routine(&name, r, now, warnings)).collect(),
+ memories: memories(raw.memories, MAX_MEMORIES),
+ files,
+ section: None,
+ key,
+ name,
+ })
+}
+
+fn group(raw: &Value, bots: &[Bot], now: i64, warnings: &mut Vec<String>) -> Result<Group> {
+ let raw: RawChannel = serde_json::from_value(raw.clone())?;
+ let key = checked_key(&raw.key)?;
+ let name = one_line(&raw.name);
+ if name.is_empty() {
+ bail!("it has no name");
+ }
+ let mut members: Vec<String> = Vec::new();
+ for member in raw.lead.iter().chain(&raw.members) {
+ if bots.iter().any(|b| &b.key == member) && !members.contains(member) {
+ members.push(member.clone());
+ }
+ }
+ if members.is_empty() {
+ bail!("none of its agents are in the export");
+ }
+ Ok(Group {
+ description: described(&raw.title, &raw.instructions),
+ routines: raw.routines.iter().take(MAX_ROUTINES).filter_map(|r| routine(&name, r, now, warnings)).collect(),
+ memories: memories(raw.memories, MAX_MEMORIES),
+ members,
+ key,
+ name,
+ })
+}
+
+/// A routine Codync can run, or a warning that says why it's left out.
+fn routine(owner: &str, raw: &Value, now: i64, warnings: &mut Vec<String>) -> Option<Routine> {
+ let parsed = serde_json::from_value::<RawRoutine>(raw.clone()).map_err(anyhow::Error::from).and_then(|r| {
+ let zone = Some(r.timezone.trim())
+ .filter(|z| z.parse::<chrono_tz::Tz>().is_ok())
+ .map_or_else(crate::routines::local_zone, str::to_owned);
+ let trigger = schedule::trigger(&r.schedule, &zone, now)?;
+ let (name, instruction) = (one_line(&r.name), r.instruction.trim().to_owned());
+ if name.is_empty() || instruction.is_empty() {
+ bail!("it has no name or instruction");
+ }
+ Ok(Routine { name, instruction, enabled: r.active, triggers: vec![trigger] })
+ });
+ parsed.map_err(|e| warnings.push(format!("{owner}: left out the routine {}: {e:#}", label(raw)))).ok()
+}
+
+/// The role, then the instructions.
+fn described(title: &str, instructions: &str) -> String {
+ [title.trim(), instructions.trim()].into_iter().filter(|t| !t.is_empty()).collect::<Vec<_>>().join("\n\n")
+}
+
+fn memories(raw: Vec<RawMemory>, max: usize) -> Vec<String> {
+ raw.into_iter()
+ .map(|m| match m {
+ RawMemory::Text(text) | RawMemory::Item { text } => one_line(&text),
+ })
+ .filter(|t| !t.is_empty() && t.chars().count() <= MAX_MEMORY_CHARS)
+ .take(max)
+ .collect()
+}
+
+/// The transfer file's sidebar sections, onto the bots they hold.
+fn sections(raw: &Value, bots: &mut [Bot]) {
+ for section in raw.as_array().into_iter().flatten() {
+ let name = one_line(section["name"].as_str().unwrap_or_default());
+ for key in section["agentKeys"].as_array().into_iter().flatten().filter_map(Value::as_str) {
+ if let Some(bot) = bots.iter_mut().find(|b| b.key == key).filter(|_| !name.is_empty()) {
+ bot.section = Some(name.clone());
+ }
+ }
+ }
+}
+
+/// Lowercase letters, digits and inner hyphens, at most 64: safe as a folder name in the archive's paths.
+fn checked_key(key: &str) -> Result<String> {
+ let ok = !key.is_empty()
+ && key.len() <= 64
+ && !key.starts_with('-')
+ && !key.ends_with('-')
+ && key.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
+ if !ok {
+ bail!("its key `{key}` isn't lowercase letters, digits and hyphens");
+ }
+ Ok(key.to_owned())
+}
+
+fn one_line(text: &str) -> String {
+ text.split_whitespace().collect::<Vec<_>>().join(" ")
+}
diff --git a/host/src/import/mod.rs b/host/src/import/mod.rs
new file mode 100644
index 00000000..777b1e8b
--- /dev/null
+++ b/host/src/import/mod.rs
@@ -0,0 +1,258 @@
+//! Bots from another app: an export file (zip) read on this computer and turned into bots and groups with
+//! their instructions, avatars, skills, routines, memory and workspace files. Chats aren't carried over; the
+//! export keeps what matters in them as memories. The export skill (`EXPORT_SKILL`) writes Codync's own format
+//! from Grok Bot; `manifest` also reads the exports other apps take from Grok Bot and their own transfer files.
+
+mod archive;
+mod manifest;
+mod schedule;
+#[cfg(test)]
+mod tests;
+
+use crate::hub::Hub;
+use crate::market::{self, Installed};
+use crate::store::{AVATAR_COLORS, AVATAR_SHAPES};
+use anyhow::{Context, Result, bail};
+use archive::Archive;
+use base64::Engine as _;
+use manifest::{Bot, Plan};
+use serde_json::{Value, json};
+use std::collections::{HashMap, HashSet};
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+/// The skill a Grok Bot agent runs to write the export file.
+pub const EXPORT_SKILL: &str = include_str!("export-skill.md");
+
+const MAX_AVATAR: u64 = 5 * 1024 * 1024;
+const MAX_SKILL_MD: u64 = 256 * 1024;
+
+/// What the export at `path` holds, for the user to pick from.
+pub async fn preview(b: &Value) -> Result<Value> {
+ let path = export_path(b)?;
+ let (plan, skipped) = tokio::task::spawn_blocking(move || {
+ let mut archive = Archive::open(&path)?;
+ anyhow::Ok((manifest::read(&mut archive, crate::store::now_ms())?, archive.skipped))
+ })
+ .await??;
+ Ok(json!({"plan": plan, "skipped": skipped}))
+}
+
+/// Imports the bots (`bots`: their keys, default all) and groups (`groups`, default all) of the export at
+/// `path`. A bot whose import fails is removed again and the others carry on.
+pub async fn apply(hub: &Arc<Hub>, b: &Value) -> Result<Value> {
+ let path = export_path(b)?;
+ let picked = |key: &str| -> Option<Vec<String>> { serde_json::from_value(b[key].clone()).ok() };
+ let (bots, groups) = (picked("bots"), picked("groups"));
+ let hub = hub.clone();
+ tokio::task::spawn_blocking(move || {
+ let mut archive = Archive::open(&path)?;
+ let mut plan = manifest::read(&mut archive, crate::store::now_ms())?;
+ plan.bots.retain(|bot| bots.as_ref().is_none_or(|keys| keys.contains(&bot.key)));
+ plan.groups.retain(|group| groups.as_ref().is_none_or(|keys| keys.contains(&group.key)));
+ if plan.bots.is_empty() {
+ bail!("pick at least one agent to import");
+ }
+ let agents = crate::agent::backends::list()
+ .into_iter()
+ .filter(|a| a["available"] == true)
+ .filter_map(|a| a["id"].as_str().map(str::to_owned))
+ .collect();
+ Ok(Importer { hub, archive, agents, warnings: std::mem::take(&mut plan.warnings) }.run(&plan))
+ })
+ .await?
+}
+
+fn export_path(b: &Value) -> Result<PathBuf> {
+ let path = PathBuf::from(b["path"].as_str().context("`path` is required")?);
+ if !path.is_absolute() || !path.is_file() {
+ bail!("there's no file at {}", path.display());
+ }
+ Ok(path)
+}
+
+struct Importer {
+ hub: Arc<Hub>,
+ archive: Archive,
+ /// The agents that run on this computer.
+ agents: HashSet<String>,
+ warnings: Vec<String>,
+}
+
+impl Importer {
+ fn run(mut self, plan: &Plan) -> Value {
+ let (mut bots, mut ids) = (Vec::new(), HashMap::new());
+ for (i, bot) in plan.bots.iter().enumerate() {
+ match self.bot(bot, i) {
+ Ok(done) => {
+ ids.insert(bot.key.clone(), done["id"].as_str().unwrap_or_default().to_owned());
+ bots.push(done);
+ }
+ Err(e) => self.warnings.push(format!("Couldn't import {}: {e:#}", bot.name)),
+ }
+ }
+ let mut groups = Vec::new();
+ for group in &plan.groups {
+ let members: Vec<String> = group.members.iter().filter_map(|k| ids.get(k).cloned()).collect();
+ let Some(first) = members.first().cloned() else { continue };
+ match self.group(group, &members) {
+ Ok(Some(id)) => groups.push(json!({"key": group.key, "id": id, "name": group.name})),
+ // The same bots share one group: the routines and memory still go to its lead.
+ Ok(None) => self.warnings.push(format!(
+ "The group chat {} has the same bots as one you have, so it joins that one",
+ group.name
+ )),
+ Err(e) => {
+ self.warnings.push(format!("Couldn't import the group chat {}: {e:#}", group.name));
+ continue;
+ }
+ }
+ // Routines and memory belong to a bot in Codync: the group's go to its lead (or first bot).
+ for routine in &group.routines {
+ let name = format!("{}: {}", group.name, routine.name);
+ self.routine(&first, &name, routine);
+ }
+ self.memories(&first, &group.name, &group.memories);
+ }
+ json!({"source": plan.source, "bots": bots, "groups": groups, "warnings": self.warnings})
+ }
+
+ /// One bot: made first, then filled; removed again if a step it can't do without fails.
+ fn bot(&mut self, bot: &Bot, index: usize) -> Result<Value> {
+ let backend = bot.backend.as_ref().filter(|agent| self.agents.contains(*agent));
+ if let (Some(agent), None) = (&bot.backend, backend) {
+ self.warnings
+ .push(format!("{} ran on {agent}, which isn't on this computer, so it gets the default", bot.name));
+ }
+ let id = self.create(&json!({
+ "name": bot.name,
+ "description": bot.description,
+ "backend": backend,
+ "section": bot.section,
+ "avatarColor": AVATAR_COLORS[index % AVATAR_COLORS.len()],
+ "avatarShape": AVATAR_SHAPES[index % AVATAR_SHAPES.len()],
+ }))?;
+ let filled = self.fill(&id, bot);
+ if filled.is_err()
+ && let Err(e) = self.hub.delete_bot(&id)
+ {
+ tracing::warn!(bot = %id, error = format!("{e:#}"), "couldn't remove a bot whose import failed");
+ }
+ let (skills, files) = filled?;
+ let routines = bot.routines.iter().filter(|r| self.routine(&id, &r.name, r)).count();
+ let memories = self.memories(&id, &bot.name, &bot.memories);
+ if let Some(avatar) = &bot.avatar {
+ self.avatar(&id, &bot.name, avatar);
+ }
+ Ok(json!({
+ "key": bot.key, "id": id, "name": bot.name,
+ "skills": skills, "routines": routines, "memories": memories, "files": files,
+ }))
+ }
+
+ fn create(&self, b: &Value) -> Result<String> {
+ let runtime = tokio::runtime::Handle::current();
+ let cfg = runtime.block_on(crate::agent::new_bot::with_defaults(&self.hub, b.clone()))?;
+ let made = self.hub.create_bot(cfg)?;
+ Ok(made["id"].as_str().context("the new bot has an id")?.to_owned())
+ }
+
+ /// A new group of `members`, or None when a group of the same bots exists (creating would open that one).
+ fn group(&self, group: &manifest::Group, members: &[String]) -> Result<Option<String>> {
+ if crate::chat::group::with_members(&self.hub.store, members)?.is_some() {
+ return Ok(None);
+ }
+ let b = json!({"kind": "group", "name": group.name, "description": group.description, "members": members});
+ self.create(&b).map(Some)
+ }
+
+ /// Its skills and workspace files: how many of each. On a failure, those it added go again.
+ fn fill(&mut self, id: &str, bot: &Bot) -> Result<(usize, usize)> {
+ let cwd = self.hub.store.bot(id)?.context("the new bot")?.config.cwd;
+ let imported = Path::new(&cwd).join("imported");
+ let mut skills = Vec::new();
+ let files = self.fill_into(id, bot, &imported, &mut skills);
+ if files.is_err() {
+ for skill in &skills {
+ if let Err(e) = market::remove_skill(&self.hub.store, skill) {
+ tracing::warn!(skill, error = format!("{e:#}"), "couldn't remove a skill whose import failed");
+ }
+ }
+ if let Err(e) = std::fs::remove_dir_all(&imported)
+ && e.kind() != std::io::ErrorKind::NotFound
+ {
+ tracing::warn!(error = %e, "couldn't remove files whose import failed");
+ }
+ }
+ Ok((skills.len(), files?))
+ }
+
+ /// `fill`'s steps; `skills` collects the ids of the skills it adds.
+ fn fill_into(&mut self, id: &str, bot: &Bot, imported: &Path, skills: &mut Vec<String>) -> Result<usize> {
+ for dir in &bot.skills {
+ skills.push(self.skill(id, dir).with_context(|| format!("the skill {dir}"))?);
+ }
+ market::turn_on(&self.hub, Installed::Skills, skills, Some(id))?;
+ match &bot.files {
+ Some(dir) => self.archive.extract(dir, imported),
+ None => Ok(0),
+ }
+ }
+
+ /// A skill folder as a skill of that bot's own (on for it only); returns its id.
+ fn skill(&mut self, id: &str, dir: &str) -> Result<String> {
+ let md = String::from_utf8(self.archive.read(&format!("{dir}/SKILL.md"), MAX_SKILL_MD)?)
+ .context("SKILL.md isn't UTF-8 text")?;
+ let (name, description) = market::front_matter(&md);
+ let name = name.unwrap_or_else(|| dir.rsplit('/').next().unwrap_or(dir).to_owned());
+ let skill = market::add_custom_skill(
+ &self.hub.store,
+ &name,
+ &description.unwrap_or_default(),
+ market::skill_body(&md),
+ Some(id),
+ )?;
+ // The whole folder (scripts, references), its own SKILL.md over the one just written from it.
+ if let Err(e) = self.archive.extract(dir, &skill.dir()) {
+ market::remove_skill(&self.hub.store, &skill.id)?;
+ return Err(e);
+ }
+ Ok(skill.id)
+ }
+
+ fn routine(&mut self, id: &str, name: &str, routine: &manifest::Routine) -> bool {
+ let body = json!({
+ "name": name, "instruction": routine.instruction, "enabled": routine.enabled, "triggers": routine.triggers,
+ });
+ let saved = self.hub.routines.save(&self.hub, id, &body);
+ if let Err(e) = &saved {
+ self.warnings.push(format!("Couldn't add the routine {name}: {e:#}"));
+ }
+ saved.is_ok()
+ }
+
+ fn memories(&mut self, id: &str, owner: &str, facts: &[String]) -> usize {
+ if facts.is_empty() {
+ return 0;
+ }
+ match crate::chat::memory::add_facts(&self.hub, id, facts) {
+ Ok(written) => written,
+ Err(e) => {
+ self.warnings.push(format!("Couldn't add {owner}'s memories: {e:#}"));
+ 0
+ }
+ }
+ }
+
+ /// The avatar image as the bot's custom icon (which needs this computer signed in to Codync).
+ fn avatar(&mut self, id: &str, name: &str, path: &str) {
+ let set = self.archive.read(path, MAX_AVATAR).and_then(|bytes| {
+ let data = base64::engine::general_purpose::STANDARD.encode(bytes);
+ let b = json!({"target": format!("bot:{id}"), "data": data});
+ tokio::runtime::Handle::current().block_on(crate::icons::set(&self.hub, &b))
+ });
+ if let Err(e) = set {
+ self.warnings.push(format!("{name} keeps a Codync avatar: {e:#}"));
+ }
+ }
+}
diff --git a/host/src/import/schedule.rs b/host/src/import/schedule.rs
new file mode 100644
index 00000000..d7908762
--- /dev/null
+++ b/host/src/import/schedule.rs
@@ -0,0 +1,157 @@
+//! An exported routine's schedule as Codync triggers. The shapes are the ones the export skill writes (and
+//! the other apps' exports use): hourly, daily, weekdays, weekly, monthly, interval, advanced, custom and once.
+
+use crate::routines::Trigger;
+use anyhow::{Context, Result, bail};
+use chrono::TimeZone as _;
+use chrono_tz::Tz;
+use serde_json::Value;
+
+/// The trigger for `schedule` in `zone` (an IANA name), checked from `now` on.
+pub fn trigger(schedule: &Value, zone: &str, now: i64) -> Result<Trigger> {
+ let int = |key: &str| schedule[key].as_i64().with_context(|| format!("`{key}` is required"));
+ let cron = |expression: String| Trigger::Cron { expression, time_zone: zone.to_owned() };
+ let trigger = match schedule["kind"].as_str().unwrap_or_default() {
+ "hourly" => cron(format!("{} * * * *", ranged(int("minute")?, 0, 59, "minute")?)),
+ "daily" => cron(at(schedule, "* * *")?),
+ "weekdays" => cron(at(schedule, "* * 1-5")?),
+ "weekly" => cron(at(schedule, &format!("* * {}", ranged(int("weekday")?, 0, 6, "weekday")?))?),
+ "monthly" => cron(at(schedule, &format!("{} * *", ranged(int("day")?, 1, 31, "day")?))?),
+ "interval" => Trigger::Interval { seconds: int("amount")?.checked_mul(unit(schedule)?).context("too long")? },
+ "custom" => cron(schedule["expression"].as_str().context("`expression` is required")?.trim().to_owned()),
+ "advanced" => cron(advanced(schedule)?),
+ "once" => Trigger::Once { at: once(schedule, zone)? },
+ other => bail!("unknown schedule `{other}`"),
+ };
+ trigger.validate(now)?;
+ Ok(trigger)
+}
+
+/// `minute hour` from the schedule's `time` (`HH:MM`), then the cron fields after them.
+fn at(schedule: &Value, rest: &str) -> Result<String> {
+ let (hour, minute) = hh_mm(schedule["time"].as_str().unwrap_or_default())?;
+ Ok(format!("{minute} {hour} {rest}"))
+}
+
+fn hh_mm(time: &str) -> Result<(i64, i64)> {
+ let (h, m) = time.split_once(':').context("a time is `HH:MM`")?;
+ let hour = ranged(h.trim().parse().context("a time is `HH:MM`")?, 0, 23, "hour")?;
+ Ok((hour, ranged(m.trim().parse().context("a time is `HH:MM`")?, 0, 59, "minute")?))
+}
+
+fn ranged(value: i64, low: i64, high: i64, what: &str) -> Result<i64> {
+ if !(low..=high).contains(&value) {
+ bail!("{what} must be {low} to {high}");
+ }
+ Ok(value)
+}
+
+/// Seconds in one of an interval's `unit`s.
+fn unit(schedule: &Value) -> Result<i64> {
+ Ok(match schedule["unit"].as_str().unwrap_or_default() {
+ "minutes" => 60,
+ "hours" => 3_600,
+ "days" => 86_400,
+ other => bail!("unknown interval unit `{other}`"),
+ })
+}
+
+/// Months, days of the week or month, and a time or a repeat within the day, as one cron expression.
+fn advanced(schedule: &Value) -> Result<String> {
+ let list = |value: &Value, low: i64, high: i64, what: &str| -> Result<String> {
+ let days: Vec<String> = value
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|d| ranged(d.as_i64().context("a list holds numbers")?, low, high, what).map(|d| d.to_string()))
+ .collect::<Result<_>>()?;
+ Ok(if days.is_empty() { "*".into() } else { days.join(",") })
+ };
+ let months = list(&schedule["months"], 1, 12, "month")?;
+ let days = &schedule["days"];
+ let (day_of_month, day_of_week) = match days["kind"].as_str().unwrap_or_default() {
+ "every-day" => ("*".into(), "*".into()),
+ "days-of-week" => ("*".into(), list(&days["days"], 0, 6, "weekday")?),
+ "days-of-month" => (list(&days["days"], 1, 31, "day")?, "*".into()),
+ other => bail!("unknown day choice `{other}`"),
+ };
+ let time = &schedule["time"];
+ let (minute, hour) = match time["kind"].as_str().unwrap_or_default() {
+ "at-time" => {
+ let (hour, minute) = hh_mm(time["time"].as_str().unwrap_or_default())?;
+ (minute.to_string(), hour.to_string())
+ }
+ "every" => {
+ let amount = time["amount"].as_i64().context("`amount` is required")?;
+ match time["unit"].as_str().unwrap_or_default() {
+ "minutes" => (format!("*/{}", ranged(amount, 1, 59, "minutes")?), "*".into()),
+ "hours" => ("0".into(), format!("*/{}", ranged(amount, 1, 23, "hours")?)),
+ other => bail!("unknown repeat unit `{other}`"),
+ }
+ }
+ other => bail!("unknown time choice `{other}`"),
+ };
+ Ok(format!("{minute} {hour} {day_of_month} {months} {day_of_week}"))
+}
+
+/// A one-time run's `date` (`YYYY-MM-DD`) and `time` in `zone`, in Unix milliseconds.
+fn once(schedule: &Value, zone: &str) -> Result<i64> {
+ let date = schedule["date"].as_str().unwrap_or_default();
+ let time = schedule["time"].as_str().unwrap_or_default();
+ let local = chrono::NaiveDateTime::parse_from_str(&format!("{date} {time}"), "%Y-%m-%d %H:%M")
+ .context("a one-time run has a `date` and a `time`")?;
+ let tz: Tz = zone.parse().context("invalid IANA time zone")?;
+ let at = tz.from_local_datetime(&local).earliest().context("that time doesn't exist in the time zone")?;
+ Ok(at.timestamp_millis())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn cron(schedule: &Value) -> String {
+ match trigger(schedule, "Europe/Warsaw", 0).expect("valid schedule") {
+ Trigger::Cron { expression, time_zone } => {
+ assert_eq!(time_zone, "Europe/Warsaw");
+ expression
+ }
+ other => panic!("expected cron, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn calendar_schedules_become_cron() {
+ assert_eq!(cron(&json!({"kind": "hourly", "minute": 15})), "15 * * * *");
+ assert_eq!(cron(&json!({"kind": "daily", "time": "09:05"})), "5 9 * * *");
+ assert_eq!(cron(&json!({"kind": "weekdays", "time": "08:30"})), "30 8 * * 1-5");
+ assert_eq!(cron(&json!({"kind": "weekly", "weekday": 5, "time": "15:00"})), "0 15 * * 5");
+ assert_eq!(cron(&json!({"kind": "monthly", "day": 1, "time": "09:00"})), "0 9 1 * *");
+ assert_eq!(cron(&json!({"kind": "custom", "expression": "0 9 * * 1-5"})), "0 9 * * 1-5");
+ let advanced = json!({"kind": "advanced", "months": [1, 7], "days": {"kind": "days-of-week", "days": [1, 3]},
+ "time": {"kind": "every", "amount": 2, "unit": "hours"}});
+ assert_eq!(cron(&advanced), "0 */2 * 1,7 1,3");
+ }
+
+ #[test]
+ fn intervals_and_one_time_runs() {
+ let interval = trigger(&json!({"kind": "interval", "amount": 30, "unit": "minutes"}), "UTC", 0);
+ assert_eq!(interval.expect("valid"), Trigger::Interval { seconds: 1_800 });
+ let once = trigger(&json!({"kind": "once", "date": "2030-01-02", "time": "03:04"}), "UTC", 0);
+ assert_eq!(once.expect("valid"), Trigger::Once { at: 1_893_553_440_000 });
+ }
+
+ #[test]
+ fn bad_schedules_are_refused() {
+ for bad in [
+ json!({"kind": "daily", "time": "25:00"}),
+ json!({"kind": "weekly", "weekday": 7, "time": "09:00"}),
+ json!({"kind": "custom", "expression": "every day"}),
+ json!({"kind": "interval", "amount": 3, "unit": "weeks"}),
+ json!({"kind": "once", "date": "2001-01-01", "time": "00:00"}),
+ json!({"kind": "sometimes"}),
+ ] {
+ assert!(trigger(&bad, "UTC", 1_700_000_000_000).is_err(), "{bad}");
+ }
+ }
+}
diff --git a/host/src/import/tests.rs b/host/src/import/tests.rs
new file mode 100644
index 00000000..c160cf96
--- /dev/null
+++ b/host/src/import/tests.rs
@@ -0,0 +1,188 @@
+use super::archive::Archive;
+use super::manifest;
+use serde_json::{Value, json};
+use std::io::Write as _;
+use std::path::PathBuf;
+
+/// A zip at a fresh temporary path holding `files` (path, contents).
+fn zip(files: &[(&str, &[u8])]) -> PathBuf {
+ let path = std::env::temp_dir().join(format!("codync-import-{}.zip", uuid::Uuid::new_v4()));
+ let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
+ for (name, data) in files {
+ zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
+ zip.write_all(data).unwrap();
+ }
+ zip.finish().unwrap();
+ path
+}
+
+fn read(files: &[(&str, &[u8])]) -> anyhow::Result<(manifest::Plan, Vec<String>)> {
+ let path = zip(files);
+ let mut archive = Archive::open(&path)?;
+ let plan = manifest::read(&mut archive, 1_700_000_000_000);
+ std::fs::remove_file(path).unwrap();
+ Ok((plan?, archive.skipped))
+}
+
+fn export() -> Value {
+ json!({
+ "format": "codync-bot-import", "version": 1, "source": {"app": "grok-bot"},
+ "agents": [
+ {"key": "research", "name": "Research", "title": "Analyst", "description": "Find sources.",
+ "avatar": "agents/research/avatar.png", "skills": ["agents/research/skills/brief", "agents/sales/skills/x"],
+ "routines": [
+ {"name": "Digest", "instruction": "Summarize.", "active": false, "timezone": "Asia/Taipei",
+ "schedule": {"kind": "weekdays", "time": "08:30"}},
+ {"name": "Broken", "instruction": "x", "schedule": {"kind": "fortnightly"}}
+ ],
+ "memories": ["The user reports in EUR.", ""], "files": "agents/research/files"},
+ {"key": "Bad Key", "name": "Bad"},
+ {"key": "sales", "name": "Sales", "description": "Sell."}
+ ],
+ "channels": [
+ {"key": "desk", "name": "Desk", "members": ["sales", "research", "ghost"], "lead": "research",
+ "memories": ["Actions, not summaries."]},
+ {"key": "empty", "name": "Empty", "members": ["ghost"]}
+ ]
+ })
+}
+
+#[test]
+fn an_export_reads_into_bots_and_groups() {
+ let manifest = export().to_string();
+ let (plan, skipped) = read(&[
+ ("codync-import.json", manifest.as_bytes()),
+ ("agents/research/avatar.png", b"png"),
+ ("agents/research/skills/brief/SKILL.md", b"---\nname: Brief\ndescription: Write briefs\n---\nDo it."),
+ ("agents/research/files/notes.md", b"notes"),
+ ("agents/research/files/.env", b"SECRET=1"),
+ ("__MACOSX/agents/._x", b""),
+ ])
+ .unwrap();
+ assert_eq!(plan.source, "grok-bot");
+ assert_eq!(skipped, ["agents/research/files/.env"]);
+ let keys: Vec<&str> = plan.bots.iter().map(|b| b.key.as_str()).collect();
+ assert_eq!(keys, ["research", "sales"], "the agent with a bad key is left out");
+ let research = &plan.bots[0];
+ assert_eq!(research.description, "Analyst\n\nFind sources.");
+ assert_eq!(research.avatar.as_deref(), Some("agents/research/avatar.png"));
+ assert_eq!(research.skills, ["agents/research/skills/brief"], "another agent's folder is refused");
+ assert_eq!(research.files.as_deref(), Some("agents/research/files"));
+ assert_eq!(research.memories, ["The user reports in EUR."]);
+ assert_eq!(research.routines.len(), 1);
+ assert!(!research.routines[0].enabled);
+ assert_eq!(plan.groups.len(), 1, "a group with no exported agent is left out");
+ assert_eq!(plan.groups[0].members, ["research", "sales"], "the lead first, unknown agents dropped");
+ let warnings = plan.warnings.join("\n");
+ for expected in ["Bad", "Broken", "agents/sales/skills/x", "Empty"] {
+ assert!(warnings.contains(expected), "{expected} in {warnings}");
+ }
+}
+
+#[test]
+fn other_apps_exports_and_a_wrapping_folder_are_read() {
+ let mut agent = export();
+ agent["format"] = "openbot-agent-import".into();
+ let (plan, _) = read(&[("export/openbot-import.json", agent.to_string().as_bytes())]).unwrap();
+ assert_eq!(plan.bots.len(), 2);
+
+ let transfer = json!({
+ "format": "openbot-instance-transfer", "version": 1, "source": {"appVersion": "1.0", "exportedAt": null},
+ "agents": [{"key": "ops", "name": "Ops", "title": "", "description": "Keep it running.",
+ "provider": "codex", "skills": [], "files": null, "routines": [],
+ "oneTimeRoutines": [{"key": "r", "name": "Launch", "instruction": "Ship.", "active": true,
+ "timezone": "UTC", "schedule": {"kind": "once", "date": "2031-01-01", "time": "09:00"}}],
+ "memories": [{"text": "Deploys on Fridays.", "inclusion": "essential"}]}],
+ "settings": {"sidebarSections": [{"name": "Work", "agentKeys": ["ops"]}]}
+ });
+ let (plan, _) = read(&[("openbot-transfer.json", transfer.to_string().as_bytes())]).unwrap();
+ let ops = &plan.bots[0];
+ assert_eq!(plan.source, "openbot");
+ assert_eq!(ops.memories, ["Deploys on Fridays."]);
+ assert_eq!(ops.routines.len(), 1, "one-time routines come along");
+ assert_eq!(ops.section.as_deref(), Some("Work"));
+ assert_eq!(ops.backend.as_deref(), Some("codex"));
+}
+
+#[test]
+fn files_that_are_not_an_export_are_refused() {
+ assert!(read(&[("readme.md", b"hi")]).is_err(), "no manifest");
+ let mut newer = export();
+ newer["version"] = 2.into();
+ let err = read(&[("codync-import.json", newer.to_string().as_bytes())]).unwrap_err();
+ assert!(format!("{err:#}").contains("newer version"));
+ let mut wrong = export();
+ wrong["format"] = "something-else".into();
+ assert!(read(&[("codync-import.json", wrong.to_string().as_bytes())]).is_err());
+ let none = json!({"format": "codync-bot-import", "version": 1, "agents": [{"key": "-x", "name": "X"}]});
+ assert!(read(&[("codync-import.json", none.to_string().as_bytes())]).is_err(), "no importable agent");
+}
+
+#[test]
+fn extract_keeps_paths_below_the_folder() {
+ let path = zip(&[("a/files/x.md", b"x"), ("a/files/d/y.md", b"y"), ("a/other.md", b"o")]);
+ let mut archive = Archive::open(&path).unwrap();
+ let dest = std::env::temp_dir().join(format!("codync-import-out-{}", uuid::Uuid::new_v4()));
+ assert_eq!(archive.extract("a/files", &dest).unwrap(), 2);
+ assert_eq!(std::fs::read_to_string(dest.join("d/y.md")).unwrap(), "y");
+ assert!(!dest.join("other.md").exists());
+ std::fs::remove_dir_all(dest).unwrap();
+ std::fs::remove_file(path).unwrap();
+}
+
+#[test]
+fn entries_that_leave_the_archive_or_link_are_skipped() {
+ let path = std::env::temp_dir().join(format!("codync-import-{}.zip", uuid::Uuid::new_v4()));
+ let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
+ let options = zip::write::SimpleFileOptions::default();
+ for name in ["../evil.md", "/abs.md", "ok.md"] {
+ zip.start_file(name, options).unwrap();
+ zip.write_all(b"x").unwrap();
+ }
+ zip.add_symlink("link", "/etc/passwd", options).unwrap();
+ zip.finish().unwrap();
+ let archive = Archive::open(&path).unwrap();
+ std::fs::remove_file(path).unwrap();
+ assert!(archive.has("ok.md") && !archive.has("/abs.md"), "an absolute path stays below the archive's root");
+ assert_eq!(archive.skipped, ["../evil.md", "link"]);
+}
+
+#[tokio::test]
+async fn an_import_makes_bots_and_one_group_and_rolls_a_failed_bot_back() {
+ let dir = std::env::temp_dir().join(format!("codync-import-hub-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = crate::store::Store::open(&dir.join("t.db")).unwrap();
+ let identity = crate::remote::identity::Identity::load_or_create(&dir).unwrap();
+ let hub = crate::hub::Hub::new(store, "test".into(), identity, "token".into(), 0);
+ let mut manifest = export();
+ manifest["agents"][0]["skills"] = json!([]);
+ manifest["agents"][1] = json!({"key": "ops", "name": "Ops",
+ "skills": ["agents/ops/skills/a", "agents/ops/skills/b"], "files": "agents/ops/files"});
+ manifest["channels"][1] = json!({"key": "again", "name": "Again", "members": ["research", "sales"]});
+ let manifest = manifest.to_string();
+ let path = zip(&[
+ ("codync-import.json", manifest.as_bytes()),
+ ("agents/research/files/notes.md", b"notes"),
+ ("agents/ops/files/x.md", b"x"),
+ ("agents/ops/skills/a/SKILL.md", b"---\nname: A\n---\nDo A."),
+ ("agents/ops/skills/b/SKILL.md", b"\xff\xfe"),
+ ]);
+ let done = super::apply(&hub, &json!({"path": path})).await.unwrap();
+ std::fs::remove_file(path).unwrap();
+
+ let names: Vec<&str> = done["bots"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect();
+ assert_eq!(names, ["Research", "Sales"], "Ops fails on its second skill: {done}");
+ let research = &done["bots"][0];
+ assert_eq!((research["files"].as_u64(), research["memories"].as_u64()), (Some(1), Some(1)));
+ let cwd = hub.store.bot(research["id"].as_str().unwrap()).unwrap().unwrap().config.cwd;
+ assert_eq!(std::fs::read_to_string(std::path::Path::new(&cwd).join("imported/notes.md")).unwrap(), "notes");
+ let skills = crate::market::list_skills(&hub.store);
+ assert_eq!(skills["items"].as_array().unwrap().len(), 0, "Ops' first skill goes with it: {skills}");
+ let groups = done["groups"].as_array().unwrap();
+ assert_eq!(groups.len(), 1, "two groups of the same bots are one: {done}");
+ let lead = hub.store.bot(groups[0]["id"].as_str().unwrap()).unwrap().unwrap().config.members[0].clone();
+ assert_eq!(lead, research["id"].as_str().unwrap(), "the export's lead leads");
+ let warnings = done["warnings"].to_string();
+ assert!(warnings.contains("Couldn't import Ops") && warnings.contains("Again"), "{warnings}");
+ std::fs::remove_dir_all(dir).unwrap();
+}
diff --git a/host/src/import_cli.rs b/host/src/import_cli.rs
new file mode 100644
index 00000000..8f6ff3f0
--- /dev/null
+++ b/host/src/import_cli.rs
@@ -0,0 +1,96 @@
+//! `codync-host import`: bots from another app's export file (see `import`).
+
+use crate::local_api::local_call_for;
+use anyhow::{Context, Result};
+use serde_json::{Value, json};
+use std::path::PathBuf;
+use std::time::Duration;
+
+#[derive(clap::Args)]
+pub struct ImportArgs {
+ /// The export file (.zip).
+ #[arg(required_unless_present = "skill")]
+ file: Option<PathBuf>,
+ /// Only list what the file holds.
+ #[arg(long)]
+ dry_run: bool,
+ /// Import only these agents (their keys, as `--dry-run` lists them), comma-separated.
+ #[arg(long, value_delimiter = ',')]
+ only: Option<Vec<String>>,
+ /// Print the skill that writes an export file in Grok Bot, and nothing else.
+ #[arg(long)]
+ skill: bool,
+ #[arg(long, default_value_t = crate::service::DEFAULT_PORT)]
+ port: u16,
+}
+
+pub async fn run(args: ImportArgs) -> Result<()> {
+ if args.skill {
+ print!("{}", crate::import::EXPORT_SKILL);
+ return Ok(());
+ }
+ let file = args.file.context("name the export file")?;
+ let path = std::fs::canonicalize(&file).with_context(|| format!("there's no file at {}", file.display()))?;
+ let path = path.to_string_lossy();
+ let timeout = Duration::from_mins(10);
+ if args.dry_run {
+ let v = local_call_for(args.port, "previewImport", json!({"path": path}), timeout).await?;
+ print_plan(&v["plan"], &v["skipped"]);
+ return Ok(());
+ }
+ let body = json!({"path": path, "bots": args.only});
+ let v = local_call_for(args.port, "importBots", body, timeout).await?;
+ for bot in list(&v["bots"]) {
+ let n = |k: &str| bot[k].as_u64().unwrap_or(0);
+ println!(
+ "Imported {}: {} skills, {} routines, {} memories, {} files",
+ text(bot, "name"),
+ n("skills"),
+ n("routines"),
+ n("memories"),
+ n("files")
+ );
+ }
+ for group in list(&v["groups"]) {
+ println!("Imported the group {}", text(group, "name"));
+ }
+ warnings(&v["warnings"]);
+ Ok(())
+}
+
+fn print_plan(plan: &Value, skipped: &Value) {
+ println!("From {}:", plan["source"].as_str().filter(|s| !s.is_empty()).unwrap_or("an export"));
+ for bot in list(&plan["bots"]) {
+ let n = |k: &str| bot[k].as_array().map_or(0, Vec::len);
+ println!(
+ " {:<24} {} ({} skills, {} routines, {} memories{})",
+ text(bot, "key"),
+ text(bot, "name"),
+ n("skills"),
+ n("routines"),
+ n("memories"),
+ if bot["files"].is_string() { ", files" } else { "" }
+ );
+ }
+ for group in list(&plan["groups"]) {
+ println!(" group {:<18} {}", text(group, "key"), text(group, "name"));
+ }
+ for path in list(skipped) {
+ println!("Left out of the file: {}", path.as_str().unwrap_or_default());
+ }
+ warnings(&plan["warnings"]);
+}
+
+fn warnings(v: &Value) {
+ for w in list(v) {
+ println!("Note: {}", w.as_str().unwrap_or_default());
+ }
+}
+
+fn list(v: &Value) -> &[Value] {
+ v.as_array().map_or(&[], Vec::as_slice)
+}
+
+fn text<'a>(v: &'a Value, key: &str) -> &'a str {
+ v[key].as_str().unwrap_or_default()
+}
diff --git a/host/src/local_api.rs b/host/src/local_api.rs
new file mode 100644
index 00000000..eed1e6c6
--- /dev/null
+++ b/host/src/local_api.rs
@@ -0,0 +1,38 @@
+//! The running host's local API, as the `codync-host` commands call it (`~/.codync/token` over loopback).
+use crate::{http, service};
+use anyhow::{Context, Result};
+use std::time::Duration;
+
+/// What a local command says when it can't reach the running host.
+pub(crate) const NOT_RUNNING: &str =
+ "codync-host isn't running here. Start it with `codync-host install` (or `serve`).";
+
+/// Calls `method` on the running host.
+pub(crate) async fn local_call(port: u16, method: &str, body: serde_json::Value) -> Result<serde_json::Value> {
+ local_call_for(port, method, body, Duration::from_secs(20)).await
+}
+
+/// `local_call` for a method that may take longer than 20 seconds.
+pub(crate) async fn local_call_for(
+ port: u16,
+ method: &str,
+ body: serde_json::Value,
+ timeout: Duration,
+) -> Result<serde_json::Value> {
+ let not_running = || anyhow::anyhow!(NOT_RUNNING);
+ let token = std::fs::read_to_string(service::data_dir().join("token")).map_err(|_| not_running())?;
+ let res = http()
+ .post(format!("http://127.0.0.1:{port}/api/{method}"))
+ .bearer_auth(token.trim())
+ .json(&body)
+ .timeout(timeout)
+ .send()
+ .await
+ .map_err(|_| not_running())?;
+ let status = res.status();
+ let v: serde_json::Value = res.json().await.context("reading the host's answer")?;
+ if !status.is_success() {
+ anyhow::bail!("{}", v["error"].as_str().unwrap_or("the host refused"));
+ }
+ Ok(v)
+}
diff --git a/host/src/main.rs b/host/src/main.rs
index c281fe98..367ad574 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -10,6 +10,9 @@ mod compat;
mod environment;
mod hub;
mod icons;
+mod import;
+mod import_cli;
+mod local_api;
mod market;
mod mcp;
mod network;
@@ -28,6 +31,7 @@ mod usage;
mod voice;
use agent::backends;
+use local_api::local_call;
use remote::identity;
use anyhow::{Context, Result};
@@ -115,6 +119,8 @@ enum Sub {
Cloud(cloud_cli::CloudArgs),
/// Your other computers: create a network, invite them, see who is around.
Network(network_cli::NetworkArgs),
+ /// Import bots from another app's export file (`--skill` prints the skill that writes one in Grok Bot).
+ Import(import_cli::ImportArgs),
/// Install and start the host as a background service (launchd / systemd --user).
Install {
#[arg(long, default_value_t = service::DEFAULT_PORT)]
@@ -349,6 +355,7 @@ async fn main() -> Result<()> {
Sub::Pair { port, json } => pair(port, json).await,
Sub::Info { port, json } => info(port, json).await,
Sub::Send(args) => send_cli::run(args).await,
+ Sub::Import(args) => import_cli::run(args).await,
Sub::Devices { port, action } => match action.unwrap_or(DevicesAction::List) {
DevicesAction::List => {
let v = local_call(port, "devices", json!({})).await?;
@@ -573,29 +580,6 @@ async fn shutdown_signal() {
}
}
-/// What a local command says when it can't reach the running host.
-const NOT_RUNNING: &str = "codync-host isn't running here. Start it with `codync-host install` (or `serve`).";
-
-/// Calls the running host's local API (`~/.codync/token` over loopback).
-async fn local_call(port: u16, method: &str, body: serde_json::Value) -> Result<serde_json::Value> {
- let not_running = || anyhow::anyhow!(NOT_RUNNING);
- let token = std::fs::read_to_string(service::data_dir().join("token")).map_err(|_| not_running())?;
- let res = http()
- .post(format!("http://127.0.0.1:{port}/api/{method}"))
- .bearer_auth(token.trim())
- .json(&body)
- .timeout(Duration::from_secs(20))
- .send()
- .await
- .map_err(|_| not_running())?;
- let status = res.status();
- let v: serde_json::Value = res.json().await.context("reading the host's answer")?;
- if !status.is_success() {
- anyhow::bail!("{}", v["error"].as_str().unwrap_or("the host refused"));
- }
- Ok(v)
-}
-
async fn pair(port: u16, as_json: bool) -> Result<()> {
let hello = local_call(port, "hello", json!({})).await?;
let p = local_call(port, "pairing", json!({})).await?;
diff --git a/host/src/market/mod.rs b/host/src/market/mod.rs
index 784c8a45..6cc03b60 100644
--- a/host/src/market/mod.rs
+++ b/host/src/market/mod.rs
@@ -33,11 +33,11 @@ mod updates;
pub use install::{add_custom_connector, import_connectors, install_connector, list_connectors, remove_connector};
pub use registry::{browse_connectors, connector_info, refresh_first_page};
-pub(crate) use skills::front_matter;
pub use skills::{
add_custom_skill, browse_skills, expand_command, install_skill, list_skills, remove_skill, skill_details,
skills_brief, slash_command, turn_on_installed_once, update_custom_skill,
};
+pub(crate) use skills::{body as skill_body, front_matter};
pub use updates::{automatic_loop, refresh_connector};
diff --git a/host/src/market/skills.rs b/host/src/market/skills.rs
index 6f45c108..cb2059e3 100644
--- a/host/src/market/skills.rs
+++ b/host/src/market/skills.rs
@@ -41,7 +41,7 @@ pub(crate) fn front_matter(md: &str) -> (Option<String>, Option<String>) {
}
/// `SKILL.md` without its front matter: what a skill tells the agent to do.
-fn body(md: &str) -> &str {
+pub(crate) fn body(md: &str) -> &str {
let mut lines = md.split_inclusive('\n');
if lines.next().map(str::trim) != Some("---") {
return md.trim();
diff --git a/host/src/network_cli.rs b/host/src/network_cli.rs
index f39fb29a..c1cc912a 100644
--- a/host/src/network_cli.rs
+++ b/host/src/network_cli.rs
@@ -1,6 +1,6 @@
//! `codync-host network`: this computer's network of the user's computers (codync-network).
-use crate::local_call;
+use crate::local_api::local_call;
use anyhow::Result;
use clap::Subcommand;
use serde_json::{Value, json};
diff --git a/host/src/send_cli.rs b/host/src/send_cli.rs
index 1f21ae34..190a490a 100644
--- a/host/src/send_cli.rs
+++ b/host/src/send_cli.rs
@@ -177,7 +177,7 @@ async fn execute(args: &SendArgs) -> Result<Exit, Failure> {
.await
.map_err(|_| Failure::usage("couldn't read the message"))??;
let base = format!("http://127.0.0.1:{}", args.port);
- let token = Client::new(&base, None).token().ok_or_else(|| Failure::host(crate::NOT_RUNNING))?;
+ let token = Client::new(&base, None).token().ok_or_else(|| Failure::host(crate::local_api::NOT_RUNNING))?;
let mut feed = BotFeed::connect(&base, &token).await?;
let bots = feed.bots();
let bot = resolve_bot(&args.bot, &bots)?;
@@ -233,7 +233,7 @@ async fn send(base: &str, token: &str, body: &Value) -> Result<Value, Failure> {
};
match answer {
Some(answer) => return Ok(answer),
- None if attempts == 3 => return Err(Failure::host(crate::NOT_RUNNING)),
+ None if attempts == 3 => return Err(Failure::host(crate::local_api::NOT_RUNNING)),
None => attempts += 1,
}
tokio::time::sleep(Duration::from_millis(250)).await;
diff --git a/host/src/send_cli/events.rs b/host/src/send_cli/events.rs
index 5afa6746..41e4bbcd 100644
--- a/host/src/send_cli/events.rs
+++ b/host/src/send_cli/events.rs
@@ -105,7 +105,7 @@ impl BotFeed {
.await
.ok()
.and_then(Result::ok)
- .ok_or_else(|| Failure::host(crate::NOT_RUNNING))?;
+ .ok_or_else(|| Failure::host(crate::local_api::NOT_RUNNING))?;
if !response.status().is_success() {
let body: Value = response.json().await.unwrap_or_default();
return Err(Failure::host(redact(body["error"].as_str().unwrap_or("the host refused"), token)));
diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdx
index 51e8affc..b0fd58f1 100644
--- a/web/content/docs/bots.mdx
+++ b/web/content/docs/bots.mdx
@@ -130,6 +130,18 @@ Confirm with **Delete bot and its conversation**. Deleting your lead bot leaves
On the iPhone details sheet or the desktop details panel, **Create template** shows the bot's settings as text you can copy, without its conversation.
+## Import bots from Grok Bot
+
+Bring your Grok Bot agents over without setting each one up again. Each agent becomes a bot with its instructions, avatar, skills, scheduled tasks (as routines), memories and, if you choose, its workspace files; group chats become groups.
+
+1. In the desktop app, click **+** and choose **Import bots…**, then **Copy export skill**.
+2. In Grok Bot, paste it as a skill of one agent (or into its instructions) and send that agent: *Export my agents for Codync*. It asks which agents to include and whether to add workspace files, then saves `codync-export-<date>.zip` to Downloads.
+3. Back in Codync, click **Choose file…**, pick that file, turn off any bot or group chat you don't want, and click **Import**.
+
+Chats aren't copied: the export keeps what matters in them as memories. The file is read on your computer and isn't uploaded. Codync leaves out secrets it finds in the file (`.env` files, private keys) and anything it can't read, and lists what it left out. An avatar picture needs the computer signed in, like any [custom icon](#custom-icons); otherwise the bot keeps a Codync character. A group chat's routines and memories go to its lead bot.
+
+Exports other apps make from Grok Bot, and their own transfer files, import the same way. From a terminal: `codync-host import <file>` (`--dry-run` lists what the file holds, `--skill` prints the export skill).
+
## Custom icons
Open an existing bot's avatar picker and choose **Upload from desktop** (**Upload image** on phones), or choose **Paste URL** to reveal the address field, paste an HTTPS image address, and press the arrow button. Changes save immediately. **Tint icon** uses the bot's color; turn it off to keep the picture's original colors. **Use default** restores the character.