diff --git a/.skills/README.md b/.skills/README.md new file mode 100644 index 0000000..4d7b493 --- /dev/null +++ b/.skills/README.md @@ -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. diff --git a/.skills/add-data-type/SKILL.md b/.skills/add-data-type/SKILL.md new file mode 100644 index 0000000..0379838 --- /dev/null +++ b/.skills/add-data-type/SKILL.md @@ -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/.ts` | `discordMessage.ts` | +| Schema | `Schema` (enums: `Enum`) | `DiscordMessageSchema` | +| TS type | `Type` | `DiscordMessageType` | +| Class | `` | `DiscordMessage` | +| `@Identifier` | `_` 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; + +@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(vendorObject): 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();`. 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(.shape)` and that `.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:-schemas` script to `package.json` that downloads + the spec into `schemas/`, filters it with + `../../scripts/openapi-filter.mjs --roots ` and converts it + with `../../scripts/openapi-to-zod.mjs` into + `src/generated/-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. diff --git a/.skills/add-event/SKILL.md b/.skills/add-event/SKILL.md new file mode 100644 index 0000000..407f9cf --- /dev/null +++ b/.skills/add-event/SKILL.md @@ -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/.ts` | `discordMessageCreated.ts` | +| Class + `@Identifier` | `` (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(...))` — 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();`. + +## 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. diff --git a/.skills/add-function/SKILL.md b/.skills/add-function/SKILL.md new file mode 100644 index 0000000..2ca57f9 --- /dev/null +++ b/.skills/add-function/SKILL.md @@ -0,0 +1,136 @@ +--- +name: add-function +description: Add or change a runtime function (a node a flow calls) in a TypeScript action — decorators, signature, parameters, error handling, registration and tests. Use when an action should be able to do something new, or an existing node's inputs/outputs change. +--- + +# Add a runtime function + +A runtime function is one node in the flow editor. It is a class with hercules +decorators that describe the node, and a `run()` method that executes it. + +Reference: `actions/discord-action/src/functions/messaging/discordSendMessage.ts`. + +## 1. Name it + +| What | Convention | Example | +|---|---|---| +| File | `src/functions//.ts` | `functions/messaging/discordSendMessage.ts` | +| Class | `Function` | `DiscordSendMessageFunction` | +| `@Identifier` | `` (camelCase, globally unique — always prefix the vendor) | `discordSendMessage` | +| Error fallback code | `ERROR_ING_` | `ERROR_SENDING_MESSAGE` | + +Verbs: `get` (one, by id), `get…s` (list), `create`, `update`, `delete`, +`send`, `add…To…`, `remove…From…`. Use the vendor's nouns, but plain English +where the vendor's term is obscure (Discord "guild" is shown as "server"). + +## 2. Write the class + +```ts +import { Description, DisplayIcon, DisplayMessage, Documentation, Identifier, Name, Parameter, Signature } from "@code0-tech/hercules"; +import { getVendorClient } from "../../client.js"; +import { handleVendorError, mapVendorMessage } from "../../helpers.js"; +import { VendorMessageType } from "../../data_types/vendorMessage.js"; + +@Identifier("vendorSendMessage") +@Signature("(apiToken: string, channelId: string, content: string, silent?: boolean): VENDOR_MESSAGE") +@Name({ code: "en-US", content: "Send message" }) +@DisplayIcon("simple:vendor") +@DisplayMessage({ code: "en-US", content: "Send message to ${channelId}" }) +@Documentation({ code: "en-US", content: "Longer explanation: what it does, limits, what is returned." }) +@Description({ code: "en-US", content: "Send a message to a channel." }) +@Parameter({ + runtimeName: "apiToken", + name: [{ code: "en-US", content: "API token" }], + description: [{ code: "en-US", content: "The token of the Vendor account that sends the message." }], +}) +@Parameter({ + runtimeName: "channelId", + name: [{ code: "en-US", content: "Channel ID" }], + description: [{ code: "en-US", content: "The ID of the target channel." }], +}) +@Parameter({ + runtimeName: "content", + name: [{ code: "en-US", content: "Content" }], + description: [{ code: "en-US", content: "The text of the message." }], +}) +@Parameter({ + runtimeName: "silent", + name: [{ code: "en-US", content: "Silent" }], + description: [{ code: "en-US", content: "Send without a notification." }], + optional: true, +}) +export class VendorSendMessageFunction { + async run( + _context: unknown, + apiToken: string, + channelId: string, + content: string, + silent?: boolean + ): Promise { + try { + const client = await getVendorClient(apiToken); + const message = await client.messages.send(channelId, { content, silent: silent ?? false }); + return mapVendorMessage(message); + } catch (error) { + return handleVendorError(error, "ERROR_SENDING_MESSAGE", "Failed to send the message."); + } + } +} +``` + +### Rules + +- **`@Signature` is the contract.** TypeScript-like: + `(name: type, optional?: type): RETURN`. Types are `string`, `number`, + `boolean`, or a data type identifier (`VENDOR_MESSAGE`), arrays as `TYPE[]`. + Return `void` only if there is really nothing to return — prefer returning + the affected object (e.g. delete returns the deleted message). +- **One `@Parameter` per signature parameter, in the same order**, with the + same `runtimeName`. `run()` takes `context` first, then the parameters in + that order. Optional parameters get `optional: true`, `?` in the signature + and `?` in `run()`. +- **Credential first.** The first parameter is the credential, required + (discord: `botToken`). Same name in every function and event of the action. +- **Context.** Name it `_context: unknown` when unused. Use + `context: FunctionContext` only when reading action configuration + (`context.matchedConfig.findConfig("")`). +- **Texts.** `@Name` is short and in sentence case ("Send message"). + `@Description` is one sentence. `@Documentation` may be longer and use + markdown. `@DisplayMessage` is what the node shows on the canvas and may + interpolate parameters with `${name}`. Locale is `en-US`. +- **Errors.** Never let a raw vendor error escape: wrap the body in + `try/catch` and route through `handleError`, which throws a + `RuntimeError` with an upper-snake code prefixed with the vendor + (`DISCORD_UNKNOWN_CHANNEL`). Validation errors on input are `RuntimeError`s + too (e.g. `DISCORD_EMPTY_MESSAGE`). +- **Output.** Always return through a `map` mapper so every field + of the data type is present (see `add-data-type`). Lists return + `map(...)` over the results and filter out `null`s the vendor returns for + inaccessible items. +- **Inputs from flows are loose.** Trim strings, treat `""` like "not set" for + optional parameters, and normalise input data types with small helpers + (`cleanString`, `cleanUrl` in discord's `helpers.ts`). +- Keep vendor-specific logic (building payloads, pagination, limits) in + `helpers.ts` so it can be unit-tested without the class. + +## 3. Register it + +In `src/index.ts`: import the class and add +`action.registerRuntimeFunction();` next to the others of its group. + +## 4. Test and document + +- Add the class to the `functions` list in `test/index.test.ts` (credential and + parameter checks run automatically) and test any new helper — see + [`test-action`](../test-action/SKILL.md). +- Add a row to the **Functions** table in the action's `README.md`. + +## Changing an existing function + +- Renaming `@Identifier` or a parameter's `runtimeName`, removing a + parameter, or making an optional parameter required **breaks existing flows**. + Avoid it; add a new optional parameter or a new function instead. If it is + unavoidable, say so explicitly in the PR. +- Adding an optional parameter at the end is safe. +- Keep signature, `@Parameter` list, `run()` and README in sync — the + parameter test in `test/index.test.ts` catches order mismatches. diff --git a/.skills/create-action/SKILL.md b/.skills/create-action/SKILL.md new file mode 100644 index 0000000..bb44bb9 --- /dev/null +++ b/.skills/create-action/SKILL.md @@ -0,0 +1,116 @@ +--- +name: create-action +description: Scaffold a new TypeScript action under actions/-action (package.json, vite, tsconfig, Dockerfile, manifest, index.ts, README, tests) and register it in CI. Use when starting a new integration for a vendor or service. +--- + +# Create a new action + +An action is a standalone service that registers data types, runtime functions +and events with the runtime and executes them. Every action lives in +`actions/-action/` and ships as its own container image. + +Reference: `actions/discord-action`. Copy its structure, not its Discord logic. + +## 1. Decide before you write code + +Write these down (in the PR description or as a comment to the user) first: + +- **Vendor and folder name** — `actions/-action`, lowercase, kebab-case. +- **Vendor SDK** — prefer the vendor's official Node SDK (`discord.js`, + `twilio`, …). Fall back to `fetch` only if there is none. +- **Credentials** — how a flow authenticates. Default (discord pattern): the + credential is the **first parameter of every function and the first setting + of every event**, so one running action serves any number of accounts and + the action itself has no configuration (`[]` as the last `Action` argument). + Only use action-level configuration (`context.matchedConfig.findConfig(...)`, + see `twilio-action`) when the vendor has exactly one account per project by + nature. +- **Scope of the first version** — a list of functions (verb + noun, e.g. + `sendMessage`, `getChannel`), the data types they return, and the events. + Start with the most common read + write operations; don't mirror the whole API. + +## 2. Create the files + +Copy the templates in [`templates/`](templates) into `actions/-action/` +and replace the placeholders: + +| Placeholder | Example | +|---|---| +| `__vendor__` | `telegram` (lowercase, used in ids and paths) | +| `__Vendor__` | `Telegram` (display name / class prefix) | +| `__VENDOR_SDK__` | `telegraf` (npm package of the vendor SDK, also listed as vite external) | +| `__ICON__` | `simple:telegram` (simple-icons) or `tabler:` | +| `__DESCRIPTION__` | One sentence: what the action lets a flow do. Same text in `index.ts`, `manifest.json` and `README.md`. | + +Resulting layout: + +``` +actions/-action/ +├── .gitignore +├── Dockerfile +├── README.md +├── manifest.json +├── package.json +├── tsconfig.json +├── vite.config.ts +├── src/ +│ ├── index.ts # creates the Action, registers everything, connects +│ ├── client.ts # vendor client, cached per credential +│ ├── helpers.ts # mappers (vendor object -> data type), error handling +│ ├── eventBridge.ts # only if the action has events +│ ├── data_types/.ts +│ ├── functions//.ts +│ └── events/.ts +└── test/ + └── index.test.ts +``` + +`` is the resource the functions work on (`messaging`, `channels`, +`members`, …), not the HTTP verb. + +## 3. Install dependencies + +```bash +cd actions/-action +corepack enable npm +npm install @code0-tech/hercules zod@4.4.3 +npm install -D @types/node tsx typescript vite vitest +``` + +Commit the generated `package-lock.json`; CI and the Dockerfile run `npm ci`. +Keep `@code0-tech/hercules` and `zod` on the same versions as `discord-action`. + +## 4. Write `client.ts` and `helpers.ts` + +- `client.ts`: one function `getClient(credential)` that trims the + credential, throws `RuntimeError("_MISSING_", ...)` when + it is empty, and caches one client per credential (see + `discord-action/src/client.ts`; drop idle clients if the SDK holds + connections open). +- `helpers.ts`: + - `handleError(error, fallbackCode, fallbackMessage): never` — maps + vendor error codes to `RuntimeError("_", message)`, + rethrows an existing `RuntimeError` unchanged, and falls back to + `fallbackCode`. + - `map(vendorObject)` per data type — see `add-data-type`. + +## 5. Add data types, functions and events + +Follow [`add-data-type`](../add-data-type/SKILL.md), +[`add-function`](../add-function/SKILL.md) and +[`add-event`](../add-event/SKILL.md). Register every class in `src/index.ts` — +an unregistered class is invisible in the editor and nothing else complains. + +## 6. Wire it into the repository + +- `.gitlab-ci.yml`: add `-action` to the `.node-actions` list. This + runs typecheck + tests and builds/publishes the image. Without it the action + is never built. +- Root `README.md`: add the action wherever actions are listed. +- `manifest.json` image must be + `ghcr.io/code0-tech/centaurus/ci-builds/-action`. + +## 7. Verify + +Run [`test-action`](../test-action/SKILL.md), then +[`review-action`](../review-action/SKILL.md). diff --git a/.skills/create-action/templates/.gitignore b/.skills/create-action/templates/.gitignore new file mode 100644 index 0000000..02f438d --- /dev/null +++ b/.skills/create-action/templates/.gitignore @@ -0,0 +1,4 @@ +.env +node_modules/ +dist/ +module.json diff --git a/.skills/create-action/templates/Dockerfile b/.skills/create-action/templates/Dockerfile new file mode 100644 index 0000000..af0d37b --- /dev/null +++ b/.skills/create-action/templates/Dockerfile @@ -0,0 +1,17 @@ +FROM node:24.10.0-alpine + +WORKDIR /app + +COPY package.json package-lock.json* ./ + +# Pins npm to the version package.json declares, so the lock is read by the +# same npm that wrote it. +RUN corepack enable npm + +RUN npm ci + +COPY . . + +RUN npm run build + +CMD ["npm", "run", "start"] diff --git a/.skills/create-action/templates/README.md b/.skills/create-action/templates/README.md new file mode 100644 index 0000000..bed627f --- /dev/null +++ b/.skills/create-action/templates/README.md @@ -0,0 +1,48 @@ +# __Vendor__ Action + +__DESCRIPTION__ + +The action holds no credentials of its own: **every runtime function and every +event takes the `` it works with as its first parameter**, so one +running action serves as many __Vendor__ accounts as its flows use. There is +nothing to configure on the module. + +## Functions + +| Function | Description | +|----------|-------------| +| `__vendor__SendMessage` | Send a message to a channel. | + +Each one starts with the `` parameter, followed by the ids it needs +(e.g. `__vendor__SendMessage(, channelId, content)`). + +## Events + +| Event | Fires when | Settings | +|-------|------------|----------| +| `__Vendor__MessageCreated` | A message is posted. | ``, `channelId?` | + +An optional setting that is left empty is a wildcard. + +## Payloads always carry every field + +Everything a function returns and every event payload contains **all** fields of +its data type: what __Vendor__ did not send is `null`, never missing, so a flow +reading it resolves the reference instead of failing with +`ReferenceValueNotFound`. + +## Setup + + + +## ENV + +| Variable | Description | Default | +|----------|-------------|---------| +| `ACTION_ID` | Identifier the action registers with. | `__vendor__-action` | +| `VERSION` | Version reported to Aquila. | `1.0.0` | +| `AQUILA_URL` | Aquila address. | `127.0.0.1:8081` | +| `AUTH_TOKEN` | Token used to connect to Aquila. | — | + +No __Vendor__ credentials are read from the environment. diff --git a/.skills/create-action/templates/manifest.json b/.skills/create-action/templates/manifest.json new file mode 100644 index 0000000..aa6aacb --- /dev/null +++ b/.skills/create-action/templates/manifest.json @@ -0,0 +1,10 @@ +{ + "name": "__vendor__", + "identifier": "__vendor__-action", + "description": "__DESCRIPTION__", + "deployment": { + "docker": { + "image": "ghcr.io/code0-tech/centaurus/ci-builds/__vendor__-action" + } + } +} diff --git a/.skills/create-action/templates/package.json b/.skills/create-action/templates/package.json new file mode 100644 index 0000000..dccd5e4 --- /dev/null +++ b/.skills/create-action/templates/package.json @@ -0,0 +1,31 @@ +{ + "name": "@code0-tech/__vendor__-action", + "version": "1.0.0", + "private": true, + "type": "module", + "packageManager": "npm@11.21.3", + "engines": { + "npm": ">=11.21.3" + }, + "main": "dist/index.js", + "scripts": { + "dev": "tsx watch src/index.ts", + "typecheck": "tsc --noEmit", + "build": "vite build", + "test": "vitest run", + "export": "hercules export src/index.ts -o module.json", + "start": "node dist/index.js" + }, + "dependencies": { + "@code0-tech/hercules": "^1.9.0", + "__VENDOR_SDK__": "", + "zod": "4.4.3" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "tsx": "^4.0.0", + "typescript": "^5.9.3", + "vite": "^8.0.3", + "vitest": "^4.1.10" + } +} diff --git a/.skills/create-action/templates/src/index.ts b/.skills/create-action/templates/src/index.ts new file mode 100644 index 0000000..1caf443 --- /dev/null +++ b/.skills/create-action/templates/src/index.ts @@ -0,0 +1,56 @@ +import "reflect-metadata"; +import { Action, CodeZeroEvent } from "@code0-tech/hercules"; + +// Only when the action has events: +// import { startEventBridge } from "./eventBridge.js"; + +// Data types — register types before the types that reference them. +// import { __Vendor__Message } from "./data_types/__vendor__Message.js"; + +// Runtime functions +// import { __Vendor__SendMessageFunction } from "./functions/messaging/__vendor__SendMessage.js"; + +// Events +// import { __Vendor__MessageCreated } from "./events/__vendor__MessageCreated.js"; + +// The action holds no credentials of its own: every function and every event +// takes the credential it works with as its first parameter, so one running +// action serves as many __Vendor__ accounts as its flows use. +const action = new Action( + process.env.ACTION_ID ?? "__vendor__-action", + process.env.VERSION ?? "1.0.0", + process.env.AQUILA_URL ?? "127.0.0.1:8081", + "code0-tech", + "__ICON__", + "__DESCRIPTION__", + [{ code: "en-US", content: "__Vendor__" }], + [] +); + +// action.registerDataTypeClass(__Vendor__Message); + +// action.registerRuntimeFunction(__Vendor__SendMessageFunction); + +// action.registerRuntimeEventClass(__Vendor__MessageCreated); + +// startEventBridge(action); + +action.on(CodeZeroEvent.connected, () => { + console.log("Connected to aquila"); +}); + +action.on(CodeZeroEvent.error, (error: Error) => { + console.error("Stream error:", error.message); + console.log("Attempting to reconnect in 5s..."); + setTimeout(() => { + action.connect(process.env.AUTH_TOKEN ?? "your_auth_token_here").catch((err: Error) => { + action.emit(CodeZeroEvent.error, err); + }); + }, 5000); +}); + +action.connect(process.env.AUTH_TOKEN ?? "your_auth_token_here").catch((err: Error) => { + action.emit(CodeZeroEvent.error, err); +}); + +export { action }; diff --git a/.skills/create-action/templates/test/index.test.ts b/.skills/create-action/templates/test/index.test.ts new file mode 100644 index 0000000..37470de --- /dev/null +++ b/.skills/create-action/templates/test/index.test.ts @@ -0,0 +1,66 @@ +import "reflect-metadata"; +import { describe, expect, it } from "vitest"; +import { readFile } from "node:fs/promises"; + +// import { __Vendor__SendMessageFunction } from "../src/functions/messaging/__vendor__SendMessage.js"; +// import { __Vendor__MessageCreated } from "../src/events/__vendor__MessageCreated.js"; + +/** Every runtime function of the action. Keep in sync with src/index.ts. */ +const functions: Function[] = [ + // __Vendor__SendMessageFunction, +]; + +/** Every event of the action. Keep in sync with src/index.ts. */ +const events: Function[] = [ + // __Vendor__MessageCreated, +]; + +/** The name of the credential every function and event takes first. */ +const CREDENTIAL = "apiToken"; + +describe("registration", () => { + it("registers every function and event in index.ts", async () => { + const source = await readFile(new URL("../src/index.ts", import.meta.url), "utf8"); + + for (const cls of [...functions, ...events]) { + expect(source, `${cls.name} is not registered in index.ts`).toMatch( + new RegExp(`register\\w+\\(${cls.name}\\)`) + ); + } + }); +}); + +describe("credential", () => { + it.each(functions)("is the first parameter of %o", (fn) => { + const parameters = Reflect.getMetadata("hercules:function_parameters", fn) as { runtimeName: string }[]; + const signature = Reflect.getMetadata("hercules:signature", fn) as string; + + expect(parameters[0].runtimeName).toEqual(CREDENTIAL); + expect(parameters[0]).not.toHaveProperty("optional", true); + expect(signature.startsWith(`(${CREDENTIAL}: string`)).toBe(true); + }); + + it.each(events)("is the first setting of %o", (event) => { + const settings = Reflect.getMetadata("hercules:flow_settings", event) as { identifier: string }[]; + const signature = Reflect.getMetadata("hercules:signature", event) as string; + + expect(settings[0].identifier).toEqual(CREDENTIAL); + expect(settings[0]).not.toHaveProperty("optional", true); + expect(signature.startsWith(`(${CREDENTIAL}: string`)).toBe(true); + }); +}); + +describe("parameters", () => { + it.each(functions)("match the signature and run() of %o", (fn) => { + const parameters = Reflect.getMetadata("hercules:function_parameters", fn) as { runtimeName: string }[]; + const signature = Reflect.getMetadata("hercules:signature", fn) as string; + const inSignature = [...signature.matchAll(/(\w+)\??:/g)].map((m) => m[1]); + + expect(parameters.map((p) => p.runtimeName)).toEqual(inSignature); + // run(context, ...parameters) + expect((fn as any).prototype.run.length).toEqual(parameters.length + 1); + }); +}); + +// Add per data type: a mapper test that checks every schema key is present +// (see .skills/test-action/SKILL.md, "Mapper tests"). diff --git a/.skills/create-action/templates/tsconfig.json b/.skills/create-action/templates/tsconfig.json new file mode 100644 index 0000000..65d780f --- /dev/null +++ b/.skills/create-action/templates/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "Bundler", + "declaration": true, + "outDir": "dist", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "baseUrl": ".", + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "types": ["node", "vite/client"] + }, + "include": [ + "src/**/*", + "test/**/*", + "vite.config.ts" + ] +} diff --git a/.skills/create-action/templates/vite.config.ts b/.skills/create-action/templates/vite.config.ts new file mode 100644 index 0000000..0c49129 --- /dev/null +++ b/.skills/create-action/templates/vite.config.ts @@ -0,0 +1,21 @@ +import { defineConfig } from 'vite'; +import { resolve } from 'path'; + +export default defineConfig({ + build: { + target: "node18", + ssr: resolve(__dirname, 'src/index.ts'), + rollupOptions: { + // Runtime dependencies stay external: they are installed in the image + // by `npm ci`. Add every package from "dependencies" here. + external: (id) => + [ + 'fs', + 'path', + 'typescript', + '@code0-tech/hercules', + '__VENDOR_SDK__' + ].includes(id) || id.startsWith('node:') + } + } +}); diff --git a/.skills/review-action/SKILL.md b/.skills/review-action/SKILL.md new file mode 100644 index 0000000..39be851 --- /dev/null +++ b/.skills/review-action/SKILL.md @@ -0,0 +1,78 @@ +--- +name: review-action +description: Checklist to review a new or changed TypeScript action against the repository conventions (structure, naming, credentials, payloads, errors, tests, docs, CI) before opening or merging a PR. Use when reviewing action changes or finishing work on an action. +--- + +# Review an action + +Go through the list for every action the change touches +(`git diff --stat main...HEAD -- actions/`). Report each failed item with the +file and line. Reference for "how it should look": `actions/discord-action`. + +## Structure + +- [ ] Folder is `actions/-action` with `package.json`, + `package-lock.json`, `tsconfig.json`, `vite.config.ts`, `Dockerfile`, + `manifest.json`, `README.md`, `.gitignore`, `src/`, `test/`. +- [ ] `package.json` name `@code0-tech/-action`, `packageManager` + npm pinned, scripts `dev`, `typecheck`, `build`, `test`, `start`. +- [ ] `@code0-tech/hercules` and `zod` versions match `discord-action`. +- [ ] Every runtime dependency is listed as external in `vite.config.ts`. +- [ ] `manifest.json` identifier `-action`, image + `ghcr.io/code0-tech/centaurus/ci-builds/-action`. +- [ ] Action added to `.node-actions` in `.gitlab-ci.yml` (and only there). +- [ ] No `dist/`, `node_modules/`, `module.json` or `.env` committed. + +## Naming + +- [ ] Functions: `functions//.ts`, class + `…Function`, identifier ``. +- [ ] Data types: `data_types/.ts`, `…Schema`, `…Type`, + identifier `_`. +- [ ] Events: `events/.ts`, class = identifier. +- [ ] All identifiers vendor-prefixed; error codes upper snake and + vendor-prefixed. + +## Registration and contract + +- [ ] Every data type, function and event is registered in `src/index.ts`; + nested data types before the ones that use them. +- [ ] `@Signature`, `@Parameter` list and `run()` arguments agree in names, + order and optionality. +- [ ] Credential is the first, required parameter of every function and first + setting of every event, with the same name everywhere. No credentials + read from env. +- [ ] Filter settings of events are optional and empty means "match all". +- [ ] Every node has `@Name`, `@Description`, `@DisplayMessage`, + `@DisplayIcon`; functions also `@Documentation`. Texts are `en-US`, + sentence case, and describe the behaviour correctly. +- [ ] **No breaking change** to existing identifiers, parameter + `runtimeName`s, setting identifiers or data type fields — or it is + called out in the PR. + +## Behaviour + +- [ ] Every function body goes through `handleError`; no raw vendor + error, no `console.log` of credentials or payloads with personal data. +- [ ] Every returned value / event payload goes through a mapper that fills + **every** schema field (`null` instead of missing). +- [ ] Optional schema fields are `.nullish()`. +- [ ] Inputs are trimmed / cleaned; empty optional input behaves like unset. +- [ ] Vendor clients are cached per credential and failed logins are not + cached. +- [ ] Event listeners never throw out of a vendor callback; flows are fired + with `Promise.allSettled`; the action ignores its own output where that + could loop. +- [ ] Lists respect vendor limits / pagination and document the maximum. + +## Tests and docs + +- [ ] [`test-action`](../test-action/SKILL.md) checks pass: `typecheck`, + `test`, `build`, `hercules export` counts match the registrations. +- [ ] Metadata test lists contain every function and event; a mapper test + exists for every data type; new helpers and error mappings are tested. +- [ ] No real tokens, ids or personal data in fixtures. +- [ ] README: functions table, events table (with settings), the + "payloads always carry every field" note, vendor setup (scopes, + intents, webhooks), ENV table. +- [ ] Description identical in `index.ts`, `manifest.json` and README. diff --git a/.skills/test-action/SKILL.md b/.skills/test-action/SKILL.md new file mode 100644 index 0000000..06d3676 --- /dev/null +++ b/.skills/test-action/SKILL.md @@ -0,0 +1,119 @@ +--- +name: test-action +description: Write and run the checks for a TypeScript action — vitest unit tests (metadata, mappers, helpers, faked vendor client), typecheck, build, module export and Docker build. Use after adding or changing anything in an action, and before opening a PR. +--- + +# Test an action + +All checks run without the runtime (Aquila) and without real vendor +credentials. Tests must never call the real vendor API. + +Reference: `actions/discord-action/test/`. + +## 1. Run the checks + +From `actions/-action`: + +```bash +corepack enable npm +npm ci # or npm install when adding dependencies +npm run typecheck # tsc --noEmit, includes test/ +npm test # vitest run +npm run build # vite build -> dist/index.js +npx hercules export src/index.ts -o module.json +``` + +`hercules export` loads `index.ts` **without connecting** and writes the +module exactly as the runtime would receive it. Check that the counts match +what you registered: + +```bash +node -e "const m=require('./module.json');for(const k of ['definitionDataTypes','functionDefinitions','flowTypes'])console.log(k,m[k].length)" +``` + +and skim the entries you added (names, parameters, signature). Don't commit +`module.json`. + +CI (`.gitlab-ci.yml`, `test-node`) runs `npm ci`, `typecheck` and `test` for +every action in `.node-actions`; all actions at once from the repo root: +`npm run typecheck && npm test`. + +Optionally build the image the way CI does: +`docker build -t -action .` + +## 2. What to test + +Put tests in `test/*.test.ts`. Start every file with +`import "reflect-metadata";`. + +### Metadata tests (required) + +Taken over from the template in +`.skills/create-action/templates/test/index.test.ts`. Keep the `functions` +and `events` lists complete; the tests then check for each class: + +- it is registered in `src/index.ts`, +- the credential is the first, required parameter / setting and starts the + signature, +- the `@Parameter` list matches the signature and `run()`. + +Decorator metadata is read with `Reflect.getMetadata(key, Class)`: +`hercules:function_parameters`, `hercules:signature`, `hercules:flow_settings`. + +### Mapper tests (required per data type) + +The most important behavioural test: every key of the data type is present. + +```ts +it("fills every field of a message, using null for what the vendor omitted", () => { + const message = mapVendorMessage({ id: "1", channel_id: "2", author: fakeUser, text: "hi", + edited_at: null, created_at: "2026-11-24T11:27:31.344Z" } as any); + + expect(Object.keys(message).sort()).toEqual(Object.keys(VendorMessageSchema.shape).sort()); + expect(message.editedAt).toBeNull(); + expect(VendorMessageSchema.parse(message)).toBeTruthy(); +}); +``` + +Use a minimal fake object cast with `as any` — just the fields the mapper +reads. Use realistic but **fake** ids and values; never paste real tokens, +SIDs or keys (they trip secret scanners — see the comment in +`twilio-action/test/index.test.ts`). + +### Helper tests + +Pure logic in `helpers.ts`: input cleaning (empty string → undefined, invalid +URL dropped), payload building and its validation errors, enum mapping incl. +the `"unknown"` fallback, `toEventPayload` (undefined → null). + +### Error tests + +- vendor error codes map to the expected `RuntimeError` code + (`expect(() => handleVendorError({ code: 50027, message: "…" })).toThrow(/VENDOR_…/)`), +- an existing `RuntimeError` passes through unchanged, +- a missing / blank credential is rejected + (`await expect(getVendorClient(" ")).rejects.toBeInstanceOf(RuntimeError)`). + +### Function / bridge tests with a fake client + +To test a function's `run()` or the event bridge, replace the client module +before importing the code under test: + +```ts +vi.mock("../src/client.js", () => ({ + getVendorClient: async (token: string) => fakeClients.get(token), +})); +const { VendorSendMessageFunction } = await import("../src/functions/messaging/vendorSendMessage.js"); +``` + +The fake records what was called so the test can assert on it. Example: +`discord-action/test/slashCommands.test.ts`. + +## 3. When a check fails + +- Typecheck error in a decorator → usually a typo in a `@Parameter` / + `@EventSetting` property; compare with discord. +- Missing count in the export → the class is not registered in `index.ts`. +- Mapper key test fails → a schema field was added without updating the + mapper (or vice versa). +- Fix the code, not the test, unless the test encodes an outdated contract.