Skip to content
Spools
Documentation
On this page

Extending

Most changes are config: see the configuration reference. When config isn't enough, extend in code. Server-side extensions live in one file you own, src/app/extensions.ts:

ts
import { defineExtensions } from '@swirls/spools/extensions'export default defineExtensions({  handlers: {}, // "run": "local:<name>"  runTargets: {}, // new "<kind>:<name>" targets  hooks: {}, // record lifecycle  email: undefined, // campaign email transport})

The full contract, with types, is packages/spools/src/crm/extensions.ts.

A feature set others could use too (its objects, its code, its own tables, panels and pages) is better written as a module: a package any Spool lists in modules, whose hooks run before yours and whose clashes with yours are refused instead of silently won.

Handlers: run your own code from a button or automation#

ts
handlers: {  async markVip(ctx) {    await updateRecord(ctx.objectKey, ctx.record.id, { status: "customer" }, ctx.actor);    return { message: "Marked as VIP" };  },},
json
{ "id": "markVip", "label": "Mark as VIP", "run": "local:markVip" }

ctx is { objectKey, record, actor, trigger }. Import updateRecord and friends from @swirls/spools/extensions so hooks and automations still run. The returned message is shown to the user. Return open as well ({ message, open: "/deals/<id>" }) and the record page goes to that page of the CRM once the handler has run.

To make one record from another (a lead into a deal), reach for conversions in the config first: a handler is for what a conversion can't say.

Hooks: react to record changes#

Hooks run for every write, whether it comes from the CRM or the assistant.

ts
hooks: {  // Return new values to change them. Throw to reject the change.  beforeCreate({ objectKey, values }) {    if (objectKey === "deals" && !values.owner) throw new Error("Deals need an owner");  },  async afterUpdate({ objectKey, record, previous }) {    if (objectKey === "deals" && previous.stage !== "won" && record.stage === "won") {      await notifyTeam(`Won: ${record.title}`);    }  },},

Available hooks: beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete (throw to refuse the delete: nothing is removed) and afterDelete. With modules, each module's hooks run first, in the order they are listed, and yours last. beforeUpdate and afterUpdate receive the previous record. Values returned from a before* hook are still validated against the config. A relations field arrives in values as <field>Ids (a list, or { add, remove }), and on record and previous as <field>, <field>Ids and <field>Count.

A change happens in this order:

  1. The before* hook runs. Throwing here refuses the change: nothing is written, and staff see the message.
  2. The record and its lines on the timeline are written together, as one transaction.
  3. The after* hook and the config's automations run, once the change is kept.

So an after* hook can read the record it is told about and change it again. If it throws, the change stays, and staff see "Saved, but a step after it failed" with the message, so nobody makes the change a second time.

For simple "when X changes, run Y", prefer automations in the config. Use hooks when you need the previous value, want to change or reject the write, or need logic that doesn't belong in a workflow.

Hand a record on to the next step#

A hook can create the records and tasks the next person needs. Import from @swirls/spools/extensions: its createRecord and updateRecord write through the service, so the new records get their own timeline, hooks and automations, and createTask makes the to-dos. (The framework's own modules return Effects, which do nothing when awaited; this file is their promise version.)

ts
import { createRecord, createTask, updateRecord } from "@swirls/spools/extensions";hooks: {  async afterUpdate({ objectKey, record, previous, actor }) {    const won = objectKey === "deals" && record.stage === "won" && previous.stage !== "won";    // Guard on the link, so winning the same deal twice doesn't make two projects.    if (!won || record.projectId) return;    const project = await createRecord("projects", { title: record.title, companyId: record.companyId }, actor);    await updateRecord("deals", record.id, { projectId: project.id }, actor);    await createTask(      // No assignee means whoever is named as the task's creator.      { title: "Send the welcome pack", assigneeId: record.owner ? String(record.owner) : null, objectKey: "projects", recordId: project.id },      actor?.id ?? "system",    );  },},
  • A hook that updates the record it is handling runs again for that update: compare with previous (as above) so it does its work once.
  • actor is null for scripts; a CSV import in the CRM has the teammate who ran it. Decide what a hand-off should do with no actor; bulk imports that call records.createRecord directly skip hooks.
  • To give the new record the old one's folder, see shareRecordFolder in Files.

Hooks and record scopes#

In a Spool with record scopes, what a hook, a handler or a run target does through @swirls/spools/extensions is done with the access of whoever caused it: listRecords in a hook lists what that person could, and createRecord makes a record in the scope they are working in. A script has nobody behind it, so a scoped record is refused until it says it is the system:

ts
import { asSystem, createRecord } from '@swirls/spools/extensions'await asSystem(() => createRecord('contacts', { name: 'Ada', branch: 'north' }, null))

asSystem reaches every scope. Use it in scripts, and in a hook only where the work really is the business's and not the person's.

Three things follow from "whoever caused it":

  • Nobody caused it, nothing is changed. Code that runs with nobody signed in (a script, a webhook, an endpoint of your own behind publicRoute or cronRoute) reads shared objects and changes no record at all, a shared object's included, until it says it is the system. A before hook is not called for a change that is going to be refused: not for a read-only person's, not for one that names a scope its maker can't write, and not for one nobody is behind.
  • A workflow's write-back is about one record, and so is what it sets off. A workflow started for a record calls the tool API under a grant made for that record (Swirls). When its update runs your afterUpdate hook or an automation's handler, that code is bound to the same record: getRecord, updateRecord, deleteRecord, addActivity, listActivities, listTasks, createTask, listNotes, createNote, recordFolder and runTarget work when they are about that record, and listRecords, countMatching, createRecord, updateTask, deleteTask and shareRecordFolder are refused, with a message that says why. asSystem lifts the one record with the scope. A change a person makes in the CRM is bound to no record.
  • Reaching past these functions is your own. @swirls/spools/server/* exports the server's modules for code written with Effect. A program built from them and run with runServer inside a hook works with the caller's whole access, grant or not: the binding to one record is what the functions above do.

Hooks and role access#

When the config gives a role access, the same holds for it, with or without record scopes: a hook, a handler, a run target, and your own crmHandler and apiRoute code work through @swirls/spools/extensions with the role access of the teammate they run for. An object their roles deny is not found (getRecord, listRecords and createRecord reject with the NotFound error), and a change to one they only read is refused in words.

So a hook that writes somewhere the person who caused it may not must say it is the server's work:

ts
hooks: {  async afterUpdate({ objectKey, record, previous, actor }) {    const closed = objectKey === 'jobs' && record.stage === 'closed' && previous.stage !== 'closed'    if (!closed) return    // The ledger is the office's. A designer closes jobs, and is denied the ledger.    await asSystem(() => createRecord('ledger', { jobId: record.id, amount: record.value }, actor))  },},
  • asSystem lifts role access and record scopes together. The line on the timeline still names the actor you pass.
  • Code nobody is signed in for (a script, a cronRoute, a publicRoute, the config's automations) holds no role, so nothing is kept from it, and access.default does not apply.
  • Role access is checked before your hooks: a before hook is not called for a change to an object the person may only read, or not see, as it is not called for one record scopes refuse. The data layer checks it again when the record is written, for code that writes there directly. The same holds for a run target (an action), an email to a record and an enrolment in a sequence: none starts for someone who may only read the record.
  • addActivity from @swirls/spools/extensions is a change to the record: refused, for the teammate your code runs for, on a record of an object they may only read, and not found on one they are kept from. So are createTask, updateTask, deleteTask and createNote, recordFolder for a record that has no folder yet (it would make one), and shareRecordFolder, which changes both records' folders. Wrap the server's own bookkeeping in asSystem.
  • A hook is handed the record it is about. Don't send that on to someone it is kept from.

Kept fields: values the server keeps for itself#

A count of open visits on a job, the time a notice last went out: values no person writes, which your code keeps up to date. Mark the field readonly in the config and write it with writeKeptFields from @swirls/spools/extensions:

ts
import { writeKeptFields } from '@swirls/spools/extensions'await writeKeptFields('projects', jobId, { openVisits: count })// Claim a notice once: written only if nobody claimed it since `seenAt` was read.const claimed = await writeKeptFields(  'projects',  jobId,  { fieldNoticeAt: now },  { when: { fieldNoticeAt: seenAt } },)

It writes no timeline line and runs no hook or automation, as the server (role access and record scopes don't refuse it). That is safe because it writes only readonly fields, which no person writes, so no person's change goes untold; any other field is refused. The record's rules still hold (values are checked; unique, lock and appendOnly apply: add a kept field to a lock's except to keep it counting on a locked record), the record is held for the write, and when makes it a compare-and-set. It returns the record, or null when the record is gone or when no longer holds.

Scopes: who holds what#

When your sign-in provider doesn't say which scopes a person holds, say it yourself:

ts
scopes: {  // Each scope this person holds, with a role from `scopes.roles` in crm.config.json.  async grants(user) {    const rows = await myDirectory.branchesOf(user.email)    return rows.map((row) => ({ scope: row.branch, role: row.manager ? 'member' : 'viewer' }))  },  // Every scope there is, for the switcher of someone whose role reaches them all.  async list() {    return [{ key: 'north', label: 'North' }, { key: 'south', label: 'South' }]  },},

Its answer for a person is kept for a minute, so a change takes that long to show. Returning nothing for a person shows them no scoped record. A resolver here wins over the sign-in provider's.

A scope grants returns counts only when it is one of this Spool's: an option of a scoped object's scope field where that field is a select, and for a scope field kept as text or as a relation, one that list names. So list is not only for the switcher. Where a scope field is text or a relation, a resolver without list gives nobody a scope, and the server says so when it starts. list is also what a record's scope is checked against when it is saved: a scope it doesn't name is refused. A grant whose role is marked all is head office's and is not a scope's: it counts as you return it.

A run target, a handler or an automation runs for whoever may change the record it is run for. Someone who only reads the record starts none of them.

Run targets: add a new kind#

A run target kind handles every "<kind>:<name>" in the config.

ts
runTargets: {  slack: {    validate: (channel) => (channels.includes(channel) ? null : `unknown channel "${channel}"`),    async run(channel, ctx) {      await postToSlack(channel, `${ctx.trigger}: ${ctx.record.id}`);      return { message: `Posted to #${channel}` };    },  },},
json
{ "on": "deals.created", "run": "slack:sales" }

validate is optional. When present, bun run crm:gen and server start-up use it to reject targets that can't resolve, so a typo fails early.

Email: use a different provider#

Campaign email goes through the Spool's email adapter. To send it some other way without writing an adapter, replace the transport:

ts
email: {  async send({ to, subject, text, html, headers }) {    const id = await myProvider.send({ to, subject, text, html, headers });    return { id, sent: true };  },},

Keep the headers: they carry the one-click unsubscribe.

Marketing: add a social or ad network#

Add a network under marketing and a channel or an ad account in crm.config.json can name it. posts networks say how long a post may be and how to send one; ads networks say how to read an account's campaigns. The full example is in Marketing.

ts
marketing: {  posts: {    mastodon: {      label: "Mastodon",      limit: 500,      access: { env: "MASTODON_TOKEN" },      async publish({ text, token }) {        // Call the network. Return where the post is; throw to refuse it.        return { id: "...", url: "https://..." };      },    },  },},

Integrations: let teammates connect another service#

Add an OAuth provider under integrations and it appears on the Integrations page. The framework runs the connect flow and keeps the tokens encrypted; your handlers find a connection with findConnections and ask for a current token with getAccessToken. The full example is in Integrations.

A connection belongs to the teammate who connected it. Add shared: 'team' for an account the whole business uses (one accounting system), or shared: 'group' with groups for one per branch or region, and canManage to say who may connect and disconnect it. See Share a provider with the team.

ts
integrations: {  books: {    label: "Acme Books",    description: "Create invoices from won deals",    clientId: "BOOKS_CLIENT_ID",    clientSecret: "BOOKS_CLIENT_SECRET",    authUrl: "https://books.example.com/oauth/authorize",    tokenUrl: "https://books.example.com/oauth/token",    scopes: ["invoices.write"],    account: async ({ get }) => (await get<{ id: string }>("https://books.example.com/api/me")).id,    // Left out, each teammate connects their own. With it, one connection serves everyone.    shared: "team",    canManage: ["finance@acme.example"],  },},

Files: choose where a record's folder goes#

An object with files in the config gives each record a folder in the drive, at <plural label>/<record title>, or inside a related record's folder with under. Return another path from files.location to lay the drive out your way. It is asked once per record, when its folder is made. See Files.

ts
files: {  location: ({ objectKey, record }) => (objectKey === "jobs" ? `Jobs/${record.name}` : ""),},

Add a field type#

A field type is part of the framework, so this is a change to packages/spools: two files, and the compiler lists what's missing.

  1. In packages/spools/src/crm/field-types.ts, add the config shape to fieldSchema and an entry to fieldTypes:

    ts
    z.object({ ...fieldBase, type: z.literal("rating"), max: z.number().int().default(5) }),
    ts
    rating: { column: "integer", input: (field) => nullable(z.coerce.number().int().min(0).max(field.max)) },
  2. In packages/spools/src/crm/ui/fields.tsx, add rating to fieldDisplay and fieldInput.

Then run bun run crm:gen, and document the type in docs/configuration.md.

Add a view type#

  1. Add the config shape to viewSchema in packages/spools/src/crm/config-schema.ts.
  2. Add a component to viewComponents in packages/spools/src/crm/ui/views.tsx. Its props are ViewProps in the same file.
  3. Teach sanitise in packages/spools/src/server/views.ts which settings the new type keeps.

Pages#

Each page is a small file in src/routes that mounts one of the framework's:

tsx
import { createFileRoute } from '@tanstack/react-router'// src/routes/_crm/tasks.tsximport { tasksPage } from '@swirls/spools/pages/tasks'export const Route = createFileRoute('/_crm/tasks')(tasksPage)

Delete the file and the page is gone. Keep its data and change how it looks:

tsx
export const Route = createFileRoute('/_crm/tasks')({ ...tasksPage, component: MyTasks })

Pages and endpoints of your own#

A page is a route file. Inside src/routes/_crm it gets the CRM's shell, and only signed-in teammates can open it. The framework's parts are in @swirls/spools/ui/* (kit for buttons and dialogs, shell for the top bar, workspace, views).

Its data comes from a server function, whose handler is one from @swirls/spools/handlers:

tsx
// src/routes/_crm/stock.tsximport { createFileRoute } from '@tanstack/react-router'import { createServerFn } from '@tanstack/react-start'import { z } from 'zod'import { crmHandler } from '@swirls/spools/handlers'const stockFn = createServerFn({ method: 'GET' })  .validator(z.object({ sku: z.string() }))  .handler(crmHandler('stock', async ({ data, user }) => lookUpStock(data.sku, user.email)))export const Route = createFileRoute('/_crm/stock')({  loader: () => stockFn({ data: { sku: 'A-100' } }),  component: () => <p>{Route.useLoaderData().count} in stock</p>,})

An endpoint is the same with apiRoute:

ts
// src/routes/api/stock.$sku.tsimport { createFileRoute } from '@tanstack/react-router'import { apiRoute } from '@swirls/spools/handlers'export const Route = createFileRoute('/api/stock/$sku')({  server: {    handlers: {      GET: apiRoute<{ sku: string }>('stock', async ({ params, user }) =>        Response.json(await lookUpStock(params.sku, user.email)),      ),    },  },})
Handler Who it answers
crmHandler A server function, for signed-in teammates on the access list
apiRoute An endpoint, for the same people. Anyone else gets 401
cronRoute A scheduled job with CRON_SECRET. Anyone else gets 401
publicHandler A server function that answers anyone. Nothing staff-only belongs here
publicRoute An endpoint that answers anyone, such as a webhook. Check its signature before anything else

apiRoute also runs a write sent with an Idempotency-Key once with { idempotency: {} } (Idempotent requests). For people who are not teammates, build your own door behind publicRoute (Building your own door).

Each checks who is asking before your code runs, hands it the person, stops when the browser goes away, and shows the page the message of an error you throw. A new Spool's bun run lint refuses a server function or endpoint that goes without one.

Building your own door#

Spools has no built-in door for people who are not teammates (installation crews, clients, vendors). Your app builds its own endpoints for them behind publicRoute, from small pieces in @swirls/spools/extensions, and decides itself who may do what. Nothing a teammate's request gets (role access, record scopes, the access list) applies to such an endpoint: inside it your code runs with nobody said, so everything it may reach, and everything it hands back, is yours to check. Do the checks in this order, each before anything costs more:

  1. Origins. Answer browsers only from your front end's origins (CORS is yours), and name those origins for the token check below.
  2. The caller's address, limited before anything else is looked at: callerAddress(headers) reads X-Forwarded-For as far as TRUST_PROXY (1 to 10 proxies) says, and is null when the address can't be known (TRUST_PROXY unset or mistyped). Never count a limit under null or any one shared value: it would be one counter for every caller. Skip the address limit and say so in production (and limit at the platform in front, a WAF or the host's firewall), or refuse. peekLimit(bucket, key, limit) says how long a key must wait without counting a hit, so an over-limit address is refused before any work.
  3. The token. bearerToken(headers), then verifyToken(token, { authorizedParties }): the user id it was issued to, by the auth adapter's own check (with clerk(), locally against keys it holds, and offline with CLERK_JWT_KEY), or null. Name your front end's origins: with none, only a developer's or a test's server takes any token, so a teammate's token from the CRM itself never opens your door. devAuth({ outsiders: [{ id, name, email, token }] }) hands out tokens in development.
  4. A limit per user: hitLimit(bucket, userId, { max, windowMs }), peekLimit to look without counting, and consumeLimit for a quota counted in amounts (uploads, megabytes). Your buckets are counted apart from the framework's (as app:<bucket>).
  5. Who they are in your records: a record of an object of yours whose field holds their user id, read with asSystem. Make that field readonly (written only by your code, with writeKeptFields), so no teammate's form, import or the assistant can point a record at someone else.
  6. An explicit field allowlist, both ways: write only the fields you name, and answer only the fields you name. Never hand a record back as listRecords gives it.
  7. Ownership: every record id the caller sends (in the path or the body, a relation's included) must be one they may reach by your rules. Answer one that isn't exactly as one that doesn't exist.
  8. Idempotency for writes an offline front end retries: idempotent(request, { caller: verifiedCaller('crew', userId) }, work). idempotent takes only a caller verifiedCaller made from ids you have verified, never anything the request says.
ts
// src/routes/api/crew/notes.ts: crew members leave notes on the jobs they look after.import { createFileRoute } from '@tanstack/react-router'import {  asSystem,  bearerToken,  callerAddress,  createRecord,  hitLimit,  idempotent,  listRecords,  peekLimit,  verifiedCaller,  verifyToken,} from '@swirls/spools/extensions'import { publicRoute } from '@swirls/spools/handlers'const ORIGINS = (process.env.CREW_APP_ORIGINS ?? '').split(',')const minute = (max: number) => ({ max, windowMs: 60_000 })const answer = (error: string, status: number) => Response.json({ error }, { status })if (process.env.NODE_ENV === 'production' && !process.env.TRUST_PROXY) {  console.warn('[crew] TRUST_PROXY is unset: callers are not limited by address here')}export const Route = createFileRoute('/api/crew/notes')({  server: {    handlers: {      POST: publicRoute('crew.notes', async (request) => {        // Null when the address can't be known: that limit is then skipped, never shared.        const address = await callerAddress(request.headers)        if (address !== null) {          if ((await peekLimit('crew:address', address, minute(60))) > 0)            return answer('rate_limited', 429)          await hitLimit('crew:address', address, minute(60))        }        const token = bearerToken(request.headers)        const userId = token && (await verifyToken(token, { authorizedParties: ORIGINS }))        if (!userId) return answer('unauthorized', 401)        if (!(await hitLimit('crew:user', userId, minute(120))).allowed)          return answer('rate_limited', 429)        // Who they are: the crew record whose readonly `login` is their user id.        const [crew] = await asSystem(() =>          listRecords({ objectKey: 'crews', where: { login: userId, active: true }, limit: 2 }),        )        if (!crew) return answer('forbidden', 403)        return idempotent(          request,          { caller: verifiedCaller('crew', userId) },          async (_request, body) => {            const sent = JSON.parse(body) as { job?: unknown; text?: unknown }            const job = await asSystem(() =>              listRecords({                objectKey: 'jobs',                where: { id: String(sent.job), crew: crew.id },                limit: 1,              }),            )            if (job.length === 0) return answer('not_found', 404)            const note = await asSystem(() =>              createRecord(                'jobNotes',                { text: String(sent.text), jobId: String(sent.job), crewId: crew.id },                null,              ),            )            return Response.json({ id: note.id, text: note.text }, { status: 201 })          },        )      }),    },  },})

Other pieces your door may want: changedSinceAs(keys, token, mayRead) tells a live front end what changed among the keys your own check lets the caller know of; sealText/openText keep a secret of theirs sealed for its record (Adapters); file uploads go through the generic startUpload/finishUpload of @swirls/spools/server/files with the declared content type (Files).

Idempotent requests#

A write (anything but GET and HEAD) sent with an Idempotency-Key header (8 to 128 letters, digits, - or _) runs once per caller, endpoint and key, with idempotent(request, { caller, keepFor?, bodyLimit? }, work) in your own endpoint, or apiRoute(name, answer, { idempotency: {} }) for teammates (whose caller is their user id). The endpoint is the method, path and query (?draft=1 and ?draft=0 are two requests). work is handed a request that carries the body again, and the body as text; the body is read first, up to bodyLimit bytes (1 MB unless it says; larger is 413 too_large).

  • The caller is made with verifiedCaller(namespace, ...verifiedIds) from identities you have verified (a user id from verifyToken, a record of yours found for it), never anything the request says of itself, or one caller could replay another's answers. It refuses an empty part, or one holding : or a space, and its type (VerifiedCaller) is the only one idempotent takes; a string shaped otherwise is refused at runtime too. Your callers are kept apart from the framework's (app:<caller>; teammates are staff:<id>).
  • A key changes nothing about what your code reaches: it runs exactly as it would without one.
  • The first answer below 500 is kept and given again to every repeat, with Idempotent-Replayed: true: same status, and, when the Spool has a vault, the same body and type.
  • With a vault, every answer that isn't a stream is kept, however busy the server is: one built in memory (Response.json, a string, bytes, a blob) or one that declares its Content-Length, read whole up to 256 KB with no clock to lose to. Not kept: a body larger than 256 KB, an event stream (text/event-stream), one sent Transfer-Encoding: chunked, and a body your code makes as it goes (a ReadableStream) that declares no length. Give such a body a Content-Length to have it kept.
  • Without a vault no answer's body is kept, nor one of those: a repeat is the first answer's status with Idempotent-Body: withheld, Content-Type: application/json and the body { "replayed": true, "body": "withheld" } (none for 204, 205 and 304), and Idempotent-Body-SHA256 (the hex SHA-256 of the body it had) when it was read whole. An answer is never kept in the clear. What a front end does with one: take the status as the outcome of its write (it was made, once), and read what it needs back; never parse the withheld body as the first answer.
  • Once your code has answered, nothing fails the request: keeping the answer is tried again if the database stumbles, and an answer that can't be kept is logged and still sent. Only if the database refuses every try is the key left to go stale, when a repeat would run again.
  • The same key with another body is 409 key_reused.
  • A copy that arrives while the first is still running is 409 in_progress with Retry-After: 2, on this server or any other.
  • A request that fails (500 or worse, a throw, the caller going away) lets its key go, so a retry runs. A running request renews its claim every ten seconds, however long it takes; a claim left by a server that stopped counts as gone a minute after it was last renewed. Only the request holding a claim renews it, answers it or lets it go.
  • Answers are kept a week (keepFor), sealed by the vault for their own row and caller, so one moved to another row opens for nobody. Expired answers are swept as the caller sends more.

The claim is an insert into idempotent_requests, whose unique index lets one copy in, and taking over a stale claim is one conditional update. So it holds across servers on Postgres and on PGlite, and nothing is read and then written.

Rate limits#

hitLimit(bucket, key, { max, windowMs }) counts one for key when it is under the limit, in a sliding window, and answers { allowed: true } or { allowed: false, retryAfter } (seconds). peekLimit(bucket, key, { max, windowMs }) says how many seconds key must wait (0: now) and counts nothing. consumeLimit(bucket, key, amount, { max, windowMs }) is a quota counted in amounts in a fixed window (a day from midnight UTC, a minute on the minute), taken whole or not at all. All three count on the Spool's RateLimiter: in this server's memory unless defineSpool says rateLimits: storeRateLimits(), which counts in the database, the same on every instance (Adapters). A bucket or key is 1 to 200 characters, and an amount, max or windowMs that isn't a whole number above 0 is refused.

Theme the CRM#

The CRM's colours are CSS variables on .crm, defined in packages/spools/src/crm/ui/theme.css. Override them in your own src/styles.css, after the theme import, instead of editing the theme file:

css
.crm {  --c-accent: #84572f;  --c-accent-hov: #6b4526;}.crm.dark {  --c-accent: #c08a55;  --c-accent-hov: #d09c69;}

The CRM follows the system light or dark setting until someone uses the toggle in the sidebar.

Give the assistant a new capability#

  1. Add a tool to tools in packages/spools/src/server/tools.ts with a Zod input schema.
  2. Add a tool workflow to swirls/assistant.swirls that posts to /api/swirls/tools/<tool>, and list it in the agent's tools.
  3. Run swirls doctor, then swirls deploy.