Building Connectors

A connector is a self-contained integration with an external system. It declares the events it produces, the methods it exposes, and a setup function that wires everything together at runtime.

defineConnector()

defineConnector() accepts a ConnectorDefinition: a manifest plus a setup function that returns a runtime:

import { defineConnector } from '@yellatech/conduit'

export const myConnector = defineConnector({
  name: 'my-connector',
  version: '1.0.0',
  description: 'Connects to MyService',
  events: {
    'message': { description: 'New message received' },
  },
  methods: {
    'send': {
      description: 'Send a message',
      input: { text: { type: 'string' } },
    },
  },
  config: {
    apiKey: { required: true, secret: true, description: 'MyService API key' },
    channel: { required: false, default: 'general' },
  },
  setup(ctx) {
    // ctx.emit, ctx.status, ctx.config, ctx.auth, ctx.routes
    return {
      start() { /* connect to service */ },
      stop() { /* disconnect */ },
      methods: {
        send: async (input, methodCtx) => { /* implementation */ },
      },
    }
  },
})

The manifest fields (name, version, events, methods, config) are declarative metadata. The setup function receives a ConnectorContext and returns a ConnectorRuntime with optional start, stop, and methods.

Events

Declare events in the manifest with a description and optional payload schema:

events: {
  'message': { description: 'New message received', payload: { text: { type: 'string' } } },
  'status-change': { description: 'Service status changed' },
}

Emit events from inside setup via ctx.emit:

setup(ctx) {
  const poll = setInterval(async () => {
    const messages = await fetchMessages()
    for (const msg of messages) {
      ctx.emit('message', { text: msg.text, author: msg.author })
    }
  }, 5000)

  return {
    start() {},
    stop() { clearInterval(poll) },
  }
}

Events arrive in your processes as connectorName:eventName. Register handlers with the prefixed name:

app.process('my-connector:message', {
  handler: async (ctx) => {
    console.log(ctx.payload) // { text: '...', author: '...' }
  },
})

Methods

Methods support three implementation styles. When a method is invoked, Conduit checks for an implementation in this order:

flowchart TD I["invoke(connector, method, input)"] --> V{"validateInput\nschema?"} V -->|yes| VP["Parse input"] V -->|no| RP["Use raw input"] VP --> R RP --> R R{"runtime.methods[name]\nexists?"} -->|yes| RM["Execute runtime method"] R -->|no| D{"definition.methods[name].run\nexists?"} D -->|yes| RF["Execute run function"] D -->|no| H{"definition.methods[name].http\nexists?"} H -->|yes| HM["Execute HTTP template"] H -->|no| ERR["Error: no implementation"] RM --> VO{"validateOutput\nschema?"} RF --> VO HM --> VO VO -->|yes| VOP["Parse output"] VO -->|no| RET["Return result"] VOP --> RET

Runtime methods (from setup()) take priority, letting you override declarative definitions with imperative logic at startup time.

Declare methods in the manifest with a description, optional permissions, and input/output schemas:

methods: {
  'send': {
    description: 'Send a message',
    permissions: ['messages:write'],
    input: { text: { type: 'string' }, channel: { type: 'string' } },
    output: { id: { type: 'string' } },
  },
}

Implement methods in the runtime’s methods object:

setup(ctx) {
  return {
    methods: {
      send: async (input, methodCtx) => {
        const res = await fetch('https://api.myservice.com/messages', {
          method: 'POST',
          body: JSON.stringify(input),
        })
        return res.json()
      },
    },
  }
}

For simple HTTP calls, use the http template instead of writing a run function:

methods: {
  'send': {
    description: 'Send a message',
    http: {
      method: 'POST',
      path: '/api/messages',
      baseUrl: 'https://api.myservice.com',
      body: { text: '{{input.text}}' },
      auth: { type: 'api_key', key: 'sk-...', headerName: 'Authorization', prefix: 'Bearer' },
    },
  },
}

Config

Define configuration fields using ConnectorConfigField:

config: {
  apiKey: { required: true, secret: true, description: 'MyService API key' },
  channel: { required: false, default: 'general' },
  webhookUrl: { required: true, description: 'Webhook endpoint URL' },
}

Each field supports:

Pass config values when registering the connector:

app.connector(myConnector, {
  config: { apiKey: 'sk-...', channel: 'alerts' },
})

Access config inside setup via ctx.config:

setup(ctx) {
  const client = new MyServiceClient(ctx.config.apiKey as string)
  // ...
}

Registration Flow

When you call app.connector(def, opts), conduit performs several steps before the connector is considered running:

sequenceDiagram participant App as app.connector() participant DB as ConduitDb participant Def as ConnectorDefinition participant RT as ConnectorRuntime participant Hono as Hono Router App->>App: Stop existing connector (if re-registering) App->>DB: Load saved config (getConnectorConfig) App->>App: Merge: definition defaults + DB config + code opts App->>DB: Resolve auth (by name or from opts) App->>Def: Call setup(ctx) with merged config, auth, routes Def-->>RT: Return ConnectorRuntime App->>RT: Build method handle (callable functions) App->>Hono: Mount connector routes at /connectors/{name} App->>App: Record audit routes App->>RT: Call start() RT-->>App: Connector running App->>App: Update status → healthy

Config values merge in priority order: definition defaults < DB-stored config < code overrides (passed via opts.config). This lets you set defaults in the connector definition, override them via the admin API, and pin specific values in code.

Lifecycle

State machine

Connectors track their runtime status through the observability system. The state machine governs transitions:

stateDiagram-v2 [*] --> starting : app.connector() starting --> healthy : start() succeeds starting --> errored : start() throws healthy --> degraded : method error healthy --> stopped : stop() healthy --> reconnecting : app.reconnect() degraded --> healthy : method succeeds degraded --> stopped : stop() degraded --> errored : lifecycle error errored --> reconnecting : app.reconnect() errored --> stopped : stop() reconnecting --> healthy : start() succeeds reconnecting --> errored : start() throws stopped --> starting : re-register stopped --> [*]

consecutiveFailures increments on each method or lifecycle error and resets to 0 on any success (method:success, start, or reconnect).

start()

Called when the connector is registered. Set up connections, polling loops, websocket listeners, or anything that needs to run continuously:

return {
  start() {
    ws = new WebSocket(ctx.config.wsUrl as string)
    ws.on('message', (data) => ctx.emit('message', JSON.parse(data)))
  },
}

stop()

Called on app.stop() or app.reconnect(). Clean up resources:

return {
  stop() {
    ws?.close()
    clearInterval(pollInterval)
  },
}

ctx.status()

Report connector health at any time. Valid statuses: 'starting', 'healthy', 'degraded', 'reconnecting', 'stopped', 'errored':

setup(ctx) {
  ctx.status('healthy')

  ws.on('close', () => ctx.status('stopped'))
  ws.on('error', (err) => ctx.status('errored', { message: err.message }))
}

app.reconnect(name)

Stops a connector and re-registers it with a fresh setup call. Useful for recovering from errors or applying config changes:

await app.reconnect('my-connector')

HTTP Routes

ctx.routes is a Hono instance mounted at /connectors/:name/. Use it for webhook receivers, OAuth callbacks, or any custom HTTP endpoints:

setup(ctx) {
  ctx.routes.post('/webhook', async (c) => {
    const body = await c.req.json()
    ctx.emit('webhook', body)
    return c.json({ ok: true })
  })

  ctx.routes.get('/oauth/callback', async (c) => {
    const code = c.req.query('code')
    // exchange code for token...
    return c.redirect('/dashboard')
  })

  return { start() {}, stop() {} }
}

The webhook endpoint above would be available at POST /connectors/my-connector/webhook.

Built-in Connectors

Conduit has built-in cron support via app.cron(): no separate package needed. See Configuration.

PackageDescription
@yellatech/conduit-webhookInbound webhook receiver with optional HMAC verification
@yellatech/conduit-discordDiscord bot integration
@yellatech/conduit-emailEmail connector (IMAP + SMTP)

Next Steps