Something went wrong. Try again.
Open source agent hosting on the AT Protocol
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186// Move an agent whose space is under an account this installation made (a per-owner "-spaces"// authority, or before that its own "-space" authority with skey "self") into a space under its// owner's own DID: at://<owner DID>/space/ai.languid.space.agent/<name>. Only for agents of the// installation owner, whose password this installation holds.//// The Spaces alpha's migration endpoints (getRepo/importRepo, exportSpaceMeta/importSpaceMeta) move// a space between hosts under the same ref: a STAR archive's commit names its space, so it can't be// imported into a space with a different ref. So records are copied one by one, keeping collection,// rkey and value (thread and message order hang on the rkeys). Values that mention the old space// ref are rewritten to the new one.//// Nothing is deleted. The old space, its records and the old authority account stay until removed by hand.
import { Session } from './atproto/xrpc.ts'import { SpaceRepo, type SpaceRecord } from './atproto/space.ts'import { agentSpaceRef, installationAuthority, openAgentSpace, spaceAuthorityDid } from './manager.ts'import { type AgentEntry, type State, getAgent, previousSpacesOf, updateState } from './state.ts'
export interface MigrationReport { agent: string oldSpace: string newSpace: string /** The new authority: the owner. */ authority: { handle: string; did: string } /** Per member repo copied (the agent's, and the owner's when it has records): record counts per collection. */ repos: { repo: string; label: string; counts: Record<string, number>; copied?: Record<string, number> }[] /** Records whose value mentions the old space ref, rewritten in the copy. */ rewritten: string[] /** Public records (agent's repo) that mention the old space ref, rewritten in place. */ publicRewritten: string[] applied: boolean leftovers: string[]}
const key = (r: { collection: string; rkey: string }) => `${r.collection}/${r.rkey}`
/** JSON with sorted keys, for comparing record values. */function canonical(v: unknown): string { return JSON.stringify(v, (_k, x) => x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : 1))) : x, )}
/** `value` with every occurrence of `from` in its strings replaced by `to`. */function replaceIn(value: unknown, from: string, to: string): unknown { if (typeof value === 'string') return value.split(from).join(to) if (Array.isArray(value)) return value.map((v) => replaceIn(v, from, to)) if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, replaceIn(v, from, to)])) return value}
const mentions = (value: unknown, s: string) => JSON.stringify(value).includes(s)
function countByCollection(records: { collection: string }[]) { const out: Record<string, number> = {} for (const r of records) out[r.collection] = (out[r.collection] ?? 0) + 1 return Object.fromEntries(Object.entries(out).sort())}
/** The records of `to` that are missing or differ from (rewritten) `from`. */function diff(from: SpaceRecord[], to: SpaceRecord[], rewrite: (v: unknown) => unknown) { const have = new Map(to.map((r) => [key(r), canonical(r.value)])) const writes: { op: 'create' | 'update'; collection: string; rkey: string; value: Record<string, unknown> }[] = [] for (const r of from) { const value = rewrite(r.value) as Record<string, unknown> const existing = have.get(key(r)) if (existing === canonical(value)) continue writes.push({ op: existing === undefined ? 'create' : 'update', collection: r.collection, rkey: r.rkey, value }) } return writes}
/** * Copy one member's repo from the old space to the new one until they match. Re-lists the old repo * after each pass, so records written meanwhile are picked up; fails if it doesn't settle. */async function copyRepo(from: SpaceRepo, to: SpaceRepo, rewrite: (v: unknown) => unknown) { for (let pass = 0; pass < 4; pass++) { const [src, dst] = await Promise.all([from.list(), to.list()]) const extra = dst.filter((r) => !src.some((s) => key(s) === key(r))) if (extra.length) throw new Error(`the new space has records the old one doesn't: ${extra.slice(0, 5).map(key).join(', ')}`) const writes = diff(src, dst, rewrite) if (!writes.length) return countByCollection(dst) for (let i = 0; i < writes.length; i += 100) await to.applyWrites(writes.slice(i, i + 100)) } throw new Error(`${from.repo}'s records in ${from.space} kept changing during the copy; stop the agent's runs and try again`)}
/** * Plan (apply false) or carry out (apply true) moving agent `name` to a space under its owner's DID. * `entry.space` is switched only after every record is copied and verified. */export async function migrateAuthority(state: State, name: string, apply: boolean): Promise<MigrationReport> { const entry = getAgent(state, name) if (spaceAuthorityDid(entry.space) === entry.owner) throw new Error(`${name}'s space already belongs to its owner: ${entry.space}`) const ownerAccount = state.owner?.did === entry.owner ? state.owner : undefined if (!ownerAccount) throw new Error(`${name} belongs to ${entry.owner}, not to this installation's owner; only the installation owner's agents can be moved from here`) const oldSpace = entry.space const agentSession = await Session.login(state.pds, entry.agent.did, entry.agent.password) const ownerSession = await Session.login(state.pds, ownerAccount.did, ownerAccount.password)
// Member repos to copy: the agent's, and the owner's if the owner is a local account with records // there (languid writes only to the agent's, but don't leave anything behind). const members: { label: string; session: Session }[] = [{ label: 'agent', session: agentSession }, { label: 'owner', session: ownerSession }] const repos: MigrationReport['repos'] = [] const sources: { label: string; session: Session; records: SpaceRecord[] }[] = [] for (const m of members) { const records = await new SpaceRepo(m.session, oldSpace).list() if (m.label === 'owner' && !records.length) continue sources.push({ ...m, records }) repos.push({ repo: m.session.did, label: m.label, counts: countByCollection(records) }) } const rewritten = sources.flatMap((s) => s.records.filter((r) => mentions(r.value, oldSpace)).map((r) => `${s.label} ${key(r)}`))
// The agent's public records that name the space (ai.languid.agent.owner). const publicRecords: { collection: string; rkey: string; value: any }[] = [] const desc = await agentSession.call('com.atproto.repo.describeRepo', { params: { repo: agentSession.did } }) for (const collection of desc.collections as string[]) { let cursor: string | undefined do { const page = await agentSession.call('com.atproto.repo.listRecords', { params: { repo: agentSession.did, collection, limit: 100, cursor } }) for (const r of page.records) { if (mentions(r.value, oldSpace)) publicRecords.push({ collection, rkey: r.uri.split('/').pop(), value: r.value }) } cursor = page.records.length ? page.cursor : undefined } while (cursor) }
const report: MigrationReport = { agent: name, oldSpace, newSpace: agentSpaceRef(ownerAccount.did, name), authority: { handle: ownerAccount.handle, did: ownerAccount.did }, repos, rewritten, publicRewritten: publicRecords.map(key), applied: false, leftovers: leftovers(state, entry, oldSpace), } if (!apply) return report
const newSpace = await openAgentSpace(await installationAuthority(state), name, [entry.owner, entry.agent.did]) if (newSpace !== report.newSpace) throw new Error(`opened ${newSpace}, expected ${report.newSpace}`) const rewrite = (v: unknown) => replaceIn(v, oldSpace, newSpace)
for (const [i, s] of sources.entries()) { const copied = await copyRepo(new SpaceRepo(s.session, oldSpace), new SpaceRepo(s.session, newSpace), rewrite) // Verify against a fresh listing of both, collection by collection. const [src, dst] = await Promise.all([new SpaceRepo(s.session, oldSpace).list(), new SpaceRepo(s.session, newSpace).list()]) const want = countByCollection(src) if (canonical(want) !== canonical(countByCollection(dst)) || diff(src, dst, rewrite).length) { throw new Error(`verification failed for the ${s.label}'s repo: old ${canonical(want)}, new ${canonical(countByCollection(dst))}`) } repos[i].counts = want repos[i].copied = copied }
for (const r of publicRecords) { await agentSession.call('com.atproto.repo.putRecord', { body: { repo: agentSession.did, collection: r.collection, rkey: r.rkey, record: replaceIn(r.value, oldSpace, newSpace) }, }) }
updateState(state, (s) => { const e = s.agents[name] if (!e || e.space !== oldSpace) throw new Error(`${name}'s space changed in state.json during the migration; nothing switched`) e.previousSpaces = [...(e.previousSpaces ?? []), oldSpace] e.space = newSpace }) report.applied = true return report}
/** What to delete by hand once the migration has been checked. */function leftovers(state: State, entry: AgentEntry, oldSpace: string): string[] { const out: string[] = [] for (const space of [...previousSpacesOf(entry), oldSpace]) { out.push(`old space ${space} (the agent's repo in it still holds every record; clear it as the agent with com.atproto.space.clearRecords, then delete the space as its authority with com.atproto.space.deleteSpace)`) } const accounts = [entry.authority, state.authorities?.[entry.owner]].filter((a) => a !== undefined) for (const a of accounts) { out.push(`old authority account ${a.handle} (${a.did}): once it has no spaces left, remove it from state.json (${a === entry.authority ? `"authority" in ${entry.name}'s entry` : `"authorities"`}); \`languid admin prune\` then deletes it (docs/hosting.md)`) } return out}