Developers · Services

Services

@civility/services calls external services, such as AI providers, from your app. A call can use the user's own API key or a key the server operator provides.

Install

deno add jsr:@civility/services
Import Contents
@civility/services Services, ServiceError, defineService, summarizeUsage, types.
@civility/services/ai claude, openai, gemini, localProxy, and the text helpers.
@civility/services/podcast podcastindex, rssfetch, and Podcast Index helpers.

generateStructured takes a Zod schema, so add jsr:@zod/zod if you use it.

Call an AI provider with the user's key

The helpers in @civility/services/ai call the provider directly from the browser. You supply the key, for example from a settings field in your app.

import { generateText } from '@civility/services/ai'

const summary = await generateText({
  prompt: `Summarize this note in one sentence:\n\n${note.body}`,
  config: { apiKey, provider: 'claude' },
})
import { z } from '@zod/zod'
import { generateStructured } from '@civility/services/ai'

const Recipe = z.object({
  title: z.string(),
  ingredients: z.array(z.string()),
  steps: z.array(z.string()),
})

const recipe = await generateStructured({
  prompt: 'Extract a recipe from the following text.',
  userDescription: pastedText,
  schema: Recipe,
  config: { apiKey, provider: 'claude' },
})
// recipe is z.infer<typeof Recipe>, already validated
Helper Returns
generateText(options) Promise<string>
streamText(options) AsyncGenerator<string> of text pieces. Does not support tools.
generateStructured(options) Promise<z.infer<schema>>
createClient(config) { generateText, generateStructured } bound to one config.
config field Notes
apiKey The provider key. Ignored when runtime is set.
runtime A Services instance. The call then goes through it instead of straight to the provider.
provider 'claude', 'openai' or 'gemini'. Default 'claude'.
model Provider model id. Each provider has a default.
maxTokens
fetch Replacement for the global fetch.

Gemini does not allow browser requests (no CORS). Call it through a Services instance and a server, or from a non-browser runtime. The images and tools options work with Claude only.

The Services object

Services reads the server's service catalog, picks how each call runs, stores credentials, and records usage.

import { Services } from '@civility/services'
import { claude } from '@civility/services/ai'

const conn = cloud.connection // null until signed in
if (!conn) throw new Error('Not connected')

const services = new Services({
  serverUrl: conn.serverUrl,
  app: { id: APP_ID, token: conn.token },
  registry: { 'ai.claude': claude },
})

const out = await services.invoke<{ text: string }>('ai.claude', {
  messages: [{ role: 'user', content: 'Hello' }],
})
Config Notes
serverUrl Required. The Civility server.
app { id, token }: the app id and its sync token. Required for server-proxy and bundle.
registry Service definitions by name. Required for client-direct.
credentials The _civility.credentials collection. Enables services.credentials.
usage The _civility.usage collection. Enables usage records and quotas.
usageRetentionDays Default 90. Older usage records are deleted.
env { allowCorsBypass? } for runtimes that are not bound by CORS.
fetch Replacement for the global fetch.
Member Notes
catalog(force?) The server's services and what it supports. Cached.
resolveMode(service, grant?) The mode a call would use.
invoke<T>(service, input, opts?) One call. opts: { grant?, secret? }.
invokeStream<T>(service, input, opts?) Streaming call. opts also takes signal.
credentials list(), create(input), update(id, patch), delete(id).
usage.list() Local usage records, oldest first.

Modes

Each call runs in one of three modes. Services picks the first available in the order bundle, server-proxy, client-direct.

Mode Path Credential Needs
bundle App → Civility server → provider The operator's key. Counted against the user's monthly quota. Proxy on, and a bundle key for the service.
server-proxy App → Civility server → provider The user's key, sent sealed to the server for the call. Proxy on.
client-direct App → provider The user's key, sent only to the provider. The provider allows CORS, and the service is in registry.

The server operator decides whether the proxy and bundle keys are available; see hosting services. A self-hosted server may have the proxy off, so make sure your app works with client-direct and the user's own key.

Streaming

import type { ChatChunk } from '@civility/services/ai'

for await (
  const chunk of services.invokeStream<ChatChunk>('ai.claude', input)
) {
  if (chunk.text) render(chunk.text)
}

If the service or server cannot stream, you get the whole output as one chunk.

Stored credentials

Declare the _civility.credentials collection in your store and pass it to Services. Calls then use the stored credential whose serviceScope best matches the service. opts.secret overrides it for one call.

import { CREDENTIALS_COLLECTION, Services } from '@civility/services'

const services = new Services({
  serverUrl,
  credentials: store.collection(CREDENTIALS_COLLECTION),
})

const cred = await services.credentials.create({
  serviceScope: 'ai.claude', // or 'ai.*'
  label: 'My Claude key',
  kind: 'api-key',
  secret: { key: apiKey },
})
await services.credentials.update(cred.id, { secret: { key: rotatedKey } })
await services.credentials.delete(cred.id)

The secret is stored as plain JSON and syncs like any other record. Encrypt it yourself if you need to; see Encrypting your data.

Usage and quotas

Pass usage: store.collection(USAGE_COLLECTION) to record one event per call, with the credential that was used. summarizeUsage(events, sinceIso?) totals events per credential and service.

A quota is { period: 'day' | 'month', maxInvocations?, maxCostUSD? }. Set it on a credential (quota field) or on a grant passed as opts.grant. Services checks it against the local usage records before each call, so it needs the usage collection. maxCostUSD is approximate: a cost is recorded only when the server reports one, which it does for bundle calls on a key the operator has priced. client-direct calls record no cost.

Declare services in the manifest

List the services your app uses in its manifest. The user approves them on the consent page along with data permissions.

{
  "name": "My App",
  "services": [
    {
      "scope": "ai.*",
      "reason": "Summarize and import notes",
      "optional": true
    }
  ]
}

scope is a service name or a wildcard: ai.* covers ai.claude and ai.openai. The server checks the grant on every server-proxy and bundle call.

Errors

Failures throw a ServiceError with a code.

Code Meaning
services.no_supported_mode No mode is available for this service.
services.grant_denied The app has no grant covering this service.
services.quota_exceeded A quota is used up. detail.layer is host, grant or credential.
services.credential_missing No credential, or no credentials collection.
services.credential_unwrap The server could not open the sealed credential.
services.input_invalid The input failed the service's schema.
services.upstream_error The provider failed or could not be reached.
services.egress_denied The server refused the outbound request.
services.rate_limited Too many calls. Retry later.
import { ServiceError } from '@civility/services'

try {
  await services.invoke('ai.claude', input)
} catch (e) {
  if (!(e instanceof ServiceError)) throw e
  if (e.code === 'services.quota_exceeded') showQuotaMessage()
  else if (e.code === 'services.no_supported_mode') askForApiKey()
  else throw e
}

Reference