Skip to content

Server 端插件

创建插件

typescript
const myPlugin = {
  hooks: {
    beforeHandler: async (ctx) => { ... },
    afterHandler: async (ctx, result) => { ... },
  }
}

server.use(myPlugin)

Hooks

beforeStart

Server 启动前:

typescript
{
  beforeStart: async ({ config }) => {
    console.log('准备启动:', config.name)
    await initResources()
  }
}

onStart

Server 启动后:

typescript
{
  onStart: async ({ port, config }) => {
    console.log(`${config.name} 启动在端口 ${port}`)
  }
}

beforeMessage

消息处理前:

typescript
{
  beforeMessage: async (ctx) => {
    console.log('消息:', ctx.message.type)

    // 验证权限
    const userId = ctx.metadata.get('x-user-id')[0]
    if (!userId) {
      ctx.stream.send({ type: 'error', text: 'Unauthorized' })
      return 'handled'  // 跳过后续处理
    }
  }
}

onMessage

处理自定义消息类型:

typescript
{
  onMessage: async (ctx) => {
    if (ctx.message.type === 'heartbeat') {
      ctx.stream.send({ type: 'heartbeat-ack', text: 'pong' })
      return 'handled'
    }
    return 'pass'
  }
}

onCall

技能调用时:

typescript
{
  onCall: async (ctx) => {
    console.log('调用技能:', ctx.skill)

    // 可以转发到其他 Agent
    if (shouldForward(ctx.skill)) {
      await forward(ctx)
      return 'handled'
    }
  }
}

onCancel

取消请求时:

typescript
{
  onCancel: async (ctx) => {
    console.log('取消:', ctx.streamId)
    await cleanup(ctx.streamId)
  }
}

beforeHandler

Handler 执行前:

typescript
{
  beforeHandler: async (ctx) => {
    ctx.startTime = Date.now()
  }
}

afterHandler

Handler 执行后:

typescript
{
  afterHandler: async (ctx, result) => {
    const duration = Date.now() - ctx.startTime
    console.log(`${ctx.skill} 耗时 ${duration}ms`)
  }
}

onError

错误处理:

typescript
{
  onError: async (ctx, error) => {
    console.error('错误:', error.message)
    await reportError(error)
  }
}

onGetAgentCard

修改返回的 AgentCard:

typescript
{
  onGetAgentCard: async (card) => ({
    ...card,
    skills: [...card.skills, ...dynamicSkills]
  })
}

完整示例:日志插件

typescript
const createLoggingPlugin = (level = 'info') => ({
  hooks: {
    onStart: async ({ port, config }) => {
      console.log(`[${level}] ${config.name} started on ${port}`)
    },

    beforeHandler: async (ctx) => {
      console.log(`[${level}] Calling ${ctx.skill}`)
      ctx.startTime = Date.now()
    },

    afterHandler: async (ctx) => {
      const duration = Date.now() - ctx.startTime
      console.log(`[${level}] ${ctx.skill} completed in ${duration}ms`)
    },

    onError: async (ctx, error) => {
      console.error(`[error] ${ctx.skill}:`, error.message)
    }
  }
})

server.use(createLoggingPlugin('debug'))

完整示例:权限验证插件

typescript
const createAuthPlugin = (validate: (token: string) => Promise<boolean>) => ({
  hooks: {
    beforeMessage: async (ctx) => {
      const token = ctx.metadata.get('authorization')[0]

      if (!token || !await validate(token)) {
        ctx.stream.send({ type: 'error', text: 'Unauthorized' })
        return 'handled'
      }
    }
  }
})

server.use(createAuthPlugin(async token => {
  return await verifyToken(token)
}))

MIT Licensed