Skip to content

Hooks

ServerHooks

typescript
interface ServerHooks {
  beforeStart?: ({ config }) => Promise<void>
  onStart?: ({ port, config }) => Promise<void>
  beforeMessage?: (ctx) => Promise<HookResult>
  afterMessage?: (ctx) => Promise<void>
  onMessage?: (ctx) => Promise<HookResult>
  onCall?: (ctx) => Promise<HookResult>
  onCancel?: (ctx) => Promise<HookResult>
  beforeHandler?: (ctx) => Promise<void>
  afterHandler?: (ctx) => Promise<void>
  onError?: (ctx, error) => Promise<void>
  onGetAgentCard?: (card) => Promise<AgentCard>
}

示例

typescript
const plugin = {
  hooks: {
    onStart: async ({ port, config }) => {
      console.log(`${config.name} started on ${port}`)
    },

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

    afterHandler: async (ctx) => {
      console.log(`${ctx.skill} took ${Date.now() - ctx.startTime}ms`)
    },

    onError: async (ctx, error) => {
      console.error('Error:', error.message)
    }
  }
}

ClientHooks

typescript
interface ClientHooks {
  beforeCall?: (ctx) => Promise<void>
  afterCall?: (ctx, stream) => Promise<BidirectionalStream>
  onError?: (ctx, error) => Promise<void>
}

示例

typescript
const plugin = {
  hooks: {
    beforeCall: async (ctx) => {
      ctx.metadata['authorization'] = `Bearer ${token}`
    },

    afterCall: async (ctx, stream) => {
      console.log('Connected')
      return stream
    }
  }
}

HookResult

typescript
type HookResult = 'handled' | 'pass' | 'exit' | void

// 'handled' - 跳过默认处理
// 'pass'    - 继续默认处理(默认)
// 'exit'    - 退出消息循环

示例:缓存

typescript
const plugin = {
  hooks: {
    onCall: async (ctx) => {
      const cached = cache.get(ctx.skill + ctx.params)
      if (cached) {
        ctx.stream.send({ type: 'done', data: cached })
        return 'handled'  // 跳过 handler
      }
      return 'pass'
    }
  }
}

执行顺序

请求 → beforeMessage → onCall → beforeHandler → handler → afterHandler → afterMessage → 响应

MIT Licensed