Skip to Content

Engine SDK

Plugin.define, tools, Tool.Error, skills and Rpc.define for a plugin's engine part.

The engine part runs inside the conciv engine. Write it with Effect from @conciv/plugin/effect. The promise entry, @conciv/plugin, does the same without Effect: see The promise entry.

pnpm add effect
pnpm add -D @conciv/plugin

Define the plugin

Plugin.define({id, effect}) is the default export of the engine part. The engine runs effect(ctx) when it loads the plugin. Each ctx domain returns an Effect.

packages/plugins/recorder/src/index.ts
function servicesLayer(config: RecorderConfig, directory: string) {
  const rings = ClientRingsModel.clientRingsLayer({windowMs: config.windowMinutes * 60_000})
  return Layer.mergeAll(
    CaptureControlModel.captureControlLayer.pipe(Layer.provideMerge(rings)),
    RecordingStoreModel.recordingStoreLayer(directory),
    RendererCacheModel.rendererCacheLayer(launchChromiumRenderer),
  )
}

export default Plugin.define<Scope.Scope | FileSystem.FileSystem | Path.Path>({
  id: 'recorder',
  effect: (ctx) =>
    Effect.gen(function* () {
      const config = yield* Effect.sync(() => recorderConfig.parse(ctx.options))
      const path = yield* Path.Path
      const services = yield* Layer.build(servicesLayer(config, recordingsDirectory(path, ctx.location.directory)))
      yield* Effect.gen(function* () {
        const recordings = yield* RecordingStore
        const control = yield* CaptureControl
        yield* Effect.forkScoped(recordings.sweep, {startImmediately: true})
        const announcements = yield* Queue.unbounded<Announcement>()
        yield* register(ctx)
        yield* ctx.skill.transform((editor) => editor.add(info))
        const registration = yield* registerRpc(ctx.rpc, config, announcements).pipe(Effect.orDie)
        yield* Stream.fromQueue(announcements).pipe(
          Stream.merge(Stream.map(control.controls, (message): Announcement => ['control', message])),
          Stream.runForEach((event) =>
            registration.events
              .emit(...event)
              .pipe(Effect.catch(reportUndelivered), Effect.catchDefect(reportUndelivered)),
          ),
          Effect.forkScoped({startImmediately: true}),
        )
      }).pipe(Effect.provideContext(services))
    }),
})

The effect runs in a scope that closes when the plugin stops or reloads. Every tool, skill and RPC handler it registers is removed then, and so is every service built in it, like the Layer.build above.

The ctx fields this page uses:

Prop

Type

Tools

Add tools inside ctx.tool.transform. editor.namespace describes a group, and editor.add adds one tool. execute returns an Effect of the result:

packages/plugins/recorder/src/tools.ts
export const register = Effect.fn('RecorderTools.register')(function* (ctx: Pick<Context, 'tool'>) {
  const services = yield* Effect.context<ClientRingsInterface | RendererCacheInterface>()
  const control = yield* CaptureControl
  const pull = (fromTs: number, toTs: number, keyframes: number) =>
    pullWindow(fromTs, toTs, keyframes).pipe(Effect.provideContext(services))
  yield* ctx.tool.transform((editor) => {
    editor.namespace({
      name: 'recording',
      description:
        "Marked recordings of the user's app page: start one, act, stop it, or pull the last seconds. Each answers a semantic action log plus keyframe screenshots.",
    })
    editor.add({
      name: 'start',
      description:
        "Start a marked recording of the user's app page. Waits for the page to attach and begin streaming, then returns a captureId, so acting right after it returns is safe. Use before performing page actions you want to review, then call recording_stop.",
      input: z.object({}),
      output: z.object({captureId: z.string(), startedAt: z.number()}),
      options,
      execute: () =>
        Effect.gen(function* () {
          const {captureId, startTs, appendCursor} = yield* control.startCapture
          const covered = yield* control.awaitAppendAfter(appendCursor, START_WAIT_MS)
          if (covered) return {output: {captureId, startedAt: startTs}}
          yield* control.stopCapture(captureId).pipe(Effect.ignore)
          return yield* Effect.fail(
            Tool.makeError({
              message: 'no page client attached within 5s; the app page with the widget must be open to record',
            }),
          )
        }),
    })
  })
})

Prop

Type

A schema is a zod schema, any Standard Schema (Valibot, ArkType ...), an Effect Schema, or a raw JSON Schema object.

execute gets a context with sessionId, agent, the call id, and progress(update).

Tool.Error

Fail the effect with a Tool.Error to fail the call with a message the agent reads. Make one with Tool.makeError or Tool.toolError. metadata travels with it:

packages/plugins/tanstack/src/tools.ts
function toolFailure(failure: Failure) {
  return Tool.toolError({message: failure.message, error: failure.error, metadata: {code: failure.code}})
}
packages/plugins/tanstack/src/tools.ts
execute: () =>
  tanstack.buildErrors().pipe(
    Effect.map((output) => ({output})),
    Effect.mapError(toolFailure),
  ),

A typed failure becomes a Tool.Error once, at the edge, with catchTag:

packages/plugins/recorder/src/tools.ts
execute: ({captureId, keyframes}) =>
  Effect.gen(function* () {
    const range = yield* control.stopCapture(captureId)
    yield* control.awaitAppendAfter(range.appendCursor, FLUSH_WAIT_MS)
    return yield* pull(range.startTs, range.stopTs, keyframes)
  }).pipe(
    Effect.catchTag('RecorderCaptureNotFound', (missing) =>
      Effect.fail(Tool.makeError({message: `no active capture ${missing.captureId}`})),
    ),
  ),

Skills

Add a skill inside ctx.skill.transform. The agent sees its description and loads its content when it needs it.

packages/plugins/recorder/src/skill.ts
import {Skill} from '@conciv/plugin'
import {AbsolutePath} from '@conciv/plugin/schema/schema'

export const info: Skill.Info = {
  id: Skill.Id.make('recorder'),
  name: Skill.Name.make('Recorder'),
  description:
    "Record what happens on the user's app page and read it back as an action log with keyframe screenshots. Load it before your first recording tool call.",
  path: AbsolutePath.make('skill://recorder/SKILL.md'),
  content: [
    '# Recorder',
    '',
    "The recorder keeps a short recording of the user's app page while a recording is live. Nothing is recorded unless a recording was requested. Call its three tools from code mode; `discover_tools` shows their exact signatures.",
  ].join('\n'),
}
packages/plugins/recorder/src/index.ts
yield * ctx.skill.transform((editor) => editor.add(info))

@conciv/plugin/effect exports the same Skill. For skills written as files in the project, see Skills.

RPC

An RPC contract lets the browser part, another plugin or a terminal call the engine part. Put it in its own module, so both parts import it.

Rpc.define

Rpc.define({id, methods, events}) declares the contract. Each method has an input and output schema, and optional named errors. Each event has a schema.

packages/plugins/recorder/src/rpc.ts
import {Rpc} from '@conciv/plugin/rpc'
import {z} from 'zod'

export const Recorder = Rpc.define({
  id: 'recorder',
  methods: {
    config: {input: NoInput, output: recorderConfig},
    state: {input: NoInput, output: z.object({live: z.boolean()})},
    reset: {input: NoInput, output: OkOutput},
    'recordings.exportVideo': {
      input: z.object({id: z.string().min(1).max(256), offset: z.number().int().nonnegative()}),
      output: VideoPieceOutput,
      errors: {
        expired: z.undefined(),
        missing: z.undefined(),
        'render-failed': z.undefined(),
        unreadable: z.undefined(),
      },
    },
  },
  events: {
    control: {schema: RecorderControlSchema},
    appended: {schema: z.object({clientId: z.string(), cursor: z.number()})},
  },
})

An error name that starts with rpc. is reserved: Rpc.define throws on it.

Register the handlers

ctx.rpc.register(contract, handlers) answers the methods. A handler gets the parsed input and a context with error(name, message, data), which makes one of the method's declared errors, and returns an Effect. Each typed failure maps to a declared error once, at the edge:

packages/plugins/recorder/src/index.ts
'recordings.exportVideo': (input, call) =>
  Effect.gen(function* () {
    const file = yield* recordings.videoFile(input.id)
    const events = yield* recordings.get(input.id)
    yield* renderVideoFile(file, events)
    const piece = yield* readVideoPiece(file, input.offset, MAX_FILE_BYTES)
    return {...piece, ...VIDEO}
  }).pipe(
    Effect.catchTags({
      RecorderRecordingExpired: () => Effect.fail(call.error('expired', `The recording ${input.id} has expired`)),
      RecorderRecordingNotFound: () => Effect.fail(call.error('missing', `There is no saved recording ${input.id}`)),
      RecorderVideoUnrendered: () =>
        Effect.fail(call.error('render-failed', `The recording ${input.id} could not be rendered to video`)),
      RecorderVideoUnreadable: () =>
        Effect.fail(call.error('unreadable', `The video of the recording ${input.id} could not be read`)),
    }),
    Effect.provideContext(services),
  ),

The registration has dispose and events.emit(name, data), which sends an event to every subscriber:

packages/plugins/recorder/src/index.ts
const registration = yield * registerRpc(ctx.rpc, config, announcements).pipe(Effect.orDie)
yield *
  Stream.fromQueue(announcements).pipe(
    Stream.merge(Stream.map(control.controls, (message): Announcement => ['control', message])),
    Stream.runForEach((event) =>
      registration.events.emit(...event).pipe(Effect.catch(reportUndelivered), Effect.catchDefect(reportUndelivered)),
    ),
    Effect.forkScoped({startImmediately: true}),
  )

RPC methods never ask the user. An operation that must ask is a tool.

To call these methods from the widget, see Call the engine part. From a terminal, see conciv plugin call.

The promise entry

@conciv/plugin is the same engine part without Effect. Plugin.define takes setup(ctx) instead of effect, and each ctx domain returns a Promise. setup may be async, and may return a cleanup that runs when the plugin stops or reloads.

packages/plugins/test-runner/src/index.ts
import {Plugin} from '@conciv/plugin'

export default Plugin.define({
  id: 'test-runner',
  async setup(ctx) {
    const config = testRunnerConfig.parse(ctx.options)
    const adapter = getRunner(config.runner) ?? vitest
    const manager = adapter.create(ctx.location.directory)
    await register(ctx.tool, manager)
    await ctx.skill.transform((editor) => editor.add(info))
    const registration = await registerRpc(ctx.rpc, manager)
    const unsubscribe = manager.subscribeRaw((event) => {
      registration.events.emit('event', event).catch((error: unknown) => {
        console.error(`[test-runner] a live test event was not delivered: ${String(error)}`)
      })
    })
    return () => {
      unsubscribe()
      return manager.stop()
    }
  },
})

A tool's execute and an RPC handler return a Promise. A tool fails a call by throwing Tool.toolError:

packages/plugins/whiteboard/src/tool/refusal.ts
import {Tool} from '@conciv/plugin'

type Failure = {code?: string; message: string; error?: unknown}

export function fail({code, ...failure}: Failure): never {
  throw Tool.toolError(code === undefined ? failure : {...failure, metadata: {code}})
}

On this page