カスタムフィード作成

Blueskyのようなアプリからアクセス可能なアルゴリズムのホスト

カスタムフィード(フィードジェネレーター)は、ユーザーにアルゴリズムを提供するサービスです。これにより、自分好みのタイムライン表示を選んだり、他のユーザー向けに埋め込み可能なフィードを作成したりといった高い自由度が得られます。

このチュートリアルでは、Jetstreamから投稿を取り込み、アルゴリズムで並び替え、XRPCフィードとして配信するカスタムフィードサーバーを作成します。

前提条件

このチュートリアルでは、TypeScriptアプリケーションをゼロから構築します。TypeScriptとNode.jsの基本的な理解を前提としています。

以下をインストールしておいてください。

  • Node.js 22.15以上

homebrewに対応したプラットフォームでは、次のコマンドでインストールできます。

brew install node

さらに、lex CLIツールとtsxをグローバルにインストールしておく必要があります。

npm install -g @atproto/lex tsx

次に、新しいTypeScriptプロジェクトディレクトリを作成し、プロジェクトを初期化します。

mkdir my-agent
cd my-agent
npm init -y
npm pkg set type=module
npm i -D typescript @types/node dotenv @atproto/lex-server
npm i @atproto/lex @bsky/jetstream
npx tsc --init --verbatimModuleSyntax false

まず、プロジェクトにLexiconを追加します。

パート1:Lexicon

Lexiconはatprotoのレコードを定義します。基本的なフィードジェネレーターにはapp.bsky.feed.describeFeedGeneratorとapp.bsky.feed.getFeedSkeletonのLexiconが必要です。lexを使えば、これらのLexiconをダウンロードしてプロジェクトに組み込めます。

lex install app.bsky.feed.describeFeedGenerator app.bsky.feed.getFeedSkeleton

ここからlex buildを実行すると、インストール済みLexiconすべてに対してTypeScriptの型を生成できます。

lex build

生成されたコードはsrc/lexiconsに配置されます。

プロジェクトのセットアップで@bsky/jetstream SDKもインストールします。パート3で使用します。

これでフィードジェネレーターの構築を始められます。

パート2:フィードの構成

ユーザーにカスタムアルゴリズムを提供する一般的なフローは以下の通りです。

  • ユーザーがアプリケーションバックエンド(例:Bluesky)にフィードを要求する
  • アプリケーションが要求されたフィードのDIDドキュメントを見つけ、ホスティングサーバーを特定する
  • アプリケーションがホスティングサーバーへgetFeedSkeletonリクエストを送る
  • フィードのホスティングサーバーが投稿URLの一覧を返す
  • アプリケーションがフィードをハイドレート(ユーザー情報、投稿内容、集計情報などを付加)する
  • アプリケーションがハイドレート済みフィードをユーザーに返す

最初に、環境変数から設定を読み取ります。多くは公開するフィード用の設定(FEED_PUBLISHER_DID, FEED_NAME)ですが、フィードの挙動を決める設定(FEED_MAX_POSTS, SEARCH_TERMS)も含まれます。

この例では、アプリ全体をsrc/index.tsという単一ファイルで作成します。このファイルを作成し、以下のimportと設定行を追加してください。

import { Jetstream } from '@bsky/jetstream'
import { AtUriString, DidString, isDidString } from '@atproto/lex'
import { LexError, LexRouter, serviceAuth } from '@atproto/lex-server'
import { serve } from '@atproto/lex-server/nodejs'
import * as app from './lexicons/app.js'

// =============================================================================
// Configuration
// =============================================================================

interface FeedConfig {
    publisherDid: DidString
    feedName: string
    searchTerms: string[]
    maxPosts: number
    port: number
    initialRepos: DidString[]
}

const publisherDid = process.env.FEED_PUBLISHER_DID || 'did:example:alice'
if (!isDidString(publisherDid)) {
    throw new Error('FEED_PUBLISHER_DID must be a valid DID')
}

const config: FeedConfig = {
    publisherDid,
    feedName: process.env.FEED_NAME || 'goblin-mode',
    searchTerms: (process.env.FEED_SEARCH_TERMS || 'goblin,goblins,gremlin,gremlins,wizard,wizards,chaos').split(',').map(s => s.trim()),
    maxPosts: parseInt(process.env.FEED_MAX_POSTS || '1000', 10),
    port: parseInt(process.env.FEED_PORT || '3000', 10),
    initialRepos: (process.env.FEED_INITIAL_REPOS || '').split(',').map(s => s.trim()).filter(Boolean).map(s => s as DidString),
}

const FEED_URI: AtUriString = `at://${config.publisherDid}/app.bsky.feed.generator/${config.feedName}` as AtUriString

いくつか注目すべき点があります。FEED_INITIAL_REPOSはJetstreamのDIDフィルターを設定します。デフォルトでは空なので、ネットワーク全体の投稿を受信します。カンマ区切りのDIDを指定すると、特定のアカウントだけを追跡できます。

このフィードは、特定の語句を含む投稿を検索して並び替えます。語句はFEED_SEARCH_TERMS環境変数で設定できます。この例では、ゴブリン(goblin)、グレムリン(gremlin)、魔法使い(wizard)、カオス(chaos)に言及する投稿を集めるgoblin-modeフィードを作ります。

次に、Jetstreamから投稿を取り込むロジックを設定します。

パート3:Jetstreamからの取り込み

配信対象の投稿は配列に保存します。

Jetstreamはフィルター済みのイベントをデコード済みJSONとしてWebSocket経由で送信します。@bsky/jetstream SDKが接続と再接続を処理します。以下の内容をsrc/index.tsに追加してください。

// =============================================================================
// Post Index
// =============================================================================

interface IndexedPost {
    uri: AtUriString
    indexedAt: number
}

const postIndex: IndexedPost[] = []
const jetstream = new Jetstream('https://jetstream.us-east.bsky.network')

function escapeRegExp(value: string) {
    return [...value].map(char => '.^$*+?()[]{}|\\'.includes(char) ? `\\${char}` : char).join('')
}

const searchPattern = new RegExp(
    `\\b(${config.searchTerms.map(escapeRegExp).join('|')})\\b`,
    'i'
)

async function indexJetstream(signal: AbortSignal) {
    for await (const evt of jetstream.live({
        collections: ['app.bsky.feed.post'],
        ...(config.initialRepos.length > 0 && { dids: config.initialRepos }),
        kinds: ['commit', 'account'],
        signal,
    })) {
        if (evt.kind === 'account') {
            if (evt.account.active) continue
            const removed = postIndex.filter(p => p.uri.startsWith(`at://${evt.did}/`)).length
            if (removed > 0) {
                postIndex.splice(0, postIndex.length, ...postIndex.filter(p => !p.uri.startsWith(`at://${evt.did}/`)))
                console.log(`Account ${evt.did} inactive: removed ${removed} posts`)
            }
            continue
        }

        if (evt.kind !== 'commit' || evt.commit.collection !== 'app.bsky.feed.post') continue

        const { rkey } = evt.commit
        const uri = `at://${evt.did}/app.bsky.feed.post/${rkey}` as AtUriString
        const idx = postIndex.findIndex(p => p.uri === uri)

        if (evt.commit.operation === 'delete') {
            if (idx !== -1) {
                postIndex.splice(idx, 1)
                console.log(`DELETE ${uri}`)
            }
            continue
        }

        const text = typeof evt.commit.record?.text === 'string' ? evt.commit.record.text : ''
        if (!searchPattern.test(text)) {
            if (idx !== -1) postIndex.splice(idx, 1)
            continue
        }

        if (idx !== -1) postIndex.splice(idx, 1)
        postIndex.unshift({ uri, indexedAt: Date.now() })
        if (postIndex.length > config.maxPosts) postIndex.pop()

        const preview = text.substring(0, 60).replace(/\n/g, ' ')
        console.log(`${evt.commit.operation.toUpperCase()} ${uri}`)
        console.log(`  \"${preview}${text.length > 60 ? '...' : ''}\"`)
        console.log(`  ⭐ Added to index (${postIndex.length} total)`)
    }
}

このコードはapp.bsky.feed.postのコミットを対象にライブ購読します。デフォルトではネットワーク全体の投稿を受信します。FEED_INITIAL_REPOSにカンマ区切りのDIDを指定すると、それらのアカウントだけを追跡します。

投稿の作成または更新時に、コードは設定された検索語をテキストから探し、一致した投稿をpostIndexに追加します。一致しなくなった投稿や削除された投稿を取り除き、アカウントイベントでアカウントが非アクティブと報告された場合も、そのアカウントの投稿を取り除きます。レコードはデコード済みJSONで届くため、Tapを実行したり、追加でデコードしたりする必要はありません。

この例はライブストリームのみを使うため、起動後に届いた投稿をインデックスします。過去の投稿を取得する方法はJetstream Replayのドキュメントを参照してください。

パート4:フィード配信

次に、フィードを配信するためのXRPCルートを追加します。サーバーは次の2種類のリクエストを扱います。

GET /xrpc/app.bsky.feed.describeFeedGenerator
GET /xrpc/app.bsky.feed.getFeedSkeleton

src/index.tsにフィードジェネレーターサーバーのロジックを追加します。

// =============================================================================
// Feed Generator Server
// =============================================================================

// Auth is optional for this demo since we only log the requester's DID.
// In production, you may want to use credentials to personalize the feed.
const auth = serviceAuth({
    audience: config.publisherDid,
    unique: async () => true,
})

const router = new LexRouter()

router.add(app.bsky.feed.describeFeedGenerator, {
    auth,
    handler: (ctx) => {
        console.log('describeFeedGenerator from', ctx.credentials?.did)
        return {
            body: {
                did: config.publisherDid,
                feeds: [app.bsky.feed.describeFeedGenerator.feed.$build({ uri: FEED_URI })],
                links: {
                    privacyPolicy: 'https://example.com/privacy',
                    termsOfService: 'https://example.com/tos',
                },
            },
        }
    },
})

router.add(app.bsky.feed.getFeedSkeleton, {
    auth,
    handler: (ctx) => {
        if (ctx.params.feed !== FEED_URI) {
            throw new LexError('InvalidRequest', 'Feed not found')
        }
        console.log('getFeedSkeleton from', ctx.credentials?.did)

        const limit = Math.min(ctx.params.limit ?? 50, 100)
        const cursor = ctx.params.cursor as string | undefined

        let startIdx = 0
        if (cursor) {
            const cursorTime = parseInt(cursor, 10)
            startIdx = postIndex.findIndex(p => p.indexedAt < cursorTime)
            if (startIdx === -1) startIdx = postIndex.length
        }

        const slice = postIndex.slice(startIdx, startIdx + limit)
        const feed = slice.map(p => app.bsky.feed.defs.skeletonFeedPost.$build({ post: p.uri }))
        const lastPost = slice.at(-1)
        const nextCursor = lastPost && slice.length === limit && startIdx + limit < postIndex.length
            ? lastPost.indexedAt.toString()
            : undefined

        return { body: { feed, cursor: nextCursor } }
    },
})

ここでは@atproto/lex-serverパッケージのLexRouterを使ってXRPCルートを定義しています。getFeedSkeletonメソッドはレスポンスでcursorを返し、入力としてもcursorパラメータを受け取ります。これによりクライアントはフィードをページネーションできます。

最後に、サーバーを起動するためのランタイムロジックを追加します。

パート5:サーバー起動

Jetstreamのコンシューマーを起動してからサーバーを起動します。以下のランタイムロジックをsrc/index.tsに追加してください。

// =============================================================================
// Start
// =============================================================================

const jetstreamAbort = new AbortController()
const indexer = indexJetstream(jetstreamAbort.signal).catch((err) => {
    if (!jetstreamAbort.signal.aborted) console.error('Jetstream error:', err)
})
console.log('Connecting to Jetstream...')

serve(router, { port: config.port }).then((server) => {
    const feedParam = encodeURIComponent(FEED_URI)
    const repoFilter = config.initialRepos.length > 0 ? config.initialRepos.length : 'all accounts'

    console.log(`
Feed Generator Running

Server: http://localhost:${config.port}
Feed: ${config.feedName}
Terms: ${config.searchTerms.join(', ')}
Jetstream: US East
DID filter: ${repoFilter}

To test (generate a JWT with goat):
goat account service-auth --aud ${config.publisherDid}

Then:
curl -H "Authorization: Bearer <jwt>" "http://localhost:${config.port}/xrpc/app.bsky.feed.getFeedSkeleton?feed=${feedParam}"

Listening for posts matching: ${config.searchTerms.join(', ')}
`)

    const shutdown = async () => {
        console.log('Shutting down...')
        jetstreamAbort.abort()
        await indexer
        await server.terminate()
        process.exit(0)
    }

    process.on('SIGINT', shutdown)
    process.on('SIGTERM', shutdown)
})

これでJetstreamコンシューマー(フィード入力)とXRPCサーバー(フィード出力)が開始されます。SDKはライブストリームを再接続します。

npx tsx src/index.tsで実行します。新しい一致投稿が届くとインデックスされます。

Connecting to Jetstream...

Feed Generator Running

Server: http://localhost:3000
Feed: goblin-mode
Terms: goblin, goblins, gremlin, gremlins, wizard, wizards, chaos
Jetstream: US East
DID filter: all accounts

To test (generate a JWT with goat):
goat account service-auth --aud did:example:alice

Then:
curl -H "Authorization: Bearer " "http://localhost:3000/xrpc/app.bsky.feed.getFeedSkeleton?feed=at%3A%2F%2Fdid%3Aexample%3Aalice%2Fapp.bsky.feed.generator%2Fgoblin-mode"

Listening for posts matching: goblin, goblins, gremlin, gremlins, wizard, wizards, chaos

CREATE at://did:plc:q6gjnaw2blty4crticxkmujt/app.bsky.feed.post/3myxs2zcgjk2a
  "entering my goblin era. do not perceive me"
  ⭐ Added to index (1 total)

結論

これで、ネットワークから投稿を取得し、独自アルゴリズムでインデックスし、BlueskyのようなクライアントへXRPC経由で配信するカスタムatprotoフィードを構築できました。

フィードサーバーが動作したので、さらにカスタマイズして他の人が使えるように公開できます。そのためには、公開サーバー(例:AWS、DigitalOceanなど)へデプロイし、HTTPSでアクセス可能にしてください。

その後、公式のfeed-generatorリポジトリをクローンし、publishFeedGen.tsスクリプトを対話的に実行できます。これにより、あなたのフィードサーバーを指すために必要なatprotoレコードが作成され、発見可能になります。

さらに多くのガイドやチュートリアルはGuidesセクションで、より多くのサンプルアプリはCookbookリポジトリで確認できます。ぜひ開発を楽しんでください。