@appweaver/skill 0.0.0-stage → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +29 -2
- package/index.d.ts +39 -0
- package/index.js +105 -0
- package/package.json +41 -3
- package/skill/GUIDELINES.md +383 -0
- package/skill/SKILL.md +121 -0
- package/skill/references/ai.md +231 -0
- package/skill/references/audit.md +220 -0
- package/skill/references/cache.md +233 -0
- package/skill/references/cli.md +760 -0
- package/skill/references/client.md +982 -0
- package/skill/references/configuration.md +1224 -0
- package/skill/references/database.md +349 -0
- package/skill/references/dependency-injection.md +301 -0
- package/skill/references/errors.md +486 -0
- package/skill/references/events.md +203 -0
- package/skill/references/logging.md +157 -0
- package/skill/references/mailer.md +393 -0
- package/skill/references/mcp.md +245 -0
- package/skill/references/modules.md +509 -0
- package/skill/references/patterns.md +1217 -0
- package/skill/references/payments.md +795 -0
- package/skill/references/queue.md +281 -0
- package/skill/references/realtime.md +572 -0
- package/skill/references/resources.md +2238 -0
- package/skill/references/scheduler.md +228 -0
- package/skill/references/security.md +1185 -0
- package/skill/references/sms.md +143 -0
- package/skill/references/spatial.md +197 -0
- package/skill/references/storage.md +500 -0
- package/skill/references/telemetry.md +207 -0
- package/skill/references/templates.md +488 -0
- package/skill/references/timeseries.md +312 -0
- package/skill/references/workflow.md +224 -0
package/skill/SKILL.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: appweaver
|
|
3
|
+
description: >
|
|
4
|
+
Use this skill whenever the user is building, debugging, scaffolding, or
|
|
5
|
+
asking questions about Appweaver - a web development library. Triggers
|
|
6
|
+
include: any mention of 'Appweaver', requests to create backend server logic,
|
|
7
|
+
configurations, resources, models, routes, services and security policy,
|
|
8
|
+
questions about the file conventions or config system. Use this skill
|
|
9
|
+
if @appweaver npm package or Appweaver is detected anywhere in the project
|
|
10
|
+
structure of Node.js (TypeScript) project.
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
# Appweaver skill
|
|
14
|
+
|
|
15
|
+
## Purpose
|
|
16
|
+
|
|
17
|
+
Appweaver is a library for building backend REST APIs with TypeScript and Node.js (or Bun). From a declarative
|
|
18
|
+
resource model it derives the database schema, the TypeScript types, and validated CRUD routes with an OpenAPI
|
|
19
|
+
specification, and it adds authentication, authorization, file storage, caching, queues, scheduling, and mailing on top,
|
|
20
|
+
all driven by a centralized configuration. It is built on Fastify for the web server and Prisma for the database ORM.
|
|
21
|
+
The library provides factory functions for creating resource models, services, policies, and routes with predefined
|
|
22
|
+
defaults, and a CLI tool for building the application, starting a server, generating schema and types, executing
|
|
23
|
+
migrations, running seeders, testing, and more.
|
|
24
|
+
|
|
25
|
+
## Project structure
|
|
26
|
+
|
|
27
|
+
The basic file structure of the Appweaver project:
|
|
28
|
+
|
|
29
|
+
- `database/` - database migrations, seeders, generated prisma client, and client used by the application
|
|
30
|
+
- `dist/` - the output directory for transpiled JavaScript files
|
|
31
|
+
- `locales/` - the translation files, a nested JSON file per locale (`en.json`, `de.json`, `locales` module)
|
|
32
|
+
- `public/` - publicly exposed files if static file serving is enabled
|
|
33
|
+
- `src/features/` - main application logic structured using vertical slice architecture (VSA)
|
|
34
|
+
- `src/resources/` - application resources (models, services, policies, and routes)
|
|
35
|
+
- `src/types/` - application types (generated and manually created)
|
|
36
|
+
- `src/main.ts` - the main application entrypoint
|
|
37
|
+
- `templates/` - the Handlebars templates of emails, HTML pages, XML exports or any other text (`*.<format>.hbs`,
|
|
38
|
+
`templates` module)
|
|
39
|
+
- `test/e2e/` - the end-to-end tests root directory
|
|
40
|
+
- `test/unit/` - the unit tests root directory
|
|
41
|
+
- `.env` - override the central configuration (optional)
|
|
42
|
+
- `.env.{env}` - override the central configuration for a specific environment (optional)
|
|
43
|
+
- `appweaver.json` - central library configuration file, with the overrides of each environment under `environments`
|
|
44
|
+
- `appweaver.{env}.json` - environment specific configuration files, overriding the `environments` section (optional)
|
|
45
|
+
- `Dockerfile` - the dockerfile used for building a docker image for deploying the application (`docker` module)
|
|
46
|
+
- `tsconfig.json` - TypeScript 5.9 with `strict`, so `noImplicitAny` is on: type every parameter, and an object built
|
|
47
|
+
key by key as `Record<string, unknown>`
|
|
48
|
+
|
|
49
|
+
**IMPORTANT:** `{env}` is controlled by `NODE_ENV` environment variable set before any command is executed (can also be
|
|
50
|
+
set in the `.env` file). The environment names are `test`, `local`, `dev`, `staging`, `qa`, and `prod`; `development`
|
|
51
|
+
resolves to `dev`, and `production` or an unset `NODE_ENV` to `prod`.
|
|
52
|
+
|
|
53
|
+
## How to use this skill
|
|
54
|
+
|
|
55
|
+
This file is the index: read [GUIDELINES.md](GUIDELINES.md) for the compact walkthrough of a project (entrypoint,
|
|
56
|
+
resources, custom routes, injection, seeders, tests), then only the reference of the task at hand from the table
|
|
57
|
+
below. [patterns.md](references/patterns.md) holds every pattern with its code, [workflow.md](references/workflow.md)
|
|
58
|
+
the daily commands.
|
|
59
|
+
|
|
60
|
+
## Workflow
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
weaver doctor # check the project first: packages, .env, config, generated files, migrations, skill
|
|
64
|
+
weaver resource new blog-post # model.ts, service.ts, routes.ts and policy.ts in src/resources/blog-post/
|
|
65
|
+
weaver generate # types, Prisma schema and client, config schema, after any model change
|
|
66
|
+
weaver migration new add_blog_post # create and apply the migration of the change (--create-only to edit its SQL)
|
|
67
|
+
weaver start --watch # develop; npm run e2e for the end-to-end tests
|
|
68
|
+
weaver config check # validate the config, i.e. NODE_ENV=prod weaver config check in CI
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Every report command takes `--json` (`doctor`, `config print`, `config check`, `module list`, `routes`, `run` without a
|
|
72
|
+
task): one JSON document on stdout, the logs and errors on stderr.
|
|
73
|
+
|
|
74
|
+
## Rules
|
|
75
|
+
|
|
76
|
+
- A resource is a directory of `src/resources/<name>/` with `model.ts` (`createModel`), `service.ts`
|
|
77
|
+
(`createService`), `routes.ts` (`createRoutes`) and `policy.ts` (`createPolicy`), each a default export. Create all
|
|
78
|
+
four unless asked otherwise, and run `weaver generate` after every change of a model, then
|
|
79
|
+
`weaver migration new <name>`.
|
|
80
|
+
- Keep the defaults: don't set default values, `omit`/`pick`, `input`/`output`, file `mimeType` and `namePattern`, or
|
|
81
|
+
index arrays without an explicit requirement.
|
|
82
|
+
- Every route needs an authenticated user unless it sets `public: true`; a policy narrows the records per user. A
|
|
83
|
+
policy receives `null` for an anonymous request only: the application's own calls (jobs, seeders, tests) skip it.
|
|
84
|
+
- The config lives in `appweaver.json` (`config` and `environments.<env>`), overridden by `.env` and the environment;
|
|
85
|
+
read it with the section objects (`serverConfig.PORT`), never `process.env`. A new key of a local module is declared
|
|
86
|
+
with `defineConfig`.
|
|
87
|
+
- Throw the error classes of `@appweaver/common` with an `ErrorCode` (or the codes of `defineErrors`), never an HTTP
|
|
88
|
+
error: the web module maps them to RFC 9457 problem details.
|
|
89
|
+
- Inject services with `inject`, `injectService('Model')` and `injectModel`, never by constructing them.
|
|
90
|
+
- The `totalCount` of a query is off unless asked (bounded by `resource.countLimit`), and a page deeper than
|
|
91
|
+
`resource.maxOffset` uses the cursor.
|
|
92
|
+
- Tests: `weaver test setup`, then each e2e file registers `afterAll(resetTestData, 10_000)` after stopping the
|
|
93
|
+
application; the e2e Jest config keeps `"maxWorkers": 1`. Run them with `npm run e2e`, which builds first: on Node
|
|
94
|
+
the application loads the compiled `dist`.
|
|
95
|
+
- The auth routes are at `/auth` (`POST /auth/login`), never under the `/api` of the resource routes.
|
|
96
|
+
- A policy limiting writes to their creator compares `resource.createdById` with `user.id` in `checkAccess`
|
|
97
|
+
([patterns.md](./references/patterns.md#creating-a-resource-policy)).
|
|
98
|
+
|
|
99
|
+
## References
|
|
100
|
+
|
|
101
|
+
| Task | Reference |
|
|
102
|
+
| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
|
103
|
+
| Every pattern with its code | [patterns.md](references/patterns.md) |
|
|
104
|
+
| The daily commands; every CLI option | [workflow.md](references/workflow.md), [cli.md](references/cli.md) |
|
|
105
|
+
| Models, services, routes, policies, filters, extending a model | [resources.md](references/resources.md) |
|
|
106
|
+
| Config keys of every module, environments, providers | [configuration.md](references/configuration.md) |
|
|
107
|
+
| Authentication, roles, API keys, OAuth2, 2FA, captchas | [security.md](references/security.md) |
|
|
108
|
+
| Database, migrations, transactions, SQLite in production | [database.md](references/database.md) |
|
|
109
|
+
| Modules, drivers and providers, local modules | [modules.md](references/modules.md) |
|
|
110
|
+
| Error codes and responses | [errors.md](references/errors.md) |
|
|
111
|
+
| Dependency injection | [dependency-injection.md](references/dependency-injection.md) |
|
|
112
|
+
| Files and storage | [storage.md](references/storage.md) |
|
|
113
|
+
| Events and hooks | [events.md](references/events.md) |
|
|
114
|
+
| Cache, queue, scheduler | [cache.md](references/cache.md), [queue.md](references/queue.md), [scheduler.md](references/scheduler.md) |
|
|
115
|
+
| Emails, text messages, templates and translations | [mailer.md](references/mailer.md), [sms.md](references/sms.md), [templates.md](references/templates.md) |
|
|
116
|
+
| Realtime channels, resource events, actions and streams | [realtime.md](references/realtime.md) |
|
|
117
|
+
| AI models and tools, the MCP server | [ai.md](references/ai.md), [mcp.md](references/mcp.md) |
|
|
118
|
+
| Online payments, subscriptions, Stripe, payment webhooks | [payments.md](references/payments.md) |
|
|
119
|
+
| Time series, spatial fields, audit log | [timeseries.md](references/timeseries.md), [spatial.md](references/spatial.md), [audit.md](references/audit.md) |
|
|
120
|
+
| Logging, OpenTelemetry | [logging.md](references/logging.md), [telemetry.md](references/telemetry.md) |
|
|
121
|
+
| A typed HTTP client of the API | [client.md](references/client.md) |
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# AI models
|
|
2
|
+
|
|
3
|
+
`@appweaver/ai` calls AI models through `AiService`: whole responses, streams, objects matching a schema,
|
|
4
|
+
classifications and embeddings, directly or through the `ai` queue, running the tools the model calls. The `openai`
|
|
5
|
+
driver of `@appweaver/openai` speaks the OpenAI Chat Completions and Embeddings APIs, which every OpenAI-compatible
|
|
6
|
+
server implements (Ollama, LM Studio, vLLM, llama.cpp, OpenRouter, Groq, DeepSeek, Mistral, Gemini, ...).
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @appweaver/ai @appweaver/openai # or: weaver module add ai
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Configuration
|
|
13
|
+
|
|
14
|
+
- **Endpoint**: a server you name, with a `preset` filling in the driver, base URL, API key variable and capabilities.
|
|
15
|
+
- **Model reference**: `<endpoint>:<model>`, split at the first `:` (`local:qwen3:8b`). The `mock` endpoint is built in.
|
|
16
|
+
- **`defaultModel`**: the model of a call naming none.
|
|
17
|
+
- **`aliases`**: your own names for references (any name without `:`), so the code never names a vendor. A list is tried
|
|
18
|
+
in turn on `AI_RATE_LIMITED`, `AI_TIMEOUT` and `AI_PROVIDER_UNAVAILABLE`.
|
|
19
|
+
|
|
20
|
+
```jsonc
|
|
21
|
+
{
|
|
22
|
+
"config": {
|
|
23
|
+
"ai": {
|
|
24
|
+
"endpoints": {
|
|
25
|
+
"local": { "preset": "ollama" },
|
|
26
|
+
"openrouter": {
|
|
27
|
+
"preset": "openrouter",
|
|
28
|
+
"apiKey": "${OPENROUTER_API_KEY}"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"defaultModel": "openrouter:openai/gpt-4o-mini",
|
|
32
|
+
"aliases": {
|
|
33
|
+
"fast": "openrouter:openai/gpt-4o-mini",
|
|
34
|
+
"smart": ["openrouter:anthropic/claude-sonnet-4.5", "local:qwen3:14b"]
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"environments": {
|
|
39
|
+
"dev": {
|
|
40
|
+
"ai": {
|
|
41
|
+
"defaultModel": "local:qwen3:8b",
|
|
42
|
+
"aliases": { "fast": "local:qwen3:8b", "smart": "local:qwen3:14b" }
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"test": {
|
|
46
|
+
"ai": {
|
|
47
|
+
"defaultModel": "mock:echo",
|
|
48
|
+
"aliases": { "fast": "mock:echo", "smart": "mock:echo" }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Each endpoint property is also a variable, `AI_ENDPOINTS_<NAME>_<PROPERTY>` (`AI_ENDPOINTS_OPENROUTER_API_KEY`), and an
|
|
56
|
+
endpoint without `apiKey` reads its preset's variable. Startup fails when a default model or alias names an unknown
|
|
57
|
+
endpoint.
|
|
58
|
+
|
|
59
|
+
| Preset | Base URL | API key variable |
|
|
60
|
+
| -------------------------------------------------------------------------------------- | -------------------------------------- | -------------------------------- |
|
|
61
|
+
| `openai` | `https://api.openai.com/v1` | `OPENAI_API_KEY` |
|
|
62
|
+
| `openrouter` | `https://openrouter.ai/api/v1` | `OPENROUTER_API_KEY` |
|
|
63
|
+
| `ollama`, `lmstudio`, `vllm`, `llamacpp` | `localhost` on 11434, 1234, 8000, 8080 | `OLLAMA_API_KEY`, `VLLM_API_KEY` |
|
|
64
|
+
| `litellm` | `http://localhost:4000/v1` | `LITELLM_API_KEY` |
|
|
65
|
+
| `groq`, `together`, `fireworks`, `deepseek`, `mistral`, `xai`, `gemini`, `huggingface` | their APIs | `<NAME>_API_KEY`, `HF_TOKEN` |
|
|
66
|
+
| `mock` | - | - |
|
|
67
|
+
|
|
68
|
+
Any other server sets its `baseUrl` (the `openai` driver is the default). A call needing a capability the endpoint lacks
|
|
69
|
+
(`tools`, `json`, `json-schema`, `images`, `files`, `reasoning`, `embeddings`) fails with `AI_CAPABILITY_UNSUPPORTED`
|
|
70
|
+
before it is sent; set `capabilities` on the endpoint to correct the preset.
|
|
71
|
+
|
|
72
|
+
## AiService
|
|
73
|
+
|
|
74
|
+
| Method | Returns |
|
|
75
|
+
| --------------------------------------- | ------------------------- |
|
|
76
|
+
| `generate(prompt)` | `Promise<AiResult>` |
|
|
77
|
+
| `stream(prompt)` | `AiStream` |
|
|
78
|
+
| `generateObject({ ...prompt, schema })` | `Promise<AiObjectResult>` |
|
|
79
|
+
| `streamObject({ ...prompt, schema })` | `AiObjectStream` |
|
|
80
|
+
| `classify(input, labels, prompt?)` | `Promise<label>` |
|
|
81
|
+
| `embed(texts, options?)` | `Promise<AiEmbedResult>` |
|
|
82
|
+
| `supports(model, capability)` | `Promise<boolean>` |
|
|
83
|
+
| `enqueue(prompt, jobOptions?)` | `Promise<jobId>` |
|
|
84
|
+
| `generateQueued(prompt, jobOptions?)` | `Promise<AiResult>` |
|
|
85
|
+
| `streamQueued(prompt, options?)` | `AiStream` |
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
const ai = inject(AiService);
|
|
89
|
+
const { text, usage, messages } = await ai.generate({
|
|
90
|
+
model: 'fast', // an alias or a reference, default: ai.defaultModel
|
|
91
|
+
system: 'Summarize in one sentence.',
|
|
92
|
+
prompt: ticket.body, // the user message, after `messages`
|
|
93
|
+
messages: history,
|
|
94
|
+
maxTokens: 200,
|
|
95
|
+
temperature: 0.2,
|
|
96
|
+
reasoning: 'low',
|
|
97
|
+
providerOptions: { provider: { sort: 'price' } }, // sent as they are
|
|
98
|
+
signal
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`system` and `prompt` also take a template, `{ template, data, locale }` (`prompts/summarize` renders
|
|
103
|
+
`templates/prompts/summarize.md.hbs`), and `prompt` takes parts: `{ type: 'image', url | data, mimeType }` and
|
|
104
|
+
`{ type: 'file', data, mimeType }` (a PDF). The result has `text`, `toolCalls`, `finishReason`, `reasoning`, the summed
|
|
105
|
+
`usage`, the `model` reference that answered, its `steps` and the `messages` to continue the conversation.
|
|
106
|
+
|
|
107
|
+
### Streams
|
|
108
|
+
|
|
109
|
+
An `AiStream` is read once: iterate it (text deltas), its `parts()` (`text-delta`, `reasoning-delta`, `tool-call`,
|
|
110
|
+
`tool-result`, `finish`) or `text()`. `result` resolves once it ends, `abort()` aborts the call.
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
for await (const text of ai.stream({ prompt: question, signal }))
|
|
114
|
+
process.stdout.write(text);
|
|
115
|
+
|
|
116
|
+
createRealtimeAction({
|
|
117
|
+
// a streaming action returns the stream as it is
|
|
118
|
+
name: 'assistant.ask',
|
|
119
|
+
payload: Type.Object({ question: Type.String() }),
|
|
120
|
+
stream: { codec: 'text' },
|
|
121
|
+
handler: ({ question }, { signal }) =>
|
|
122
|
+
inject(AiService).stream({ prompt: question, signal })
|
|
123
|
+
});
|
|
124
|
+
await pipeAiStream(ai.stream({ prompt }), roomAnswer.open(roomId)); // into a stream of createStream
|
|
125
|
+
reply
|
|
126
|
+
.header('content-type', 'text/event-stream')
|
|
127
|
+
.send(aiEventStream(ai.stream({ prompt }))); // SSE over HTTP
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Objects and classification
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
const { object } = await ai.generateObject({
|
|
134
|
+
prompt: ticket.body,
|
|
135
|
+
schema: TicketTriage
|
|
136
|
+
});
|
|
137
|
+
const label = await ai.classify(ticket.body, ['bug', 'billing', 'question']);
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The JSON schema mode is used when the endpoint has it, otherwise its JSON mode or the prompt. An object not matching
|
|
141
|
+
the schema is sent back with the errors up to `ai.repairAttempts` times, then fails with `AI_OUTPUT_INVALID`.
|
|
142
|
+
`streamObject` yields the partial objects and checks the final one without repairs.
|
|
143
|
+
|
|
144
|
+
### Tools
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
export const getOrder = createAiTool({
|
|
148
|
+
name: 'getOrder',
|
|
149
|
+
description: 'The status of an order of the current user',
|
|
150
|
+
parameters: Type.Object({ orderId: Type.Integer() }),
|
|
151
|
+
execute: ({ orderId }) => inject(OrderService).findOne({ id: orderId }) // runs as the user of the call
|
|
152
|
+
});
|
|
153
|
+
await ai.generate({ prompt: 'Where is my order 42?', tools: [getOrder] });
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
The model is called again with the tool results until it answers or `maxSteps` (`ai.maxSteps`) calls ran. Invalid
|
|
157
|
+
arguments, thrown errors and unknown tools are sent back as failed results. A tool without `execute` ends the call and
|
|
158
|
+
returns its `toolCalls`. Registered tools can be named (`tools: ['getOrder']`), which queued prompts must do.
|
|
159
|
+
|
|
160
|
+
### Embeddings
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
const { embeddings } = await ai.embed(texts); // ai.defaultEmbeddingModel
|
|
164
|
+
const best = rankBySimilarity(queryVector, docs, (doc) => doc.embedding, 3); // and cosineSimilarity(a, b)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### Queue
|
|
168
|
+
|
|
169
|
+
`enqueue` and `generateQueued` run the call on any instance's `ai` worker (`ai.queueConcurrency`), with the queue's
|
|
170
|
+
retries; `generateQueued` gets the result through the `PubSub`. `streamQueued` relays the worker's parts through the
|
|
171
|
+
`PubSub`, is attempted once, and aborting it aborts the worker's call. Queued prompts are JSON, naming their tools.
|
|
172
|
+
The job carries the auth context of the call queuing it (the id of the user and of the roles and permissions the call
|
|
173
|
+
held, narrowed to its API key, the auth type and source, and the id of the API key), never the record of the user. The
|
|
174
|
+
worker loads the user as they are now and runs its tools as that user (`runAs`), holding only the roles and permissions
|
|
175
|
+
both the call and the user now hold, so they apply the same policies as the call; a user deleted or disabled since
|
|
176
|
+
fails the job with `AUTH_UNAUTHORIZED`, and without an auth model the tools run anonymously. The application's own
|
|
177
|
+
call, or one inside `withoutPolicies`, runs as the application (`runAsSystem`).
|
|
178
|
+
|
|
179
|
+
## Errors
|
|
180
|
+
|
|
181
|
+
| Code | Status | When |
|
|
182
|
+
| ---------------------------- | ------ | --------------------------------------------------------------- |
|
|
183
|
+
| `AI_MODEL_UNKNOWN` | 500 | No model, an unknown alias or endpoint, an invalid reference |
|
|
184
|
+
| `AI_REQUEST_INVALID` | 400 | No messages, an unknown tool name, functions in a queued prompt |
|
|
185
|
+
| `AI_CAPABILITY_UNSUPPORTED` | 400 | The model lacks a needed capability (`details.capability`) |
|
|
186
|
+
| `AI_REQUEST_FAILED` | 502 | The endpoint rejected the request |
|
|
187
|
+
| `AI_AUTH_FAILED` | 502 | The endpoint rejected the API key |
|
|
188
|
+
| `AI_RATE_LIMITED` | 429 | Rate limited (`details.retryAfter`) |
|
|
189
|
+
| `AI_TIMEOUT` | 504 | The request timed out |
|
|
190
|
+
| `AI_PROVIDER_UNAVAILABLE` | 503 | Unreachable, or a server error |
|
|
191
|
+
| `AI_CONTEXT_LENGTH_EXCEEDED` | 422 | The messages exceed the model's context |
|
|
192
|
+
| `AI_OUTPUT_INVALID` | 502 | The object does not match the schema after the repairs |
|
|
193
|
+
|
|
194
|
+
The SDK retries rate limits, timeouts and server errors `maxRetries` times first. An aborted call throws its signal's
|
|
195
|
+
reason.
|
|
196
|
+
|
|
197
|
+
## Testing and local development
|
|
198
|
+
|
|
199
|
+
- **Local models**: `ollama pull qwen3:0.6b` (`qwen3:8b` for tools) and a `dev` environment on the `local` endpoint.
|
|
200
|
+
- **`mock` endpoint**: `echo` repeats the last user message, `tools` calls every tool once, a schema is answered with
|
|
201
|
+
its default value, embeddings are derived from the text. `mockAiResponse((request) => 'Paris')` scripts its answers.
|
|
202
|
+
- **Drivers**: `registerAiDriver(name, Class)` registers a driver without a module, and a driver package runs
|
|
203
|
+
`testAiDriverContract` of `@appweaver/testing`.
|
|
204
|
+
|
|
205
|
+
## Writing a driver
|
|
206
|
+
|
|
207
|
+
A driver extends `AiDriver` (`generate`, `stream`, `checkHealth`, optional `embed`), is created once per endpoint
|
|
208
|
+
(`this.endpoint`), throws `AiError` with the codes above, and is provided by a module:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
export default defineModule({
|
|
212
|
+
name: '@acme/appweaver-anthropic',
|
|
213
|
+
requires: ['@appweaver/ai'],
|
|
214
|
+
providers: [
|
|
215
|
+
{
|
|
216
|
+
contract: AiDriver,
|
|
217
|
+
name: 'anthropic',
|
|
218
|
+
load: () => import('./anthropic-driver')
|
|
219
|
+
}
|
|
220
|
+
]
|
|
221
|
+
});
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Endpoints select it with `"driver": "anthropic"`; every installed driver is usable at once.
|
|
225
|
+
|
|
226
|
+
## Health and telemetry
|
|
227
|
+
|
|
228
|
+
The `ai` health check lists the models of `ai.healthCheckEndpoints`. Every model call is a `chat <model>` or
|
|
229
|
+
`embeddings <model>` span with the `gen_ai.*` attributes, every tool call an `execute_tool <name>` span, with the
|
|
230
|
+
`gen_ai.client.token.usage` and `gen_ai.client.operation.duration` metrics (`telemetry.instrumentations.ai`). Prompts
|
|
231
|
+
are logged only with `ai.logPrompts`.
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# Audit log
|
|
2
|
+
|
|
3
|
+
The audit log of `@appweaver/data` and `@appweaver/web` records who did what: every request of the server, by an
|
|
4
|
+
authenticated user or an anonymous one, and the changed fields of every record the resource services create, update
|
|
5
|
+
and delete. It is off by default:
|
|
6
|
+
|
|
7
|
+
```json
|
|
8
|
+
{
|
|
9
|
+
"config": {
|
|
10
|
+
"audit": {
|
|
11
|
+
"enabled": true,
|
|
12
|
+
"retention": "90d"
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Enabling it adds the `AuditLog` and `AuditChange` models, so run `weaver generate` and `weaver migration new
|
|
19
|
+
add_audit_log` afterwards. `AuditLog` in `database.keepTables` keeps both tables while the audit log is disabled, like `ApiKey` does
|
|
20
|
+
for the API keys, so the next migration does not drop the history.
|
|
21
|
+
|
|
22
|
+
## Tables
|
|
23
|
+
|
|
24
|
+
`AuditLog` holds one entry per request, or per change made outside of a request:
|
|
25
|
+
|
|
26
|
+
| Field | Description |
|
|
27
|
+
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
28
|
+
| `id` | A UUIDv7, so the entries sort by time. |
|
|
29
|
+
| `category` | `auth`, `read`, `write`, `change` (a change made outside of a request) or `custom`. |
|
|
30
|
+
| `source` | `http`, `mcp`, `realtime`, `job`, `task` or `system` (no scope, i.e. a queue worker). |
|
|
31
|
+
| `action` | The resource action (`update`), the auth route (`auth.login`), the tool (`mcp.post_create`). |
|
|
32
|
+
| `method`, `route`, `path`, `query` | The request: its route template (`/api/posts/:id`) and its redacted query. |
|
|
33
|
+
| `body` | The redacted JSON body, with `audit.requestBody` only. |
|
|
34
|
+
| `status`, `errorCode`, `duration` | The response status, the error code of a failed request, the duration in milliseconds. |
|
|
35
|
+
| `userId`, `authType`, `apiKeyId` | The authenticated user, or the one a sign-in signs in, empty for an anonymous request. A plain value without a relation, kept on deletion. |
|
|
36
|
+
| `ip`, `userAgent`, `requestId`, `traceId` | The client and the request, the trace of the telemetry. |
|
|
37
|
+
| `model`, `resourceId` | The record of a resource route, or the one record a request changed (i.e. created). |
|
|
38
|
+
| `metadata` | Free JSON of the entries of the application. |
|
|
39
|
+
| `createdAt` | When the request started. |
|
|
40
|
+
|
|
41
|
+
`AuditChange` holds one row per changed record, deleted with its entry: `model`, `resourceId`, `action` (`create`,
|
|
42
|
+
`update`, `delete`) and `diff`, the changed fields as `{ field: { from, to } }`, `from` absent on a create and `to`
|
|
43
|
+
absent on a delete. A relation is compared by the ids of its records, a value longer than `audit.maxValueSize` is
|
|
44
|
+
truncated, and an update changing nothing is not recorded.
|
|
45
|
+
|
|
46
|
+
## Categories
|
|
47
|
+
|
|
48
|
+
Each category is switched and kept on its own, its empty `retention` falling back to `audit.retention`:
|
|
49
|
+
|
|
50
|
+
| Section | Default | Records |
|
|
51
|
+
| --------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
|
52
|
+
| `audit.auth` | on | The routes of `security.routePrefix` and `security.account.routePrefix` (login, OAuth2, 2FA, account), failed ones included. |
|
|
53
|
+
| `audit.read` | off | The `find`, `query`, `aggregate` and `export` routes, and the `GET` routes. |
|
|
54
|
+
| `audit.write` | on | The create, update, delete, bulk and file routes, and the routes of the other methods. |
|
|
55
|
+
| `audit.changes` | on | The diffs of the records. Off, no `AuditChange` is written at all. |
|
|
56
|
+
| `audit.custom` | on | The entries of `AuditService.record`. |
|
|
57
|
+
|
|
58
|
+
The changes of a request whose category is disabled are still recorded, each with an entry of its own (`change`), so
|
|
59
|
+
`audit.write.enabled: false` keeps the history of the records without an entry per request.
|
|
60
|
+
|
|
61
|
+
## Excluding
|
|
62
|
+
|
|
63
|
+
- `audit.excludePaths`: URL paths, exact or a prefix ending with `*`. The health check, Swagger, static file and
|
|
64
|
+
template preview routes are always left out, and so are the `OPTIONS` requests.
|
|
65
|
+
- The webhook and return routes of `@appweaver/payments` and its read-only record routes are left out too
|
|
66
|
+
(`audit: false`). Its action routes (a refund, a capture, a subscription) are recorded like any custom route.
|
|
67
|
+
- `audit.excludeModels`: whole resources, their routes and their changes.
|
|
68
|
+
- `audit.excludeActions`: an action of every model (`find`, `export`, `auth.refresh`) or of one (`Post.update`).
|
|
69
|
+
- The `audit` option of a route: `false` leaves the route and the changes it makes out, an object sets the category
|
|
70
|
+
and the action of its entries.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
registerRoute((router) => router.post('/invoices/:id/send', sendInvoice), {
|
|
74
|
+
audit: { category: 'custom', action: 'invoice.send' }
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
createRoutes({ modelName: 'Session', defaults: { audit: false } }); // every route of the resource
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Redaction
|
|
81
|
+
|
|
82
|
+
Passwords and secrets never reach the audit log. A value is replaced with `[Redacted]`, the change itself still
|
|
83
|
+
recorded, when its field:
|
|
84
|
+
|
|
85
|
+
- is `hidden` (`passwordHash`, `keyHash`) or has the `redact` option,
|
|
86
|
+
- is named like a secret: `password`, `secret`, `token`, `privateKey`, `credentials`, `apiKey` and their compounds
|
|
87
|
+
(`clientSecret`, `refreshToken`),
|
|
88
|
+
- or is one of `audit.redactKeys` (`['code']` by default, the 2FA and OAuth2 codes).
|
|
89
|
+
|
|
90
|
+
The same names are redacted inside the JSON fields, the query and the body. `redact` keeps a field in the API output
|
|
91
|
+
while keeping its values out of the audit log:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
createModel({
|
|
95
|
+
name: 'Patient',
|
|
96
|
+
scalars: {
|
|
97
|
+
diagnosis: { type: 'string', redact: true }
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The `email` and `phone` of the auth model take `redact` too, to keep the contact details of the users out of the diffs
|
|
103
|
+
(`createAuthModel({ name: 'User', scalars: { email: { type: 'string', redact: true } } })`).
|
|
104
|
+
|
|
105
|
+
`audit.anonymizeIp` stores the client addresses without their last octet (IPv4) or their last 80 bits (IPv6).
|
|
106
|
+
|
|
107
|
+
## Writing
|
|
108
|
+
|
|
109
|
+
The entries are buffered and written in batches (`audit.flushInterval`, `audit.batchSize`), so a request never waits
|
|
110
|
+
for its entry, and flushed when the application stops. The flush runs `audit.flushInterval` after an entry is buffered,
|
|
111
|
+
so an idle application runs no timer. A batch failing is retried once with the next flush. Beyond
|
|
112
|
+
`audit.maxBuffer` buffered rows (an entry and each of its changes) the oldest entries are dropped with a warning, and a
|
|
113
|
+
request making more changes keeps its first ones, counted in the `appweaver.audit.dropped` metric
|
|
114
|
+
(`appweaver.audit.written` counts the written ones). The flushes write outside of the call adding the entry (its
|
|
115
|
+
transaction), and the services are destroyed before the drivers, so the last flush reaches the queue or the database.
|
|
116
|
+
|
|
117
|
+
A request only buffers the two states of a changed record, copied when the change is recorded (their JSON form, a
|
|
118
|
+
relation as the ids of its records): the diff is computed when the batch is written, so an update changing nothing is
|
|
119
|
+
left out then. With `audit.writeVia: 'queue'` a batch is sent as a job of the `audit` queue
|
|
120
|
+
(BullMQ across instances) instead of written, and the instances with `audit.writeWorker` (the default) write it, so the
|
|
121
|
+
API instances run no insert: `audit.writeWorker: false` on them, `true` on a worker instance.
|
|
122
|
+
|
|
123
|
+
A change is recorded once its transaction commits, so a rolled back change leaves no trace. Only the writes of the
|
|
124
|
+
resource services are recorded: code writing through Prisma directly (`service.client`, `db.client()`) records its
|
|
125
|
+
changes itself:
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
import { inject } from '@appweaver/core';
|
|
129
|
+
import { AuditService } from '@appweaver/data';
|
|
130
|
+
|
|
131
|
+
const audit = inject(AuditService);
|
|
132
|
+
|
|
133
|
+
const previous = await tx.order.findUnique({ where: { id } });
|
|
134
|
+
const current = await tx.order.update({
|
|
135
|
+
where: { id },
|
|
136
|
+
data: { status: 'shipped' }
|
|
137
|
+
});
|
|
138
|
+
audit.recordChange('Order', 'update', previous, current);
|
|
139
|
+
|
|
140
|
+
audit.record({
|
|
141
|
+
category: 'custom',
|
|
142
|
+
action: 'invoice.sent',
|
|
143
|
+
model: 'Invoice',
|
|
144
|
+
resourceId: invoice.id
|
|
145
|
+
});
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`record` takes the user, the client and the trace of the current call when the entry does not set them.
|
|
149
|
+
|
|
150
|
+
## Request scope
|
|
151
|
+
|
|
152
|
+
A change belongs to the entry of the request it is made in through the request scope of `@appweaver/core`, which the
|
|
153
|
+
web module creates for every request. Outside of a request, run the code in a scope to record its changes under a
|
|
154
|
+
source and an action:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
import { runInRequestScope, setRequestScope } from '@appweaver/core';
|
|
158
|
+
|
|
159
|
+
await runInRequestScope({ source: 'job', action: 'import.products' }, () =>
|
|
160
|
+
importProducts()
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
setRequestScope({ action: 'report.publish' }); // the action of the entry of the current request
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
A request is recorded with the user it authenticates. A route without authentication, i.e. a `public` route, reads no
|
|
167
|
+
credentials, so its entries are anonymous even when the client sends a token. A sign-in (the password login, OAuth2,
|
|
168
|
+
the token exchange ending the 2FA challenge) names the user it issues the tokens to in the scope (`userId`), so its
|
|
169
|
+
entry is theirs, and a failed one stays anonymous.
|
|
170
|
+
|
|
171
|
+
`weaver run` runs every task in a scope of the `task` source (`task.<name>`), and the MCP server names the tool of a
|
|
172
|
+
call (`source: 'mcp'`, `mcp.<tool>`). The actions of the realtime connections are not recorded yet, only the request
|
|
173
|
+
opening the connection.
|
|
174
|
+
|
|
175
|
+
## Reading
|
|
176
|
+
|
|
177
|
+
`audit.routes.enabled: true` serves the audit log with the routes of the framework: `/audit-logs` and
|
|
178
|
+
`/audit-changes`, `find` and `query` only, for the roles of `audit.routes.roles` (`['Admin']`), left out of the audit
|
|
179
|
+
log themselves, with a service and an append-only policy of each model. They are off by default.
|
|
180
|
+
|
|
181
|
+
For other access rules, leave them off and expose the models like the application's own resources, with a service,
|
|
182
|
+
its routes and a policy each (`src/resources/audit-log/`, `src/resources/audit-change/`):
|
|
183
|
+
|
|
184
|
+
```ts
|
|
185
|
+
// service.ts
|
|
186
|
+
export default createService({ modelName: 'AuditLog' });
|
|
187
|
+
|
|
188
|
+
// routes.ts: read-only, for the admins, reading the audit log left out of it
|
|
189
|
+
export default createRoutes({
|
|
190
|
+
modelName: 'AuditLog',
|
|
191
|
+
actions: ['find', 'query'],
|
|
192
|
+
defaults: { roles: ['Admin'], audit: false }
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// policy.ts: append-only, so no service call changes the history either
|
|
196
|
+
export default createPolicy({
|
|
197
|
+
modelName: 'AuditLog',
|
|
198
|
+
checkAccess: (_user, _resource, action) =>
|
|
199
|
+
!['create', 'update', 'delete'].includes(action)
|
|
200
|
+
});
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
The same for `AuditChange`. The routes take the filters, sorts and paging of every resource route, and permissions or
|
|
204
|
+
`readRestrictions` of the policy (i.e. the entries of a tenant) like any resource. An entry found by its id comes with
|
|
205
|
+
its changes, and a change with its entry, so the history of a record is a query of the changes:
|
|
206
|
+
|
|
207
|
+
```http
|
|
208
|
+
POST /api/audit-changes/query
|
|
209
|
+
{ "filter": { "model": "Post", "resourceId": "5" }, "sort": "-createdAt" }
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Only the `AuditService` writes the tables and only the retention deletes the entries, so keep the write routes
|
|
213
|
+
excluded. `sample/cms-api` exposes both models this way.
|
|
214
|
+
|
|
215
|
+
## Retention
|
|
216
|
+
|
|
217
|
+
The entries older than the retention of their category are deleted with their changes, in batches of
|
|
218
|
+
`maintenance.batchSize`, by the `auditRetention` maintenance job, once per cluster every hour by default
|
|
219
|
+
(`maintenance.jobs.auditRetention.schedule`, see the [maintenance jobs](./modules.md#maintenance-jobs)). `audit.retention:
|
|
220
|
+
0` keeps every entry.
|