Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .skills/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Skills

Step-by-step instructions for working on the actions in this repository, written
for coding agents and humans alike. Each skill lives in its own folder with a
`SKILL.md` (frontmatter `name` + `description`, then the instructions).

The reference implementation for every skill is
[`actions/discord-action`](../actions/discord-action). When a skill and that
action disagree, the action wins — fix the skill.

| Skill | Use it to |
|---|---|
| [`create-action`](create-action/SKILL.md) | Scaffold a new TypeScript action under `actions/` and wire it into CI. |
| [`add-function`](add-function/SKILL.md) | Add a runtime function (a node a flow calls). |
| [`add-data-type`](add-data-type/SKILL.md) | Add a data type, hand-written or generated from an OpenAPI spec. |
| [`add-event`](add-event/SKILL.md) | Add an event (a trigger that starts a flow) and fire it. |
| [`test-action`](test-action/SKILL.md) | Write and run the tests, typecheck, build and module export of an action. |
| [`review-action`](review-action/SKILL.md) | Check an action against the conventions before opening a PR. |

Typical order for a new integration: `create-action` → `add-data-type` →
`add-function` / `add-event` → `test-action` → `review-action`.

The skills cover TypeScript actions. The Rust actions (`cron-action`,
`rest-action`, `mcp-action`) use `hercules-sdk` and are not covered yet.
130 changes: 130 additions & 0 deletions .skills/add-data-type/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
---
name: add-data-type
description: Add or change a data type (the shape of values flows pass around) in a TypeScript action — zod schema, decorators, mapper that fills every field, optional OpenAPI generation. Use when a function or event needs to return or accept a structured value.
---

# Add a data type

A data type is a named zod schema the editor knows about. Functions return
it, take it as a parameter, and events carry it as payload.

Reference: `actions/discord-action/src/data_types/discordMessage.ts`,
`discordChannel.ts` (enum), `discordEmbed.ts` (several types in one file).

## 1. Name it

| What | Convention | Example |
|---|---|---|
| File | `src/data_types/<vendor><Noun>.ts` | `discordMessage.ts` |
| Schema | `<Vendor><Noun>Schema` (enums: `<Vendor><Noun>Enum`) | `DiscordMessageSchema` |
| TS type | `<Vendor><Noun>Type` | `DiscordMessageType` |
| Class | `<Vendor><Noun>` | `DiscordMessage` |
| `@Identifier` | `<VENDOR>_<NOUN>` upper snake, vendor-prefixed | `DISCORD_MESSAGE` |

## 2. Write it

```ts
import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules";
import { z } from "zod";
import { VendorUserSchema } from "./vendorUser.js";

export const VendorMessageSchema = z.object({
id: z.string(),
channelId: z.string(),
author: VendorUserSchema,
content: z.string(),
editedAt: z.string().nullish(),
createdAt: z.string(),
});
export type VendorMessageType = z.infer<typeof VendorMessageSchema>;

@Identifier("VENDOR_MESSAGE")
@Name({ code: "en-US", content: "Vendor Message" })
@DisplayMessage({ code: "en-US", content: "Vendor Message: ${id}" })
@Schema(VendorMessageSchema)
export class VendorMessage {}
```

### Schema rules

- **camelCase field names**, even if the vendor API uses snake_case. Map in
the mapper, not in the schema.
- Only fields a flow would plausibly use. A data type is not a dump of the
vendor response.
- Anything the vendor may omit is `.nullish()` — not `.optional()` — so the
mapper can return `null` and inputs may still leave it out.
- Timestamps are ISO strings (`date.toISOString()`), ids are strings, colors /
enums are their simplest form.
- Fixed value sets are a `z.enum([...])` with their own data type
(`DISCORD_CHANNEL_TYPE`); always include an `"unknown"` fallback when
mapping from a vendor enum that may grow.
- Reuse nested schemas by importing them (`author: DiscordUserSchema`), and
give every nested object that a flow may build itself its own data type
(`DISCORD_EMBED_FIELD`, `DISCORD_EMBED_FOOTER`, …).
- `@DisplayMessage` may interpolate a field (`"Channel: #${name}"`).

## 3. Write the mapper

Add `map<Vendor><Noun>(vendorObject): <Vendor><Noun>Type` to `helpers.ts`.

**Every field the schema declares must be present in the result — use `null`
for what the vendor did not send, never leave a key out.** A missing key has
no reference in the flow's value store, so a flow that reads it fails with
`ReferenceValueNotFound`.

```ts
export function mapVendorMessage(msg: VendorSdkMessage): VendorMessageType {
return {
id: msg.id,
channelId: msg.channel_id,
author: mapVendorUser(msg.author),
content: msg.text ?? "",
editedAt: msg.edited_at ? new Date(msg.edited_at).toISOString() : null,
createdAt: new Date(msg.created_at).toISOString(),
};
}
```

If the same object reaches the action in two shapes (SDK object and raw API
JSON), write one mapper per shape and test that both produce the same keys
(discord: `mapDiscordMessage` / `mapApiMessage`).

## 4. Register it

In `src/index.ts`: `action.registerDataTypeClass(<Class>);`. Register nested
types **before** the types that use them.

## 5. Test it

Add a mapper test (see [`test-action`](../test-action/SKILL.md), "Mapper
tests"): build a minimal vendor object, map it, and assert that the keys equal
`Object.keys(<Schema>.shape)` and that `<Schema>.parse(result)` succeeds.

## Generating data types from an OpenAPI spec

For large vendor objects with an official OpenAPI spec (Stripe, Twilio,
Shopware, GitHub) generate the zod schemas instead of writing them:

1. Add a `generate:<vendor>-schemas` script to `package.json` that downloads
the spec into `schemas/`, filters it with
`../../scripts/openapi-filter.mjs --roots <component,...>` and converts it
with `../../scripts/openapi-to-zod.mjs` into
`src/generated/<vendor>-schemas.ts`. Full options:
[`scripts/README.md`](../../scripts/README.md); working example:
`actions/twilio-action/package.json`.
2. Run it once and commit `schemas/*.filtered.json` and the generated file.
It is not run in CI or in Docker.
3. The data type file re-exports the generated schema and adds the decorators:
```ts
export const VendorMessageSchema = schemas.VendorMessage;
```
and documents where it comes from and how to regenerate (see
`twilio-action/src/data_types/twilioMessage.ts`).

Generated schemas keep the vendor's field names (snake_case); that is
accepted for generated types. Never edit `src/generated/` by hand.

## Changing an existing data type

Removing or renaming a field, or changing its type, breaks flows that read it.
Adding a `.nullish()` field is safe. Keep the mapper and its test in step.
108 changes: 108 additions & 0 deletions .skills/add-event/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
---
name: add-event
description: Add or change an event (a trigger that starts flows) in a TypeScript action — event class with settings, the event bridge that listens to the vendor and fires matching flows, payload mapping and tests. Use when something happening at the vendor should start a flow.
---

# Add an event

An event is a flow trigger. It has two halves:

1. **The event class** — decorators only. Declares the settings a flow fills
in (credential, filters) and the payload type.
2. **The event bridge** (`src/eventBridge.ts`) — listens to the vendor
(gateway, webhook server, polling), finds the flows whose settings match,
and fires them with the mapped payload.

Reference: `actions/discord-action/src/events/discordMessageCreated.ts` and
`actions/discord-action/src/eventBridge.ts`.

## 1. Name it

| What | Convention | Example |
|---|---|---|
| File | `src/events/<vendor><Noun><PastTenseVerb>.ts` | `discordMessageCreated.ts` |
| Class + `@Identifier` | `<Vendor><Noun><PastTenseVerb>` (PascalCase, both identical) | `DiscordMessageCreated` |

## 2. Write the class

```ts
import { Description, DisplayIcon, DisplayMessage, EventSetting, Identifier, Name, Signature } from "@code0-tech/hercules";

@Identifier("VendorMessageCreated")
@DisplayIcon("simple:vendor")
@Name({ code: "en-US", content: "Vendor message created" })
@Description({ code: "en-US", content: "Triggered when a message is posted in a channel. Ignores messages sent by bots." })
@DisplayMessage({ code: "en-US", content: "Vendor message created" })
@Signature("(apiToken: string, channelId?: string): VENDOR_MESSAGE")
@EventSetting({
identifier: "apiToken",
name: [{ code: "en-US", content: "API token" }],
description: [{ code: "en-US", content: "The token of the Vendor account that listens for messages." }],
})
@EventSetting({
identifier: "channelId",
name: [{ code: "en-US", content: "Channel ID" }],
description: [{ code: "en-US", content: "Only react to messages in this channel. Empty reacts to every channel." }],
optional: true,
})
export class VendorMessageCreated {}
```

### Rules

- The signature lists the settings and returns the **payload data type**.
- **Credential first**, required, same name as in the functions.
- Every other setting is a **filter**: optional, and an empty value is a
wildcard ("Empty reacts to every channel" — say so in the description).
- Say in `@Description` what is ignored (bot messages, own messages, …) to
prevent loops where a flow triggers itself.

## 3. Fire it from the event bridge

If the action has no `eventBridge.ts` yet, create one modelled on discord's
and call `startEventBridge(action)` in `index.ts` after the registrations.
Its parts:

- **Sync on flow changes.** Subscribe to `CodeZeroEvent.connected`,
`flowUpdated` and `flowDeleted`; debounce (discord: 250 ms) and then walk
`action.flows.values()`, collect the credentials of all event flows, and make
sure a listener exists for each (`setPinnedTokens` keeps those clients alive).
Credentials no event flow uses any more must be released again (discord:
they are unpinned and dropped by the idle sweeper in `client.ts`).
- **Read settings** with a `readSetting(flow, identifier)` helper that returns
the trimmed string value or `undefined` for empty.
- **Match** with `settingMatches(flow, identifier, value)`: an empty setting
matches everything.
- **Fire** with `action.fire(flow.flowId, payload)` for every matching flow,
via `Promise.allSettled` so one failing flow doesn't stop the others; log
failures.
- **Payload**: `toEventPayload(map<Vendor><Noun>(...))` — the mapper fills every
field (see `add-data-type`), `toEventPayload` turns remaining `undefined`
into `null` and `Date` into ISO strings.
- **Never throw out of a vendor listener.** Wrap async handlers in
`try/catch` and log; an unhandled rejection takes the action down.
- Add the identifier to the bridge's set of known event identifiers
(`EVENT_IDENTIFIERS` in discord).

Vendor-specific constraints belong in the bridge and in the README, e.g.
discord defers slash command replies because Discord requires an answer within
3 s, and registers / removes slash commands to match the flows.

## 4. Register it

In `src/index.ts`: `action.registerRuntimeEventClass(<Class>);`.

## 5. Test and document

- Add the class to the `events` list in `test/index.test.ts` (credential check).
- Test the bridge logic that can be tested without the vendor: matching,
payload mapping, and any sync against the vendor with a faked client via
`vi.mock("../src/client.js", ...)` (see
`discord-action/test/slashCommands.test.ts`).
- Add a row to the **Events** table in the README: identifier, when it fires,
settings. Document setup the vendor needs (intents, webhook URL, scopes).

## Changing an existing event

Renaming the identifier or a setting identifier, or making a filter required,
breaks existing flows. Adding an optional filter setting is safe.
Loading