@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.2
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 +1403 -2
- package/build-internals.ts +25 -0
- package/caller/agent-launch.ts +60 -0
- package/client.tsx +498 -0
- package/component-actions.ts +327 -0
- package/component-alerts.ts +136 -0
- package/component-attributes.ts +340 -0
- package/component-parts.tsx +1177 -0
- package/core-contracts/auth.ts +40 -0
- package/package.json +98 -4
- package/quit.ts +58 -0
- package/regions.tsx +94 -0
- package/screen-search.ts +211 -0
- package/send-file.ts +175 -0
- package/server-build-internals.ts +11 -0
- package/solid.ts +132 -0
- package/src/agent-command.ts +48 -0
- package/src/agent-info-cache.ts +34 -0
- package/src/agent-reports.ts +140 -0
- package/src/agent-turn.ts +289 -0
- package/src/api.ts +174 -0
- package/src/auth.ts +39 -0
- package/src/call-error.ts +37 -0
- package/src/caller-storage.ts +32 -0
- package/src/client.ts +163 -0
- package/src/database.ts +322 -0
- package/src/functions.ts +726 -0
- package/src/hooks.ts +141 -0
- package/src/host.ts +211 -0
- package/src/http-action.ts +55 -0
- package/src/index.ts +126 -0
- package/src/internal/contracts.ts +260 -0
- package/src/internal/machine-scope.ts +21 -0
- package/src/local.ts +22 -0
- package/src/plugin.ts +162 -0
- package/src/points.ts +79 -0
- package/src/protocol.ts +64 -0
- package/src/schema.ts +136 -0
- package/src/storage.ts +193 -0
- package/src/thread-context.ts +42 -0
- package/src/transport.ts +421 -0
- package/src/triggers.ts +87 -0
- package/src/unstable.ts +66 -0
- package/src/validators.ts +248 -0
- package/src/values.ts +98 -0
- package/src/visibility.ts +8 -0
- package/src/websocket-transport.ts +91 -0
- package/src/window-state-protocol.ts +7 -0
- package/src/within.ts +24 -0
- package/src/worker-limits.ts +5 -0
- package/tools/bundle.mjs +490 -0
- package/tools/client-entry.mjs +10 -0
- package/tools/contracts.mjs +254 -0
- package/tools/http-actions.mjs +42 -0
- package/tools/placement.mjs +535 -0
- package/tools/plugin-boundary.mjs +592 -0
- package/tools/plugin-compiler.mjs +125 -0
- package/tools/plugin-descriptor.ts +75 -0
- package/tools/points.mjs +340 -0
- package/tools/result-validator.mjs +83 -0
- package/tools/server-builtins.mjs +82 -0
- package/tools/server-files.mjs +34 -0
- package/tools/table-references.mjs +98 -0
- package/tools/worker.mjs +110 -0
- package/tsconfig.plugin-server.json +12 -0
- package/tsconfig.plugin-window.json +15 -0
- package/view.ts +27 -0
- package/web.d.ts +6 -0
- package/window-state-host.ts +228 -0
- package/window-state.ts +43 -0
package/README.md
CHANGED
|
@@ -1,3 +1,1404 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tokamaq/sdk (POC)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The portable authoring/client layer between TypeScript features and the native
|
|
4
|
+
host. `src/` uses ES2022 only. `tools/` runs on the pinned Bun 1.4.4 build machine,
|
|
5
|
+
not in QuickJS. There is no SDK CLI and no runtime dependency.
|
|
6
|
+
|
|
7
|
+
## Author a feature
|
|
8
|
+
|
|
9
|
+
A feature folder contains `schema.ts` (default schema export, optional) and
|
|
10
|
+
TypeScript modules exporting query, mutation or action definitions. Bind builders to the
|
|
11
|
+
schema for table, document and filter types:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
// schema.ts
|
|
15
|
+
import { defineSchema, defineTable, v } from "@tokamaq/sdk";
|
|
16
|
+
export default defineSchema({
|
|
17
|
+
notes: defineTable({ text: v.string(), done: v.boolean() }),
|
|
18
|
+
});
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
// notes.ts
|
|
23
|
+
import { createFunctions, v } from "@tokamaq/sdk";
|
|
24
|
+
import schema from "./schema";
|
|
25
|
+
const { query, mutation } = createFunctions(schema);
|
|
26
|
+
|
|
27
|
+
export const list = query({
|
|
28
|
+
args: { done: v.boolean() },
|
|
29
|
+
handler: (ctx, { done }) => ctx.db.query("notes").where("done", "=", done).order("desc").collect(),
|
|
30
|
+
});
|
|
31
|
+
export const add = mutation({
|
|
32
|
+
args: { text: v.string() },
|
|
33
|
+
handler: (ctx, { text }) => ctx.db.insert("notes", { text, done: false }),
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Direct `query` and `mutation` exports also work without schema-bound table
|
|
38
|
+
checking. Validators infer handler/client argument types; arguments default to
|
|
39
|
+
an empty, strict object. `v` supports string, finite number, boolean, null,
|
|
40
|
+
literal, id, file, array, object, optional object fields, union, and any JSON value.
|
|
41
|
+
Validation runs before the handler and names the failing argument path.
|
|
42
|
+
|
|
43
|
+
Queries have a read-only `ctx.db` at both the type and runtime levels. Mutations
|
|
44
|
+
also have `insert`, `patch`, `replace`, `delete`. Writes return IDs (insert) or
|
|
45
|
+
null (other writes). `get(id)` returns a document or null. Query builders are
|
|
46
|
+
immutable, use repeated `.where(field, '=', value)` for equality AND, order by
|
|
47
|
+
creation time with `.order('asc' | 'desc')` (default asc), and execute only with
|
|
48
|
+
`take(n)`, `first()` or `collect()`. There is no SQL expression, pagination,
|
|
49
|
+
or implicit thenable.
|
|
50
|
+
|
|
51
|
+
### Store files
|
|
52
|
+
|
|
53
|
+
Declare a top-level file field with `v.file({ accept?, maxSize? })`. It holds a
|
|
54
|
+
file ID string. `accept` is a list of MIME patterns (for example `image/*` or
|
|
55
|
+
`application/pdf`); omit it to accept any type. `maxSize` defaults to
|
|
56
|
+
100,000,000 bytes.
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
const schema = defineSchema({
|
|
60
|
+
attachments: defineTable({ name: v.string(), file: v.file({ accept: ["image/*"] }) }),
|
|
61
|
+
});
|
|
62
|
+
const { mutation } = createFunctions(schema);
|
|
63
|
+
export const openAvatarUpload = mutation({
|
|
64
|
+
handler: (ctx) => ctx.storage.upload("attachments.file", { path: "avatars/kira.png", name: "kira.png" }),
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
In window code, use `sendFile` from `@tokamaq/sdk/client` to send a `File` or
|
|
69
|
+
`Blob`. It resolves the relative upload URL against the connected server.
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { sendFile } from "@tokamaq/sdk/client";
|
|
73
|
+
|
|
74
|
+
const { url } = await api.attachments.openUpload({ name: file.name });
|
|
75
|
+
const { id } = await sendFile(url, file, { onProgress: (sent, total) => {}, signal });
|
|
76
|
+
await api.attachments.add({ name: file.name, file: id });
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The helper sends files up to 8 MiB in one request and splits larger files into
|
|
80
|
+
parts. If the connection drops or the server returns a 5xx, it waits and asks
|
|
81
|
+
the server how much it received before retrying, with up to five attempts per
|
|
82
|
+
part. A 409 triggers one offset check per part. Progress counts bytes the server
|
|
83
|
+
has confirmed, and aborting the signal stops the upload and rejects the promise.
|
|
84
|
+
Other HTTP errors reject with an `UploadHttpError` carrying `status` and any
|
|
85
|
+
message the server returned, for example 413 for size, 415 for type, or 410 for
|
|
86
|
+
an expired upload. If the server finishes the file but its final response is
|
|
87
|
+
lost, the upload URL can no longer recover the ID; open a new upload to retry.
|
|
88
|
+
|
|
89
|
+
Pass `name: file.name` when opening the upload to preserve names with non-ASCII
|
|
90
|
+
characters. The server uses that name before the encoded fallback header.
|
|
91
|
+
|
|
92
|
+
Rows store IDs, never URLs. Insert, patch and replace refuse a missing file
|
|
93
|
+
or one uploaded for a different field. A file's bytes never change. Anyone
|
|
94
|
+
with the download link can read the file.
|
|
95
|
+
|
|
96
|
+
| Call | Where | Result |
|
|
97
|
+
| ----------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------- |
|
|
98
|
+
| `upload("table.field", { path?, name? })` | Mutation, action | `{ url }` with a short-lived upload path |
|
|
99
|
+
| `get(id)`, `byPath(path)` | Query, mutation, action | File record or `null` |
|
|
100
|
+
| `list({ prefix? })` | Query, mutation, action | Files in path order, with unnamed files last when no prefix is supplied |
|
|
101
|
+
| `url(id)` | Query, mutation, action | Download link or `null` |
|
|
102
|
+
| `delete(id)` | Mutation | Removes the file when the mutation commits |
|
|
103
|
+
| `bytes(id)`, `text(id)` | Action | `Uint8Array` or UTF-8 string |
|
|
104
|
+
| `store(data, "table.field", { path?, name?, type? })` | Action | Stores a `Uint8Array` or string and returns its file ID |
|
|
105
|
+
|
|
106
|
+
Here, action means a server action or HTTP action. An action running on a
|
|
107
|
+
Runner cannot use these content methods. `store` applies the field's size and
|
|
108
|
+
type rules and refuses a path already taken by the plugin. It uses the
|
|
109
|
+
declared `type` when it cannot identify the type from the bytes. `text` and
|
|
110
|
+
`bytes` fail if the file does not exist in the calling plugin. All three
|
|
111
|
+
content methods have a 32 MiB limit. Use the upload URL and download link for
|
|
112
|
+
bigger files.
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
const id = await ctx.storage.store("month,total\n2026-11,42", "reports.file", {
|
|
116
|
+
path: "reports/2026-11.csv",
|
|
117
|
+
name: "2026-11.csv",
|
|
118
|
+
type: "text/csv",
|
|
119
|
+
});
|
|
120
|
+
const text = await ctx.storage.text(id);
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
A file record has `id`, `size`, `type`, `name`, `path`, `sha256`, `field`, and
|
|
124
|
+
`createdAt`. Both `name` and `path` may be `null`. Reads see only the calling
|
|
125
|
+
plugin's files, and subscribed queries update when their files change.
|
|
126
|
+
The download link uses the public server origin when known, otherwise it starts
|
|
127
|
+
with `/storage/files/`. The upload URL always starts with `/storage/uploads/`.
|
|
128
|
+
|
|
129
|
+
### Indexes
|
|
130
|
+
|
|
131
|
+
Declare indexes on tables before loading the plugin:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
const schema = defineSchema({
|
|
135
|
+
notes: defineTable({ owner: v.string(), text: v.string(), created: v.number() })
|
|
136
|
+
.index("by_owner_created", ["owner", "created"])
|
|
137
|
+
.unique("by_owner_text", ["owner", "text"]),
|
|
138
|
+
});
|
|
139
|
+
const { query } = createFunctions(schema);
|
|
140
|
+
const recent = query({
|
|
141
|
+
args: { owner: v.string(), since: v.number() },
|
|
142
|
+
handler: (ctx, { owner, since }) =>
|
|
143
|
+
ctx.db
|
|
144
|
+
.query("notes")
|
|
145
|
+
.withIndex("by_owner_created", (q) => q.eq("owner", owner).gt("created", since))
|
|
146
|
+
.order("desc")
|
|
147
|
+
.take(20),
|
|
148
|
+
});
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Index names and indexed fields must match `[A-Za-z_][A-Za-z0-9_]*`. Fields must
|
|
152
|
+
be declared top-level fields, nonempty and distinct; names are unique per table.
|
|
153
|
+
Table builders are immutable, so keep the returned value when adding an index.
|
|
154
|
+
Schema-bound queries check index names, field order and value types in TypeScript
|
|
155
|
+
and validate the range builder at runtime. Equalities consume leading index
|
|
156
|
+
fields in order. A range constrains the next field and ends the equality chain;
|
|
157
|
+
it may have one lower (`gt`/`gte`) and one upper (`lt`/`lte`) bound on that same
|
|
158
|
+
field. The callback can be omitted to scan the entire index. Indexed queries
|
|
159
|
+
cannot combine with `where`. Ordering follows index fields then ID; the default
|
|
160
|
+
is ascending. Indexed scans have the native `u32::MAX` row ceiling. Live indexed
|
|
161
|
+
queries conservatively invalidate whenever their table changes.
|
|
162
|
+
|
|
163
|
+
The loader installs ordinary and unique indexes in the plugin's data space.
|
|
164
|
+
Unique violations reject the host operation with the index name and abort the
|
|
165
|
+
invocation even if caught in JS. Reloading identical definitions is a no-op.
|
|
166
|
+
The server fills new and changed indexes from existing rows and removes indexes
|
|
167
|
+
that are no longer declared. Rows are preserved. If existing rows violate a new
|
|
168
|
+
unique index, the server reports the index and conflicting value. A failed reload keeps
|
|
169
|
+
the old version installed. At startup the server skips the affected plugin and
|
|
170
|
+
plugins that require it.
|
|
171
|
+
|
|
172
|
+
Limits, checked at declaration and again by the server at load: 256 tables per
|
|
173
|
+
plugin, 32 indexes per table, 16 fields per index, 64 characters per table or
|
|
174
|
+
index name.
|
|
175
|
+
General field descriptions provide types and metadata. Typed refs are checked
|
|
176
|
+
on persisted writes; general field validation and schema migrations remain deferred.
|
|
177
|
+
|
|
178
|
+
## Actions
|
|
179
|
+
|
|
180
|
+
`action({...})` (also returned by `createFunctions`) runs separately from
|
|
181
|
+
queries and mutations. See [Plugin process and action process](#plugin-process-and-action-process)
|
|
182
|
+
for action process budgets. Actions keep the real clock and randomness. They
|
|
183
|
+
have no `ctx.db`: each `ctx.runQuery` or `ctx.runMutation`
|
|
184
|
+
call rejoins the serialized coordinator and owns its own transaction. The action
|
|
185
|
+
itself is never retried; external effects and earlier mutations remain after a
|
|
186
|
+
later failure. Queries and mutations cannot call actions or fetch.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import type {} from "@tokamaq/sdk/web";
|
|
190
|
+
import { action } from "@tokamaq/sdk";
|
|
191
|
+
import { api } from "./_generated/api";
|
|
192
|
+
|
|
193
|
+
export const sync = action({
|
|
194
|
+
handler: async (ctx) => {
|
|
195
|
+
const response = await fetch("https://example.com/data");
|
|
196
|
+
if (!response.ok) throw new Error(`Upstream returned ${response.status}`);
|
|
197
|
+
return ctx.runMutation(api.records.save, { value: await response.json() });
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
// From a client: await client.action(api.jobs.sync, {});
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Declare `permissions: ['net:example.com']` in the plugin definition. Grants use
|
|
204
|
+
the canonical URL hostname, omit the port, and are checked on every request and
|
|
205
|
+
redirect. Legacy bundles receive no network grants. Nested cross-plugin calls
|
|
206
|
+
check declared dependencies and exports. Reload cancels old-generation actions, and explicit
|
|
207
|
+
server shutdown cancels busy JS, pending timers and HTTP I/O. Disconnect alone
|
|
208
|
+
does not retract an accepted action; its outcome can be unknown.
|
|
209
|
+
|
|
210
|
+
The optional **type-only** `@tokamaq/sdk/web` entry supplies standard web
|
|
211
|
+
authoring declarations for action code and browser-targeted dependencies. It
|
|
212
|
+
installs no globals and does not alter the SDK's ES2022-only source checker.
|
|
213
|
+
Only the runtime subset in [WEB_APIS.md](../engine/WEB_APIS.md) is implemented.
|
|
214
|
+
The AI SDK's published declarations additionally reference Node HTTP/Buffer and
|
|
215
|
+
JSON Schema types: consumers can install `@types/node` and `@types/json-schema`
|
|
216
|
+
as build-only dependencies, with a type-reference to Node declarations. These
|
|
217
|
+
types do not add a Node runtime; bundle with the browser target.
|
|
218
|
+
|
|
219
|
+
Generated `api.*` references infer the action kind and argument/result types.
|
|
220
|
+
Both bundled transports implement the `action` wire request. The optional
|
|
221
|
+
`ClientTransport.action` preserves existing custom transports; `client.action`
|
|
222
|
+
throws clearly when a custom transport has not implemented it.
|
|
223
|
+
|
|
224
|
+
### Choose where an action runs
|
|
225
|
+
|
|
226
|
+
An action without an `on` setting runs beside the server in its action process.
|
|
227
|
+
Set `on: "caller"` to run it in the caller's desktop Runner. It can use
|
|
228
|
+
`ctx.proc`, Runner Node modules such as `node:fs/promises` and `node:path`,
|
|
229
|
+
and the program scopes and cancellation controls below.
|
|
230
|
+
The Runner needs the matching plugin build installed. Use a literal
|
|
231
|
+
`on: "caller"` or `on: "server"` in a definition so the builder can place its
|
|
232
|
+
imports. Queries and mutations still run on the workspace server.
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
import { action, isFailure, v } from "@tokamaq/sdk";
|
|
236
|
+
import { api } from "./_generated/api";
|
|
237
|
+
|
|
238
|
+
export const collect = action({
|
|
239
|
+
on: "caller",
|
|
240
|
+
args: { cwd: v.string() },
|
|
241
|
+
handler: async (ctx, { cwd }) => {
|
|
242
|
+
const git = ctx.proc(["git", "status", "--short"], { cwd });
|
|
243
|
+
for await (const text of git.stdout) await ctx.runMutation(api.records.save, { text });
|
|
244
|
+
return await git.exited;
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
// From a window connected to a Runner:
|
|
249
|
+
const result = await client.action(api.jobs.collect, { cwd });
|
|
250
|
+
if (isFailure(result) && result.kind === "noMachine") {
|
|
251
|
+
// Show "Connect a machine to run this".
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
Pass `{ on: "server" }` or `{ on: "caller" }` to `client.action` or
|
|
256
|
+
`ctx.runAction` to choose the destination for that call. Pass `{ signal }` to
|
|
257
|
+
`client.action` to cancel an action running on the desktop Runner. The
|
|
258
|
+
action receives the original identity and call note.
|
|
259
|
+
|
|
260
|
+
The workspace server chooses the destination. A direct client authenticated
|
|
261
|
+
as a person on an embedded Runner's machine uses that Runner, including for
|
|
262
|
+
nested actions. A [Runner connected to a shared server](../runner/README.md#connect-a-headless-runner-to-a-shared-server)
|
|
263
|
+
receives `"caller"` actions for the exact device in the original call note,
|
|
264
|
+
including nested actions from that device. The desktop app automatically
|
|
265
|
+
connects its Runner using the window's device key on the active
|
|
266
|
+
joined server. Caller actions wait briefly for the Runner to register before
|
|
267
|
+
asking the user to retry, while server actions can proceed. A desktop without
|
|
268
|
+
automatic attachment can still forward work to its local Runner through the
|
|
269
|
+
public-only window route. A browser without a Runner for its device gets
|
|
270
|
+
`noMachine`.
|
|
271
|
+
|
|
272
|
+
Install the full Runner build of each served plugin in the remote Runner's
|
|
273
|
+
`--plugins` directory after every update. Missing or mismatched builds return
|
|
274
|
+
`runnerArtifactMismatch`; automatic delivery is separate work. In a caller
|
|
275
|
+
action on a connected Runner, `ctx.env` comes from the Runner's environment.
|
|
276
|
+
|
|
277
|
+
#### Run actions on a sandbox machine
|
|
278
|
+
|
|
279
|
+
The machine management API is available under `@tokamaq/sdk/unstable` and may
|
|
280
|
+
change.
|
|
281
|
+
|
|
282
|
+
Connect a sandbox Runner using
|
|
283
|
+
[`--server` and `--key-file`](../runner/README.md#connect-a-headless-runner-to-a-shared-server).
|
|
284
|
+
Target a known machine id when calling an action:
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
// Inside a server action:
|
|
288
|
+
await ctx.runAction(api.jobs.collect, { cwd }, { on: machineId });
|
|
289
|
+
// From the owning plugin's window:
|
|
290
|
+
await client.action(api.jobs.collect, { cwd }, { on: machineId });
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Set `TOKAMAQ_PUBLIC_URL` on the server to its reachable HTTP(S) origin, for
|
|
294
|
+
example `https://workspace.example.com`. `ctx.server.url()` returns `null` if
|
|
295
|
+
it is unset. Use HTTPS for a Runner outside loopback.
|
|
296
|
+
|
|
297
|
+
`MachineId` is a branded string. Supply a machine id in per-call options for
|
|
298
|
+
dynamic placement. For a fixed default in an action declaration, use a
|
|
299
|
+
literal such as `on: "device:example" as MachineId`
|
|
300
|
+
with an actual issued id. The action has the Runner capabilities described
|
|
301
|
+
above. The original caller and call note reach the action, including the
|
|
302
|
+
thread, and queries and mutations still execute on the server.
|
|
303
|
+
|
|
304
|
+
Only actions owned by a machine's plugin may run on it. A machine bound to
|
|
305
|
+
a member accepts only calls whose original call note identifies that member.
|
|
306
|
+
For thread turns, read the saved machine id and pass it as `{ on: id }`.
|
|
307
|
+
A person's device is available only to calls started by that person.
|
|
308
|
+
|
|
309
|
+
Only the owning plugin's server code can dispatch its own actions to an
|
|
310
|
+
unbound machine using `ctx.runAction`. If a server action accepts a machine id
|
|
311
|
+
from a window, check `ctx.auth` and the plugin's records before passing it through.
|
|
312
|
+
|
|
313
|
+
Unknown, removed and unauthorized ids all return `machineForbidden`.
|
|
314
|
+
An authorized machine without a Runner returns `machineOffline` immediately.
|
|
315
|
+
If its Runner disconnects or its key is removed during an action, that action
|
|
316
|
+
returns `machineLost`. Calls are never queued or replayed.
|
|
317
|
+
|
|
318
|
+
Machine management can also return `machineLimit` when the plugin already has
|
|
319
|
+
100 active machines, `machineForbidden` for an unauthorized machine or for a
|
|
320
|
+
machine bound to a member who cannot be found, and `machineOffline` if waiting
|
|
321
|
+
for a connection times out. Uninstalling a plugin revokes its machine keys.
|
|
322
|
+
|
|
323
|
+
A per-call override can move a server action to a Runner, where machine
|
|
324
|
+
management and `ctx.server.url()` fail with the typed `serverOnly` error.
|
|
325
|
+
|
|
326
|
+
`ctx.proc` starts an executable directly. Its `stdout` and `stderr` yield
|
|
327
|
+
one line at a time. Use `write` and `closeInput` for stdin and `stop` to send
|
|
328
|
+
a signal. The invocation stays alive until the handler settles. To cancel
|
|
329
|
+
from the window, pass `{ signal }` to `client.action`; the plugin process stops programs
|
|
330
|
+
still running for that invocation. Use `node:fs/promises` for local files.
|
|
331
|
+
|
|
332
|
+
**Await the programs you need finished before returning.** Any
|
|
333
|
+
call (including a routed contract method) can return while its unawaited
|
|
334
|
+
programs are still being reaped. These programs still count toward the host's
|
|
335
|
+
256-program limit. On macOS and Linux, normal cleanup sends TERM and gives a
|
|
336
|
+
live process group up to two seconds before sending KILL. On Windows, cleanup
|
|
337
|
+
closes the program's job and stops its process tree immediately.
|
|
338
|
+
|
|
339
|
+
Use `ctx.withPrograms(async (forceStop, scoped) => { … })` to group programs
|
|
340
|
+
started through `scoped.proc` and providers selected with `scoped`. Calling
|
|
341
|
+
`forceStop()` ends those process trees without cancelling the invocation
|
|
342
|
+
or its other programs. `withPrograms` can return while the scope
|
|
343
|
+
is still being reaped. On macOS and Linux, force stop sends KILL immediately,
|
|
344
|
+
including to groups already in their TERM grace. Use `contract.list(ctx)` or `contract.get(id, ctx)` in
|
|
345
|
+
actions so the lookup follows the caller across awaits.
|
|
346
|
+
Queries and mutations still use `contract.list()` and `contract.get(id)`.
|
|
347
|
+
|
|
348
|
+
Caller actions have no database context. Use `ctx.runQuery`,
|
|
349
|
+
`ctx.runMutation`, or `ctx.runAction` to call the connected server. Use public
|
|
350
|
+
`api` references when the window forwards calls to the Runner.
|
|
351
|
+
|
|
352
|
+
Declare a Runner contract with `contract<T>("name", { on: "caller" })`.
|
|
353
|
+
Providers can implement its methods with `action({ on: "caller", handler })`. Methods run inside the Runner with live input, including
|
|
354
|
+
callbacks, signals, and channels.
|
|
355
|
+
|
|
356
|
+
All Runner routes support local contracts and their channels. When the
|
|
357
|
+
window forwards work, it uses the public client API, so private function
|
|
358
|
+
calls and server contract discovery return `runnerCapabilityUnavailable`
|
|
359
|
+
with `data` set to `"privateFunctions"` or `"serverContracts"`. Those operations
|
|
360
|
+
are available to embedded and connected Runners. The window route cannot
|
|
361
|
+
invoke private functions or server contracts from a caller action.
|
|
362
|
+
On a joined desktop server, the connected Runner is what gives caller actions
|
|
363
|
+
and their hook stages access to these operations.
|
|
364
|
+
|
|
365
|
+
Runner actions use the Runner's program scope and lifetime rules, including
|
|
366
|
+
no fixed deadline while the build is current. When the build is retired, the
|
|
367
|
+
action has five seconds to settle. If it is still running, the Runner cancels
|
|
368
|
+
it and `client.action` rejects. Use `isLocalReloadTimeout(error)` from
|
|
369
|
+
`@tokamaq/sdk` to detect this on either Runner route.
|
|
370
|
+
|
|
371
|
+
A Runner action resolves `ctx.env` grants from its installation on that machine.
|
|
372
|
+
A call returns the typed failure `{ failed: true, kind: "noMachine", data: null }` when it needs a Runner
|
|
373
|
+
and has none, or when it requests a file or program from the server action
|
|
374
|
+
process. This includes calls to stubbed modules such as `node:path`,
|
|
375
|
+
`node:os`, `node:crypto`, `node:url`, and `node:fs/promises`. Use their
|
|
376
|
+
bindings inside the handler so the server bundle can load independently.
|
|
377
|
+
|
|
378
|
+
## HTTP actions
|
|
379
|
+
|
|
380
|
+
Export an `httpAction` from the plugin's server part to answer requests from
|
|
381
|
+
programs outside Tokamaq. Its path is relative to `/plugins/<plugin-id>`.
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
import type {} from "@tokamaq/sdk/web";
|
|
385
|
+
import { httpAction } from "@tokamaq/sdk";
|
|
386
|
+
|
|
387
|
+
export const proxy = httpAction({
|
|
388
|
+
path: "/:profile/*",
|
|
389
|
+
handler: async (ctx, request) => {
|
|
390
|
+
if (!checkKey(request.headers.get("x-api-key"))) {
|
|
391
|
+
return new Response(null, { status: 401 });
|
|
392
|
+
}
|
|
393
|
+
const target = upstreamUrl(ctx.params.profile, ctx.params["*"]);
|
|
394
|
+
return fetch(target, { signal: request.signal });
|
|
395
|
+
},
|
|
396
|
+
});
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
For example, `POST /plugins/my-proxy/ACME/v1/messages?format=sse` sets
|
|
400
|
+
`ctx.path` to `/ACME/v1/messages`, with `ctx.params.profile` equal to `ACME`
|
|
401
|
+
and `ctx.params["*"]` equal to `v1/messages`. Use a literal path; `:name`
|
|
402
|
+
captures one segment and a final `*` captures the remainder. Literal segments
|
|
403
|
+
take precedence over parameters, and parameters over the wildcard.
|
|
404
|
+
The core routes `/plugins/<id>/<revision>/assets/<name...>` and
|
|
405
|
+
`/plugins/<id>/reload` take precedence over HTTP actions. Dot segments,
|
|
406
|
+
including percent-encoded dots, and encoded slash or backslash are rejected.
|
|
407
|
+
There is no member sign-in: check the caller in the handler before doing work.
|
|
408
|
+
Functions called through the handler receive no member or device. A function
|
|
409
|
+
that requires a signed-in member refuses the call as it would any anonymous call.
|
|
410
|
+
`OPTIONS` reaches the handler; the plugin is responsible for CORS answers.
|
|
411
|
+
|
|
412
|
+
`ctx.serverUrl` is the bound loopback origin in the Runner. Set
|
|
413
|
+
`TOKAMAQ_PUBLIC_URL` to the CLI-reachable origin in the Server. If it is unset,
|
|
414
|
+
the Server logs a startup warning and reading `ctx.serverUrl` throws.
|
|
415
|
+
The request's Host header is never used to derive the origin.
|
|
416
|
+
|
|
417
|
+
Use `ctx.runQuery(ref, args)`, `ctx.runMutation(ref, args)`, and
|
|
418
|
+
`ctx.runAction(ref, args)` with the same typed references as a server action.
|
|
419
|
+
The handler can call its own plugin's `_generated/api`, `_generated/internal`,
|
|
420
|
+
and `_generated/plugin` functions. Each call starts at depth zero; calls made
|
|
421
|
+
from those functions increase depth as usual. The handler has no `ctx.db`;
|
|
422
|
+
each query or mutation runs in its own transaction. `ctx.runAction` accepts the
|
|
423
|
+
usual optional placement argument. A placement that needs the member's
|
|
424
|
+
Runner returns `noMachine` because the request has no member.
|
|
425
|
+
|
|
426
|
+
Use `await ctx.env("NAME")` to read a value from the server environment or the
|
|
427
|
+
installation's `.env.local`. Declare `env:NAME` in the plugin's permissions.
|
|
428
|
+
An unset value returns `null`; an undeclared name rejects.
|
|
429
|
+
|
|
430
|
+
The `Request` provides the method, URL (including query), headers and body
|
|
431
|
+
using the same [web API subset](../engine/WEB_APIS.md) as `fetch`. Uploads are
|
|
432
|
+
buffered up to 32 MiB and must finish within 30 seconds. The server gives
|
|
433
|
+
request headers 10 seconds. It removes Host, Content-Length and hop-by-hop
|
|
434
|
+
headers before handing the request to the plugin. The original Host is
|
|
435
|
+
available as `ctx.originalHost` and is untrusted. Duplicate headers are joined
|
|
436
|
+
by the web Headers implementation; the server drops response `Set-Cookie`.
|
|
437
|
+
|
|
438
|
+
Outbound requests require the usual `net:<hostname>` permission. Each
|
|
439
|
+
outbound `fetch` from a fresh host performs its own DNS lookup and, for HTTPS,
|
|
440
|
+
TLS handshake. Return the upstream `Response` directly to stream its body
|
|
441
|
+
with backpressure.
|
|
442
|
+
|
|
443
|
+
HTTP actions run in a separate plugin host process per request on macOS and
|
|
444
|
+
Linux. `TOKAMAQ_HTTP_PLUGIN_SLOTS` (default 32) and
|
|
445
|
+
`TOKAMAQ_HTTP_TOTAL_SLOTS` (default 96) cap concurrent hosts. After reading the
|
|
446
|
+
upload, the server waits up to 250 ms for a slot and replies with
|
|
447
|
+
`503 Retry-After: 1` if none becomes available. The time to response headers
|
|
448
|
+
is bounded by `TOKAMAQ_HTTP_FIRST_HEADERS_MS` (default 300000); the normal action
|
|
449
|
+
wall deadline does not apply to the response stream. On disconnect or server
|
|
450
|
+
shutdown, the host aborts `request.signal` and has up to 500 ms for cleanup
|
|
451
|
+
before it is killed. A disconnect does not roll back a mutation that already
|
|
452
|
+
started. The HTTP route itself has no generated function reference and cannot
|
|
453
|
+
be hooked, exported to windows, or provided as a contract method.
|
|
454
|
+
|
|
455
|
+
## Internal functions and expected failures
|
|
456
|
+
|
|
457
|
+
Use `internalQuery`, `internalMutation` or `internalAction` for a function only
|
|
458
|
+
your plugin's server code can call. The same builders are available from
|
|
459
|
+
`createFunctions(schema)`. Import its reference from `_generated/internal`.
|
|
460
|
+
Queries can run nested queries; mutations can run nested queries and mutations
|
|
461
|
+
within the same transaction. Actions can also call `ctx.runAction`.
|
|
462
|
+
|
|
463
|
+
```ts
|
|
464
|
+
import { action, fail, internalQuery, v } from "@tokamaq/sdk";
|
|
465
|
+
import { internal } from "./_generated/internal";
|
|
466
|
+
|
|
467
|
+
export const checkTitle = internalQuery({
|
|
468
|
+
args: { title: v.string() },
|
|
469
|
+
handler: (_, { title }) => (title.length > 200 ? fail("TooLong", { max: 200 }) : { title }),
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
export const previewTitle = action({
|
|
473
|
+
args: { title: v.string() },
|
|
474
|
+
handler: (ctx, args) => ctx.runQuery(internal.titles.checkTitle, args),
|
|
475
|
+
});
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
The action's caller receives the inferred result. For an object success like
|
|
479
|
+
`{ title }`, `if (result.failed && result.kind === "TooLong")` narrows to the
|
|
480
|
+
failure and makes `result.data.max` a number. Use `isFailure(result)` from
|
|
481
|
+
`@tokamaq/sdk` to distinguish failures from any success, including a string or
|
|
482
|
+
`null`. A mutation that returns `fail` rolls back its writes and still returns
|
|
483
|
+
the typed failure. If a nested `ctx.runMutation` returns `fail`, only that
|
|
484
|
+
callee's writes roll back. The caller can handle it and commit its own writes,
|
|
485
|
+
or return the failure to roll back the caller's writes too. Actions are not
|
|
486
|
+
transactional: returning `fail` from an action does not undo mutations it
|
|
487
|
+
already called. Throw for unexpected errors.
|
|
488
|
+
|
|
489
|
+
## Build and consume typed references
|
|
490
|
+
|
|
491
|
+
From the workspace, with a feature folder path relative to the workspace root:
|
|
492
|
+
|
|
493
|
+
```sh
|
|
494
|
+
moon run sdk:check
|
|
495
|
+
moon run sdk:build
|
|
496
|
+
moon run sdk:bundle -- packages/server/demo/feature
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
The bundle task writes:
|
|
500
|
+
|
|
501
|
+
- `FEATURE/dist/bundle.js`: one self-contained ESM module.
|
|
502
|
+
- `FEATURE/dist/bundle.js.map`: linked source map with source contents.
|
|
503
|
+
- `FEATURE/dist/transactions.js` and its map: the companion for the QuickJS action process.
|
|
504
|
+
It contains queries, mutations and inspection metadata.
|
|
505
|
+
- `FEATURE/_generated/api.ts`: typed public references.
|
|
506
|
+
- `FEATURE/_generated/internal.ts`: references for the plugin's server code.
|
|
507
|
+
|
|
508
|
+
Discovery includes `.ts` modules recursively, excluding `schema.ts`, declarations,
|
|
509
|
+
`.test.ts`/`.spec.ts`, `tests/`, `dist/`, `node_modules/` and paths beginning with
|
|
510
|
+
`_` or `.`. Imported helpers in excluded folders still bundle normally; they are
|
|
511
|
+
not independent function modules. Use a backend-only feature folder. Module
|
|
512
|
+
path collisions (`a.ts` with `a/b.ts`) fail rather than produce ambiguous APIs.
|
|
513
|
+
Generated references need feature source types available to the type checker;
|
|
514
|
+
they do not import server code at runtime. Commit both files and regenerate
|
|
515
|
+
them when functions change.
|
|
516
|
+
|
|
517
|
+
The bundle checker inherits the feature's resolution options unchanged, including
|
|
518
|
+
`paths` aliases inherited from another config (relative to the declaring config).
|
|
519
|
+
With the default workspace config, use extensionless TypeScript imports such as
|
|
520
|
+
`./schema`, not `./schema.ts`; the bundle task does not add a build-only
|
|
521
|
+
`allowImportingTsExtensions` opt-in. If a feature explicitly opts in or uses
|
|
522
|
+
aliases, consumers of its generated API must share those compiler settings,
|
|
523
|
+
because checking the references also checks the backend source types.
|
|
524
|
+
|
|
525
|
+
```ts
|
|
526
|
+
import { TokamaqClient } from "@tokamaq/sdk";
|
|
527
|
+
import { api } from "./_generated/api";
|
|
528
|
+
const client = new TokamaqClient(transport); // see concrete transports below
|
|
529
|
+
const rows = await client.query(api.notes.list, { done: false });
|
|
530
|
+
const id = await client.mutation(api.notes.add, { text: "Read this" });
|
|
531
|
+
const stop = client.subscribe(api.notes.list, { done: false }, (event) => {
|
|
532
|
+
// event is { value: typeof rows } | { error: Error }
|
|
533
|
+
});
|
|
534
|
+
stop();
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
`ClientTransport` owns connections, initial subscription delivery, ordering and
|
|
538
|
+
errors. The SDK snapshots arguments, checks JSON values, preserves inferred
|
|
539
|
+
argument/result types, and suppresses events after an idempotent unsubscribe.
|
|
540
|
+
An observer throwing during synchronous initial delivery deactivates the listener;
|
|
541
|
+
the SDK captures and calls the transport disposer before rethrowing that error.
|
|
542
|
+
If the transport's registration itself throws, the transport owns cleanup because
|
|
543
|
+
it has not returned a disposer. There is no reconnect/retry.
|
|
544
|
+
|
|
545
|
+
### Concrete transports (TKM-7)
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
import { TokamaqClient, InProcessTransport, WebSocketTransport } from "@tokamaq/sdk";
|
|
549
|
+
// Native host owns a server Session and implements MessageConnection: send a
|
|
550
|
+
// generated Request through Tower, feed its ordered Event stream to listen,
|
|
551
|
+
// and drop Session when close/dispose runs. No port is opened.
|
|
552
|
+
const embedded = new TokamaqClient(new InProcessTransport(nativeConnection));
|
|
553
|
+
// Browser/Bun caller creates and awaits OPEN on a WebSocket itself. The SDK
|
|
554
|
+
// receives this structural capability rather than importing environment globals.
|
|
555
|
+
const remoteTransport = new WebSocketTransport(openSocket);
|
|
556
|
+
const remote = new TokamaqClient(remoteTransport);
|
|
557
|
+
// All query/mutation/subscribe application code is identical for embedded/remote.
|
|
558
|
+
remoteTransport.close();
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
`Request` and `Event` are generated from `packages/server/src/protocol.rs` with `ts-rs`;
|
|
562
|
+
never edit `src/protocol.ts` manually. Regenerate/check from workspace root:
|
|
563
|
+
|
|
564
|
+
```sh
|
|
565
|
+
cargo run --locked -p server --features protocol-codegen --bin export-protocol
|
|
566
|
+
cargo run --locked -p server --features protocol-codegen --bin export-protocol -- --check
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
The WebSocket route is `/ws` on the headless runner's **loopback** listen address.
|
|
570
|
+
It preserves one stream for updates and call replies. Outstanding calls and
|
|
571
|
+
subscriptions are bounded at 128 each; safe-integer IDs are never reused.
|
|
572
|
+
Protocol/frame/admission/queue failures close the connection, reject all calls,
|
|
573
|
+
and report errors to subscriptions. A closed stream can hide a committed
|
|
574
|
+
mutation: never automatically retry it. Unsubscribe is idempotent; late events
|
|
575
|
+
are ignored. A throwing async observer is isolated so it cannot strand the
|
|
576
|
+
mutation reply behind its update; observers should handle their own failures.
|
|
577
|
+
There is no socket-open buffering, auth, TLS, reconnect or multiuser support.
|
|
578
|
+
Do not expose the POC publicly. See `packages/server/demo` for the two-client live demo.
|
|
579
|
+
|
|
580
|
+
## Native host integration contract
|
|
581
|
+
|
|
582
|
+
`packages/sdk/src/host.ts` is the single source for operation names and argument/result
|
|
583
|
+
shapes (`HostOperations`). Runtime serialization happens at the native boundary,
|
|
584
|
+
not through a second JSON-string envelope. The bundle exports:
|
|
585
|
+
|
|
586
|
+
- `schema`: the schema definition, or null when there is no `schema.ts`.
|
|
587
|
+
- `functions`: a registry keyed by `module/path:export`. Definitions expose
|
|
588
|
+
`kind`, serializable `args`, and a validated `invoke`; handlers remain closed
|
|
589
|
+
over, with no unchecked public handler entry point.
|
|
590
|
+
- `metadata`: `{ name, kind, args }[]`, inspectable without a host. `args` is a
|
|
591
|
+
`ValidatorDescription`; reading metadata does not execute handlers.
|
|
592
|
+
- `invoke({ name, args }, host) -> Promise<JsonValue>`: dispatches through the
|
|
593
|
+
same argument validator for every function. Unknown names reject. A void
|
|
594
|
+
handler result becomes null, including async void; all other results must be
|
|
595
|
+
JSON values. Errors reject rather than pretending to be successful data.
|
|
596
|
+
|
|
597
|
+
`host.op(name, payload)` accepts and returns plain JSON values, synchronously or
|
|
598
|
+
asynchronously. Bind this capability to one invocation: the native host owns
|
|
599
|
+
call lifetime, query read-only enforcement, transactions and commit/change
|
|
600
|
+
notifications. The SDK does not implement those host responsibilities.
|
|
601
|
+
|
|
602
|
+
### Record/value policy
|
|
603
|
+
|
|
604
|
+
- IDs are branded strings serialized as `table:key`. Table names match
|
|
605
|
+
`[A-Za-z][A-Za-z0-9_]*`; opaque keys match `[A-Za-z0-9_-]+`. This is deliberately
|
|
606
|
+
narrower than SurrealDB's full record-ID grammar; no SQL parser is in the SDK.
|
|
607
|
+
- Stored documents have host-owned `_id` and `_creationTime`, where the latter is
|
|
608
|
+
a finite number of milliseconds since the Unix epoch. Patch/replace preserve
|
|
609
|
+
both fields; authors cannot supply them in writes.
|
|
610
|
+
- Values are null, booleans, strings, finite numbers, dense arrays and plain
|
|
611
|
+
string-keyed objects. No Date, bigint, undefined, functions, symbols, accessors,
|
|
612
|
+
non-enumerable data or cycles. IDs used as fields are JSON strings, not an
|
|
613
|
+
implicit SurrealDB record-link codec. Optional means an absent object key.
|
|
614
|
+
- Patch shallow-merges supplied keys; replace replaces user fields. There is no
|
|
615
|
+
delete-field sentinel. Missing patch/replace is an error; missing get returns
|
|
616
|
+
null and missing delete succeeds with null.
|
|
617
|
+
- All equality conditions are ANDed. Equality is structural JSON equality with
|
|
618
|
+
object key order ignored. Fields are top-level literal names, not dotted paths
|
|
619
|
+
or expressions. Missing fields do not equal null. Ordering is by
|
|
620
|
+
`(_creationTime, _id)`, both in the requested direction; ID ties use lexical
|
|
621
|
+
ASCII ordering. `limit: null` means collect all; zero means no rows.
|
|
622
|
+
|
|
623
|
+
## Why these build tools
|
|
624
|
+
|
|
625
|
+
Verified with Firecrawl docs, opensrc source retrieval, npm metadata and local
|
|
626
|
+
Bun 1.4.4 probes (2026-11-06):
|
|
627
|
+
|
|
628
|
+
- [Bun.Transpiler.scan](https://bun.com/docs/runtime/transpiler#scan) parses
|
|
629
|
+
imports/exports without executing modules. Namespace registration plus mapped
|
|
630
|
+
TS types recognizes definitions, including aliases and reexports; no
|
|
631
|
+
hand-written parser or fragile initializer-pattern matching is needed.
|
|
632
|
+
- [Bun.build](https://bun.com/docs/bundler) provides ESM, one-file bundling,
|
|
633
|
+
linked source maps and plugins. `allowUnresolved: []` rejects even opaque
|
|
634
|
+
dynamic imports (verified against the pinned version's `bun-types/bun.d.ts`
|
|
635
|
+
and a failing local probe); the final output must also have no imports.
|
|
636
|
+
- [Bun's native checker](https://bun.com/docs/runtime/check) already ships in
|
|
637
|
+
1.4.4. No TypeScript/tsgo package is needed. `sdk:check` checks `src/` separately
|
|
638
|
+
against `lib: ES2022`, `types: []` before checking the package/tests. This stops
|
|
639
|
+
a future bun:test import from granting runtime code Bun/Node/browser globals.
|
|
640
|
+
The native checker's `--listFilesOnly` graph also guards type-only imports and
|
|
641
|
+
triple-slash references: dependencies must be inside `src/` or in the exact
|
|
642
|
+
ES2022 library set obtained from an isolated compiler invocation. Extra ambient
|
|
643
|
+
libraries (including DOM) and external declaration files are rejected.
|
|
644
|
+
- [Rolldown 1.3.0](https://rolldown.rs/guide/getting-started#using-the-api), released
|
|
645
|
+
2026-11-05: `rolldown({ input, platform: 'neutral' }).generate({ format: 'esm',
|
|
646
|
+
sourcemap: true, codeSplitting: false })` is a maintained alternative. npm
|
|
647
|
+
reports 981,872 unpacked bytes plus 18,524,990 bytes for the macOS arm64 binding.
|
|
648
|
+
- [oxc-parser 0.157.0](https://oxc.rs/docs/guide/usage/parser), released 2026-11-02:
|
|
649
|
+
`parseSync(filename, source)` exposes ESTree and ESM information; npm reports
|
|
650
|
+
2,964,029 unpacked bytes plus a 1,877,726-byte macOS arm64 binding. Both oxc and
|
|
651
|
+
Rolldown were retrieved through opensrc and inspected, but neither is needed
|
|
652
|
+
for this build pipeline. These are package sizes, not native application size.
|
|
653
|
+
- [Standard Schema 1.x](https://standardschema.dev/) was evaluated, not accepted:
|
|
654
|
+
its input/output transforms and async validation add a second argument-value
|
|
655
|
+
model outside the requested `v` POC. No adapter dependency is installed.
|
|
656
|
+
- Surlvex and Convex 1.49.0 informed the function/validator/reference patterns;
|
|
657
|
+
no implementation was copied. Their deployment, transport and extra function
|
|
658
|
+
APIs are intentionally absent here.
|
|
659
|
+
|
|
660
|
+
The SDK changes do not link JavaScript bundles into the native binary. Native
|
|
661
|
+
size measurements therefore measure the inherited host only; real QuickJS and
|
|
662
|
+
SurrealDB integration remains for the host issues and their tests.
|
|
663
|
+
|
|
664
|
+
## Plugin process and action process
|
|
665
|
+
|
|
666
|
+
On macOS, Linux and Windows, a plugin process runs caller actions.
|
|
667
|
+
The action process runs server actions in `tokamaq-plugin-host`. Queries and mutations run
|
|
668
|
+
in the server's engine.
|
|
669
|
+
|
|
670
|
+
A caller action can import `node:path`, `node:os`, `node:crypto`,
|
|
671
|
+
`node:url`, and `node:fs/promises`; an action sent to the server returns `noMachine` if it
|
|
672
|
+
uses that module. The build checks imports,
|
|
673
|
+
including bare names such as `path`. Unsupported imports such as `node:timers`,
|
|
674
|
+
`events`, or `node:path/posix` fail the build. Built-ins reached indirectly,
|
|
675
|
+
such as `process.getBuiltinModule`, `import.meta.require`, `process.binding`,
|
|
676
|
+
or `globalThis.Bun`, fail at runtime in QuickJS. Use `ctx.proc` in a caller
|
|
677
|
+
action to run a separate program when needed.
|
|
678
|
+
|
|
679
|
+
Caller actions get `process.platform` (`darwin`, `linux` or `win32`), an
|
|
680
|
+
empty `process.versions`, and a snapshot in `process.env`. Writing to that
|
|
681
|
+
object does not change the environment of later programs. Pass `env` to
|
|
682
|
+
`ctx.proc` instead. The local host supplies global timers and fetch. It caps
|
|
683
|
+
the heap at 256 MiB by default, allows up to 128 calls and 256 live programs,
|
|
684
|
+
and interrupts JavaScript that runs for five seconds without yielding. See the
|
|
685
|
+
[host reference](../host/README.md) for filesystem, timers, I/O, and memory limits.
|
|
686
|
+
|
|
687
|
+
Root local calls also get `ctx.retiring`. It aborts when the window
|
|
688
|
+
replaces the plugin's own build. The call can still use its context to settle
|
|
689
|
+
work until the old connection closes. Routed provider calls do not
|
|
690
|
+
receive this signal.
|
|
691
|
+
|
|
692
|
+
### Moving files from the local part
|
|
693
|
+
|
|
694
|
+
A caller action can move files between the Runner's disk and its plugin's
|
|
695
|
+
server storage. Both local paths must be absolute.
|
|
696
|
+
|
|
697
|
+
```ts
|
|
698
|
+
const id = await ctx.storage.uploadFile("/repo/.sync/pack-1.pack", "packs.file", {
|
|
699
|
+
path: "threads/t1/pack-1.pack",
|
|
700
|
+
});
|
|
701
|
+
await ctx.storage.downloadTo(id, "/repo/.sync/pack-1.pack");
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
`uploadFile` enforces the file field's rules and uses the local base name unless
|
|
705
|
+
you pass `name`. Both calls resume interrupted transfers with bounded retries.
|
|
706
|
+
`downloadTo` writes to a temporary file in the destination's existing folder.
|
|
707
|
+
It checks the byte count and SHA-256 against the server record, syncs the file
|
|
708
|
+
to disk, and atomically renames it. If it fails, it removes the temporary file
|
|
709
|
+
and leaves the destination unchanged.
|
|
710
|
+
|
|
711
|
+
The local part also has `ctx.storage.get`, `byPath`, `list`, `url`, and `upload`,
|
|
712
|
+
scoped to the calling plugin. `uploadFile` and `downloadTo` are available only
|
|
713
|
+
in caller actions.
|
|
714
|
+
|
|
715
|
+
### Server actions
|
|
716
|
+
|
|
717
|
+
All plugins’ server actions run in one action process. Every action call has its own
|
|
718
|
+
QuickJS runtime and starts with fresh module state. Use `ctx.runQuery`,
|
|
719
|
+
`ctx.runMutation`, and `ctx.use` for host-mediated data and plugin calls;
|
|
720
|
+
`ctx.signal` observes cancellation. There is no `process` or `process.env`;
|
|
721
|
+
use `await ctx.env(name)` and declare `env:<name>`. Declare `net:<hostname>`
|
|
722
|
+
for every host you fetch from. Actions have the engine's web APIs, including
|
|
723
|
+
global timers and [fetch](../engine/WEB_APIS.md). See the host reference for
|
|
724
|
+
wall and CPU deadlines. The action process supplies no local file or program
|
|
725
|
+
capabilities.
|
|
726
|
+
|
|
727
|
+
The server runs up to 64 signed-in calls per plugin and 128 total, with no
|
|
728
|
+
queue. Anonymous sign-in counts toward the total and has four slots across all
|
|
729
|
+
plugins outside the per-plugin limit; a fifth request is refused as busy.
|
|
730
|
+
|
|
731
|
+
The default QuickJS heap limit is 64 MiB per call. The process-wide worst case
|
|
732
|
+
is 128 times that limit (8 GiB by default), if every call fills its heap. The
|
|
733
|
+
Linux allocator may keep some freed memory per thread. Every call compiles its
|
|
734
|
+
action bundle again, as the server's engine did for default actions. In a
|
|
735
|
+
release build on an Apple M4 Pro, 100 sequential calls took 0.569 s with a
|
|
736
|
+
trivial bundle and 12.343 s with a 1.30 MB bundle of 9,976 distinct functions
|
|
737
|
+
(5.69 and 123.43 ms per call, respectively). Compilation counts toward the
|
|
738
|
+
one-second default sign-in budget.
|
|
739
|
+
|
|
740
|
+
At each startup, the plugin host evaluates each plugin's action bundle once in
|
|
741
|
+
a separate process with no permissions, no network and no host operations. A
|
|
742
|
+
bundle that needs network access to load fails this check.
|
|
743
|
+
|
|
744
|
+
Queries, mutations, and the top-level code of modules they import, including
|
|
745
|
+
modules shared with actions, still run in the server. Action definitions,
|
|
746
|
+
helpers, and imports used only by actions are not loaded by the server. The
|
|
747
|
+
server trusts the action process to identify which call owns each host
|
|
748
|
+
operation. A memory-safety bug in QuickJS could expose other plugins' network
|
|
749
|
+
permissions and in-flight calls in the action process. The server itself does
|
|
750
|
+
not run those actions. See [Plugin host](../host/README.md#action-process)
|
|
751
|
+
for deadlines, limits, and recovery.
|
|
752
|
+
|
|
753
|
+
## Web client entries
|
|
754
|
+
|
|
755
|
+
`@tokamaq/sdk` keeps the portable transport, function references, and plugin API.
|
|
756
|
+
`@tokamaq/sdk/solid` supplies `useQuery`, `ClientContext`, and `useClient` for
|
|
757
|
+
Solid 2. Provide the connected client with `<ClientContext value={client}>`.
|
|
758
|
+
Reactive query argument changes unsubscribe the old query; owner disposal
|
|
759
|
+
unsubscribes the current query.
|
|
760
|
+
|
|
761
|
+
`@tokamaq/sdk/client` supplies components and their extension actions, window
|
|
762
|
+
state, and shortcut and region helpers.
|
|
763
|
+
These entries use Solid 2.0.0 and `@solidjs/web` 2.0.0. They do not mount the app,
|
|
764
|
+
open sockets, or implement plugin module loading.
|
|
765
|
+
|
|
766
|
+
`state(initial, { keep: "me" })` loads the signed-in user's saved value once.
|
|
767
|
+
Edits show immediately and save after that load succeeds. Use a pure updater
|
|
768
|
+
such as `pins.set(previous => [...previous, pin])` to extend a saved value:
|
|
769
|
+
the updater may run again against the stored value. Passing a value to `set`
|
|
770
|
+
replaces it.
|
|
771
|
+
|
|
772
|
+
## Component actions
|
|
773
|
+
|
|
774
|
+
The builder generates a typed `find` function for each plugin's public
|
|
775
|
+
client entry. In the add-on, import the owner and export a placement:
|
|
776
|
+
|
|
777
|
+
```tsx
|
|
778
|
+
import { after } from "@tokamaq/sdk/client";
|
|
779
|
+
import * as chat from "plugin:chat/client";
|
|
780
|
+
|
|
781
|
+
export const Cost = after(chat.find("box"), (props) => <small>{props.draft.length} characters</small>);
|
|
782
|
+
```
|
|
783
|
+
|
|
784
|
+
Use `before` and `after` for siblings, `prepend` and `append` for children, and
|
|
785
|
+
`hide` to remove an element.
|
|
786
|
+
|
|
787
|
+
```tsx
|
|
788
|
+
import { layer } from "@tokamaq/sdk/client";
|
|
789
|
+
import * as chat from "plugin:chat/client";
|
|
790
|
+
|
|
791
|
+
export const Heading = layer(chat.find("heading"), (_, Original) => (
|
|
792
|
+
<Original>What should we work on?</Original>
|
|
793
|
+
));
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
Use `layer(target, (props, Original) => …)` to take over the element.
|
|
797
|
+
Render `<Original />` to draw the next layer down, or the owner's element
|
|
798
|
+
at the bottom. Pass children to change the contents without changing the
|
|
799
|
+
element or its attributes. Put `<Original.Children />` inside `<Original>` to
|
|
800
|
+
draw the contents that would appear without this layer: the children supplied
|
|
801
|
+
by an outer layer, or the owner's contents with other plugins' `prepend` and
|
|
802
|
+
`append`. Draw `Original` and `Original.Children` once at a time. A layer may have two
|
|
803
|
+
uses of `Original` in two branches and switch between them: the element is
|
|
804
|
+
handed over and stays mounted. If both are drawn at once, only the last one
|
|
805
|
+
shows, with a warning.
|
|
806
|
+
If no layer draws `Original`, the owner's element is unloaded. While a layer
|
|
807
|
+
supplies the contents, the owner's plain tags inside keep their DOM nodes,
|
|
808
|
+
but components inside mount again each time the contents change hands, so
|
|
809
|
+
their own state starts over. A layer with a
|
|
810
|
+
false `when` passes through.
|
|
811
|
+
Layers run outermost first by plugin install order, then `order` (default
|
|
812
|
+
0), plugin ID, and export name. `before` and `after` stay outside all layers;
|
|
813
|
+
`hide` also removes those sibling additions.
|
|
814
|
+
|
|
815
|
+
Use `attrs(target, (props, current) => values, options?)` to change HTML
|
|
816
|
+
attributes on a plain element or props on a component. The callback and
|
|
817
|
+
`when` are live and receive the owning render function's props. `current`
|
|
818
|
+
contains the owner's values plus earlier actions, sorted by install order,
|
|
819
|
+
then `order`, plugin ID, and export name. Class strings are added to existing
|
|
820
|
+
classes, including the owner's Solid class objects and arrays. For other
|
|
821
|
+
keys, a defined value overrides `current`; omit the key or return `undefined`
|
|
822
|
+
to leave it alone. If another add-on already set a key, read `current` for
|
|
823
|
+
that key to combine the values and avoid an overwrite warning.
|
|
824
|
+
|
|
825
|
+
```tsx
|
|
826
|
+
import { attrs } from "@tokamaq/sdk/client";
|
|
827
|
+
import * as chat from "plugin:chat/client";
|
|
828
|
+
|
|
829
|
+
export const Busy = attrs(chat.find("article", { in: "Message" }), (props) => ({
|
|
830
|
+
"aria-busy": props.message.status === "streaming",
|
|
831
|
+
}));
|
|
832
|
+
```
|
|
833
|
+
|
|
834
|
+
Give `Original` attributes with the same rules: `<Original class="dim" />`
|
|
835
|
+
adds a class after `attrs` has run. These attributes only apply if the layers
|
|
836
|
+
below draw the owner's element. You can't change identifiers (`id`,
|
|
837
|
+
`data-part`, `data-part-ignore`), refs, content as an attribute, event
|
|
838
|
+
handlers, or function props. Pass JSX children to `Original` to replace
|
|
839
|
+
its contents. Rebuild the owner to publish the attribute types for its
|
|
840
|
+
elements.
|
|
841
|
+
|
|
842
|
+
A placement and its optional live `when` function
|
|
843
|
+
receive the owning render function's props, plus `$row.item` and
|
|
844
|
+
`$row.index` in a Solid list row. Nested rows expose the enclosing row
|
|
845
|
+
as `$row.parent`. Use a literal name. Narrow it with `{ in: "Header" }` or
|
|
846
|
+
with literal `type`, `href`, `role`, and `aria` filters, such as
|
|
847
|
+
`chat.find("button", { aria: { label: "Stop" } })`. Attribute filters
|
|
848
|
+
match only static strings and the typed API offers values for that name.
|
|
849
|
+
Use a 1-based `nth` among the remaining matches. Both builds warn when
|
|
850
|
+
an add-on finds a plain tag with no static `data-part` or `id` and ask the
|
|
851
|
+
owner to add `data-part`. The window keeps the original match on owner updates when possible and follows a unique named
|
|
852
|
+
match that has moved. It skips missing or ambiguous targets, and an `nth`
|
|
853
|
+
target whose position another element took. See the [builder guide](../build/README.md#extending-a-screen)
|
|
854
|
+
for the naming rules.
|
|
855
|
+
|
|
856
|
+
Use `attach(owner.find("Composer"), TrackComposer, { when })` to run a
|
|
857
|
+
component for each mounted instance of the owner's named render function.
|
|
858
|
+
It receives live props and can use effects, cleanup, context, and shell
|
|
859
|
+
regions such as `Region.Panel`. Returned JSX is evaluated without drawing in
|
|
860
|
+
place. Hiding or layering an element inside the function leaves the attachment
|
|
861
|
+
running. An attachment stops and cleans up when its instance leaves, `when`
|
|
862
|
+
becomes false, or it throws. Failures are warned once per plugin and export.
|
|
863
|
+
|
|
864
|
+
For `attach`, `find` searches only render functions; placements search only
|
|
865
|
+
elements. Use `in` for an enclosing render function and `nth` to pick a
|
|
866
|
+
position; attribute filters apply to elements. Attachments start in plugin
|
|
867
|
+
install order, then `order`, plugin ID, and export name. Owner updates
|
|
868
|
+
recheck the match and warn when an attachment can no longer resolve.
|
|
869
|
+
|
|
870
|
+
### Plugin alerts
|
|
871
|
+
|
|
872
|
+
The active view's **Plugin alerts** list reports:
|
|
873
|
+
|
|
874
|
+
- A search that no longer matches its intended element or render function.
|
|
875
|
+
- A layer that omits `Original` and covers another plugin's lower layer,
|
|
876
|
+
inside placement, attributes, or action on a descendant.
|
|
877
|
+
- A `hide` that removes another plugin's action on the element or a descendant.
|
|
878
|
+
- An addition, layer, attribute callback, attachment, or `when` that throws.
|
|
879
|
+
The alert names the plugin and export; the owner can still render.
|
|
880
|
+
- Attribute problems: overwriting another plugin's value without reading
|
|
881
|
+
`current`, setting a forbidden attribute, or targeting an old owner that
|
|
882
|
+
must be rebuilt.
|
|
883
|
+
|
|
884
|
+
Cover and hide alerts name both plugins and clear when the action no longer
|
|
885
|
+
causes the loss. Multiple mounted instances share a single alert. Failures
|
|
886
|
+
stay in the list until the failing plugin is removed or reloaded.
|
|
887
|
+
|
|
888
|
+
## Caller identity
|
|
889
|
+
|
|
890
|
+
Queries, mutations and actions receive `ctx.auth.user` (`id`, `name`, and
|
|
891
|
+
`role`: `owner`, `admin`, or `member`) and `ctx.auth.device` (`id` and
|
|
892
|
+
`name`). Nested calls keep the same caller on signed-in requests. Before
|
|
893
|
+
sign-in, an `auth.method` action and its nested calls are anonymous:
|
|
894
|
+
`ctx.auth` throws, and nested calls can only access private queries and mutations
|
|
895
|
+
of that provider. On the QuickJS action process, the short sign-in
|
|
896
|
+
time budget includes starting the call's QuickJS runtime and evaluating the bundle.
|
|
897
|
+
|
|
898
|
+
In a window component, call `auth.me()` during setup. It returns a live object
|
|
899
|
+
with `id`, `name`, `role`, and `device`. Read the fields in reactive code so they
|
|
900
|
+
update in place. The fields suspend until identity loads.
|
|
901
|
+
|
|
902
|
+
```tsx
|
|
903
|
+
import { auth } from "@tokamaq/sdk/client";
|
|
904
|
+
import { Loading } from "@solidjs/web";
|
|
905
|
+
|
|
906
|
+
function AccountName() {
|
|
907
|
+
const me = auth.me();
|
|
908
|
+
return (
|
|
909
|
+
<Loading fallback="Loading…">
|
|
910
|
+
<span>{me.name}</span>
|
|
911
|
+
</Loading>
|
|
912
|
+
);
|
|
913
|
+
}
|
|
914
|
+
```
|
|
915
|
+
|
|
916
|
+
The core provides identity even without any installed plugins. A local
|
|
917
|
+
server supplies the owner automatically and uses the computer's name for
|
|
918
|
+
the device.
|
|
919
|
+
|
|
920
|
+
### Call notes
|
|
921
|
+
|
|
922
|
+
Queries, mutations, and actions receive a read-only
|
|
923
|
+
`ctx.call` with `user`, `device`, `depth`, and an optional `threadId`.
|
|
924
|
+
Anonymous calls have `null` for `user` and `device`; `ctx.auth` behaves
|
|
925
|
+
as before.
|
|
926
|
+
|
|
927
|
+
A root call starts at depth zero. Each nested call adds one.
|
|
928
|
+
A function can call itself or loop through others up to depth 15; going past it
|
|
929
|
+
fails with the target plugin and function in the error.
|
|
930
|
+
The first call in the chain with a validated
|
|
931
|
+
`v.id("threads")` argument whose value is a qualified `chat/threads:…` ID
|
|
932
|
+
sets the thread for its descendants. The argument can be inside an object
|
|
933
|
+
or array and can have any name. An ordinary string that looks like a thread
|
|
934
|
+
ID does not set it. If multiple typed IDs occur in one call, object fields
|
|
935
|
+
are visited in key order and arrays in element order.
|
|
936
|
+
|
|
937
|
+
`threadId` says which thread the caller claims the call is about. It is not an
|
|
938
|
+
access check; verify the caller's access before reading or changing that thread.
|
|
939
|
+
|
|
940
|
+
The Runner preserves the note across routed local contracts and when a
|
|
941
|
+
caller action calls a server query, mutation, or action through the window.
|
|
942
|
+
The server uses the window's authenticated identity and advances the depth.
|
|
943
|
+
A typed thread ID in the caller action's own arguments carries into its
|
|
944
|
+
server calls when no earlier call set the thread.
|
|
945
|
+
|
|
946
|
+
### Membership hooks
|
|
947
|
+
|
|
948
|
+
Plugins with `depends: ["auth"]` can export a server hook to react when a
|
|
949
|
+
shared server adds or removes a member:
|
|
950
|
+
|
|
951
|
+
```ts
|
|
952
|
+
import { onMember } from "@tokamaq/sdk";
|
|
953
|
+
import * as auth from "plugin:auth/contracts";
|
|
954
|
+
|
|
955
|
+
export const cleanup = onMember(auth.memberRemoved, async (ctx, member) => {
|
|
956
|
+
// Use member.id to find data that belongs to the removed member.
|
|
957
|
+
});
|
|
958
|
+
```
|
|
959
|
+
|
|
960
|
+
`auth.memberAdded` has the same signature. Hooks run as private mutations
|
|
961
|
+
after the membership change takes effect. Use the event's `{ id, name, role }`
|
|
962
|
+
to identify the member; there is no caller or device. For a schema-typed
|
|
963
|
+
handler, use `provide(auth.memberRemoved, { run: internalMutation(...) })`
|
|
964
|
+
with `memberFields` as its arguments and return `null`. Hooks run on currently
|
|
965
|
+
loaded plugins; a failed hook is logged and does not undo a membership change.
|
|
966
|
+
|
|
967
|
+
A sign-in plugin that implements `auth.method.createAccount` must also clean
|
|
968
|
+
up the account by `member.id` in `auth.memberRemoved`. If the core cannot save
|
|
969
|
+
the member binding, it runs only that provider's cleanup with the unused ID.
|
|
970
|
+
|
|
971
|
+
## Views in the shell
|
|
972
|
+
|
|
973
|
+
Export `view({ route, title, icon }, render)` to declare a page. The route is
|
|
974
|
+
a literal; the optional title and icon can be literals or `const` strings.
|
|
975
|
+
Use one single-colour SVG path in a 24 × 24 box for the icon shown in the rail,
|
|
976
|
+
tabs and search. To expose elements, use a `component` inside the page.
|
|
977
|
+
Inside a view, `Region.Sidebar`, `Region.Header` and `Region.Panel`
|
|
978
|
+
place content in the shell, and `usePageTitle(() => title)` names the page for
|
|
979
|
+
its tab and the window title while the view is mounted.
|
|
980
|
+
|
|
981
|
+
### Quitting with work in progress
|
|
982
|
+
|
|
983
|
+
When the person quits the desktop app, it asks every check registered with
|
|
984
|
+
`onQuit` from `@tokamaq/sdk/client`. A check that answers a blocker makes the
|
|
985
|
+
app ask first ("Claude is still working in 1 thread · Stop and quit ·
|
|
986
|
+
Cancel"); Stop and quit runs each blocker's `stop` before the app closes. A
|
|
987
|
+
check that throws or takes over 2 seconds blocks nothing. The app reads the
|
|
988
|
+
answers with `quitBlockers()`.
|
|
989
|
+
|
|
990
|
+
```ts
|
|
991
|
+
import { onQuit } from "@tokamaq/sdk/client";
|
|
992
|
+
const remove = onQuit(async () => {
|
|
993
|
+
const turns = await running();
|
|
994
|
+
return turns.length ? { message: "Claude is still working in 1 thread", stop: stopAll } : undefined;
|
|
995
|
+
});
|
|
996
|
+
```
|
|
997
|
+
|
|
998
|
+
`within(promise, ms)` from `@tokamaq/sdk` waits at most `ms` and resolves
|
|
999
|
+
`TIMED_OUT` when the time is up (window and local code; server functions have no timers).
|
|
1000
|
+
|
|
1001
|
+
### Typed references to another plugin's rows
|
|
1002
|
+
|
|
1003
|
+
Declare the owner in `depends` in `plugin.ts`. Import its table handles from
|
|
1004
|
+
`plugin:<id>/tables` and use `v.ref` on a top-level field in your own schema:
|
|
1005
|
+
|
|
1006
|
+
```ts
|
|
1007
|
+
import { defineSchema, defineTable, v } from "@tokamaq/sdk";
|
|
1008
|
+
import * as chat from "plugin:chat/tables";
|
|
1009
|
+
|
|
1010
|
+
export default defineSchema({
|
|
1011
|
+
threadProfiles: defineTable({
|
|
1012
|
+
thread: v.ref(chat.tables.threads),
|
|
1013
|
+
profile: v.string(),
|
|
1014
|
+
}).unique("by_thread", ["thread"]),
|
|
1015
|
+
});
|
|
1016
|
+
```
|
|
1017
|
+
|
|
1018
|
+
The field has type `Id<"chat.threads">`. The builder copies the owner's table
|
|
1019
|
+
types into `.tokamaq/types/` and refreshes the copy each time you build.
|
|
1020
|
+
Use `TableDocument<typeof chat.tables.threads>` for the owner's document type.
|
|
1021
|
+
You can use the same validator for function arguments. The ref works with an
|
|
1022
|
+
index like any other field and may be optional with `v.optional`.
|
|
1023
|
+
|
|
1024
|
+
A ref does not give `ctx.db` access to the owner's table. To read a referenced
|
|
1025
|
+
row, call the owner's public query. Saving a ref requires an existing row in
|
|
1026
|
+
the declared table. Deleting that row automatically deletes all rows that
|
|
1027
|
+
reference it as part of the same save. If the save rolls back, all rows remain.
|
|
1028
|
+
|
|
1029
|
+
Adding a ref or changing its target does not check existing values. Rows of a
|
|
1030
|
+
removed plugin keep their refs, but those refs do not cascade until the plugin
|
|
1031
|
+
is installed again. Importing `plugin:owner/tables` anywhere in your plugin
|
|
1032
|
+
switches that owner's generated API types to qualified IDs for your whole
|
|
1033
|
+
plugin, so you can pass those IDs directly between refs and public functions.
|
|
1034
|
+
|
|
1035
|
+
### Typed contracts between plugins
|
|
1036
|
+
|
|
1037
|
+
Define a contract in `src/contracts.ts`. The defining plugin can discover and
|
|
1038
|
+
choose providers without depending on them:
|
|
1039
|
+
|
|
1040
|
+
```ts
|
|
1041
|
+
import { contract } from "@tokamaq/sdk";
|
|
1042
|
+
|
|
1043
|
+
export const agent = contract<{
|
|
1044
|
+
id: string;
|
|
1045
|
+
name: string;
|
|
1046
|
+
start: (run: { report(text: string): void }) => Promise<void>;
|
|
1047
|
+
}>("agent", { on: "caller" });
|
|
1048
|
+
```
|
|
1049
|
+
|
|
1050
|
+
A provider declares the defining plugin in `depends` or `optional` in
|
|
1051
|
+
`plugin.ts`. Export the registration from any function source file:
|
|
1052
|
+
|
|
1053
|
+
```ts
|
|
1054
|
+
import { provide } from "@tokamaq/sdk";
|
|
1055
|
+
import { agent } from "plugin:ai/contracts";
|
|
1056
|
+
|
|
1057
|
+
export default provide(agent, {
|
|
1058
|
+
id: "example",
|
|
1059
|
+
name: "Example",
|
|
1060
|
+
start: async (run) => {
|
|
1061
|
+
run.report("Started");
|
|
1062
|
+
},
|
|
1063
|
+
});
|
|
1064
|
+
```
|
|
1065
|
+
|
|
1066
|
+
In a caller action or server action belonging to the defining plugin, pass
|
|
1067
|
+
the handler's `ctx`: call `await agent.list(ctx)`, `await agent.get(id, ctx)`
|
|
1068
|
+
(returns `undefined` when absent), or `await agent.get(id, ctx).start(run)`
|
|
1069
|
+
for a required method. Queries and mutations leave `ctx` out. Use the awaited
|
|
1070
|
+
provider to read data or check optional methods. Lookups use the current
|
|
1071
|
+
catalog. An explicit
|
|
1072
|
+
implementation `id` is the selection key; otherwise the plugin id is used.
|
|
1073
|
+
|
|
1074
|
+
Declare a Runner contract with `{ on: "caller" }` and call it from a caller
|
|
1075
|
+
action. The Runner routes every call
|
|
1076
|
+
to the provider's process, reusing the caller's host when the provider is the
|
|
1077
|
+
same plugin. Lookups read provider data
|
|
1078
|
+
and available method names from that process. Keep the fields static for a
|
|
1079
|
+
build; the caller can reuse them after a process restarts. Arguments and
|
|
1080
|
+
results must be plain JSON. A value JSON would change or lose fails with the
|
|
1081
|
+
contract and method name. Size and nesting limits apply, and a void result
|
|
1082
|
+
becomes `null` across processes.
|
|
1083
|
+
|
|
1084
|
+
Pass `{ signal }` to a local contract lookup to cancel its pending routed
|
|
1085
|
+
calls without ending the caller's invocation. A method that accepts one object
|
|
1086
|
+
can also take that same signal as `input.signal`. QuickJS sends only the other
|
|
1087
|
+
fields and assigns the provider invocation's signal to `input.signal` before
|
|
1088
|
+
calling the regular `action({ on: "caller", handler })` definition. If the live input uses a different signal than the
|
|
1089
|
+
routed call, use `inputSignal` to identify the value to keep off the wire.
|
|
1090
|
+
A provider can use `{ unavailable: "…" }` in
|
|
1091
|
+
`provide()` to supply a notice for the lookup's `onUnavailable` callback even
|
|
1092
|
+
when its process cannot start; errors thrown by the handler still reject.
|
|
1093
|
+
|
|
1094
|
+
The builder marks caller contracts as plain data in the manifest, and QuickJS
|
|
1095
|
+
checks that marker before routing a provider call.
|
|
1096
|
+
|
|
1097
|
+
Turn hook authors declare a regular `action({ on: "caller", handler })` and read
|
|
1098
|
+
`turn.signal`. The SDK attaches the hook invocation's signal
|
|
1099
|
+
as described above. Stop cancels the before hook; after hooks run together
|
|
1100
|
+
under one deadline and are also cancelled if the turn is lost. Code stores
|
|
1101
|
+
the before snapshot under a Git ref scoped to the thread and turn ID, so a
|
|
1102
|
+
replacement Code process can pair it with the after snapshot.
|
|
1103
|
+
|
|
1104
|
+
Use `action({ on: "caller", handler: (ctx, run: Run) => ... })` when a method needs local context
|
|
1105
|
+
such as `ctx.proc`. Declare it as a private constant and pass it to `provide`.
|
|
1106
|
+
All local methods receive the calling member and device in their context. A
|
|
1107
|
+
matching provider build must be installed on the client.
|
|
1108
|
+
|
|
1109
|
+
The `ai` agent contract uses the author's `start(ctx, run)` API. The provider SDK builds the `Run` in the agent's plugin process.
|
|
1110
|
+
`run.text` and other reports are batched, `run.ask` waits for the sender's
|
|
1111
|
+
answer, and `run.onSteer` and `run.onStop` register handlers in that host.
|
|
1112
|
+
CLI programs opened by the agent's `ctx.proc` belong to the turn and are
|
|
1113
|
+
reaped on force stop or when its manager's call is cancelled. While the
|
|
1114
|
+
manager settles a turn, Force stop can also kill groups left by a completed
|
|
1115
|
+
`start`. Await the CLI's exit before returning from `start` if the next turn
|
|
1116
|
+
needs a session file the CLI is still writing. Agent authors
|
|
1117
|
+
do not implement the message transport.
|
|
1118
|
+
|
|
1119
|
+
`Run.launchSettings`, when present, holds the environment, arguments, and
|
|
1120
|
+
optional OpenAI-compatible Responses provider (`{ baseUrl, keyEnv, key }`) for
|
|
1121
|
+
that start. Only one hook may supply the provider. Its values stay in the
|
|
1122
|
+
caller; don't log or report them. The
|
|
1123
|
+
caller-only `withAgentLaunch` helper from `@tokamaq/sdk/agent-launch` gives
|
|
1124
|
+
Claude or Codex a private CLI home under the Runner's data folder. It is
|
|
1125
|
+
shared only by turns of the same thread, agent, and set of contributing
|
|
1126
|
+
plugins, even when the hook values change. The Runner that deletes the thread
|
|
1127
|
+
cleans up its homes. The helper removes inherited CLI-specific environment
|
|
1128
|
+
variables before adding the hook's variables. Providers still load project
|
|
1129
|
+
settings, check the CLI version in the isolated environment, and wait for it
|
|
1130
|
+
to finish writing its session. Claude requires an explicit Anthropic key or
|
|
1131
|
+
token; Codex uses file storage for credentials. Hook arguments come before
|
|
1132
|
+
Tokamaq's flags and cannot override them. AI redacts launch values from errors.
|
|
1133
|
+
|
|
1134
|
+
The adapter in `packages/sdk/worker/contracts.ts` special-cases
|
|
1135
|
+
`owner === "ai" && name === "agent" && method === "start"` to build that
|
|
1136
|
+
`Run`. The Runner's linked call transport is general and does not inspect
|
|
1137
|
+
agent messages. The start carries a protocol version so an old ai bundle
|
|
1138
|
+
and a host with a different wire format fail with a version error. Reports
|
|
1139
|
+
are validated as a batch and acknowledged in order before the agent returns
|
|
1140
|
+
its final result. The 1008 KiB start payload keeps the full prompt and drops
|
|
1141
|
+
the oldest history as needed. A message that cannot fit even without history
|
|
1142
|
+
fails once, including when it is at the head of the queue.
|
|
1143
|
+
|
|
1144
|
+
QuickJS allows up to 64 concurrent turns per Runner and up to 32 on an
|
|
1145
|
+
individual agent host, within the 128 invocation slots per host. The Runner
|
|
1146
|
+
enforces both limits. Reports and questions wait for space in bounded queues.
|
|
1147
|
+
The adapter merges consecutive text or thinking deltas and replaces unsent
|
|
1148
|
+
tasks, plan, and usage snapshots. It sends batches below 640 KiB and allows
|
|
1149
|
+
768 KiB per turn (JSON bytes plus 64 bytes per buffered event, including the
|
|
1150
|
+
batch awaiting acknowledgement). At 32 turns that accounts for 24 MiB of
|
|
1151
|
+
reports per host. The reporting API stays synchronous; if coalescing cannot
|
|
1152
|
+
keep the buffer below its limit, only that turn fails with “The agent produced
|
|
1153
|
+
output faster than it could be saved.”
|
|
1154
|
+
|
|
1155
|
+
If Force stop cannot drain
|
|
1156
|
+
reports within 750 ms, the host can still kill the invocation's programs
|
|
1157
|
+
without running JavaScript. A stuck realm may subsequently be reset by the
|
|
1158
|
+
watchdog, which also ends its other invocations.
|
|
1159
|
+
|
|
1160
|
+
A server contract runs on the server by default. For each
|
|
1161
|
+
method provide a server function definition such as `internalAction` or
|
|
1162
|
+
`internalQuery`; calls obey the usual kind rules and cross the server function
|
|
1163
|
+
boundary as JSON. Data fields are JSON, and the implementation uses an object
|
|
1164
|
+
literal so the build can register its methods.
|
|
1165
|
+
|
|
1166
|
+
An optional provider still builds and runs without the defining plugin
|
|
1167
|
+
installed. The compiler only needs its public contract types. If the defining
|
|
1168
|
+
plugin's source is unavailable, check in an exact copy of its public contract
|
|
1169
|
+
declaration at `contracts/<id>.ts` in the provider. That copy supplies types
|
|
1170
|
+
and a contract key. The implementation stays inactive until the owner is in
|
|
1171
|
+
the installed catalog. For a local contract, the client skips an incompatible
|
|
1172
|
+
provider individually; the ai agent list shows the provider as unavailable.
|
|
1173
|
+
For a server contract, the server refuses a mismatched declaration hash.
|
|
1174
|
+
|
|
1175
|
+
For a direct server-to-server export, wrap a query, mutation or action in
|
|
1176
|
+
`pluginOnly(...)` and re-export it from `src/server/api.ts` as usual.
|
|
1177
|
+
Dependents can import the reference from `plugin:<id>/server`. Within the
|
|
1178
|
+
defining plugin, use the generated `_generated/plugin.ts` references. These
|
|
1179
|
+
functions are excluded from the window API, local-to-server transport and
|
|
1180
|
+
subscriptions. `internal*` remains private to its own plugin.
|
|
1181
|
+
|
|
1182
|
+
## Hook another plugin's function
|
|
1183
|
+
|
|
1184
|
+
A hook on an `on: "caller"` action runs on the caller's own machine and is
|
|
1185
|
+
advisory there: a modified client can skip it. Enforce rules with a query or
|
|
1186
|
+
mutation hook, which runs on the server.
|
|
1187
|
+
|
|
1188
|
+
Export a hook from a server module and target a query, mutation, or action
|
|
1189
|
+
in another plugin. Installing your plugin registers the hook automatically.
|
|
1190
|
+
Public and plugin-only references come from `plugin:<id>/server`; the same
|
|
1191
|
+
module's `internal` namespace provides typed references such as
|
|
1192
|
+
`team.internal.users.saveHidden`. An internal hook runs when the owner calls
|
|
1193
|
+
the function. The reference does not let other plugins call it or make it
|
|
1194
|
+
visible to the window. You cannot hook an `httpAction`.
|
|
1195
|
+
|
|
1196
|
+
```ts
|
|
1197
|
+
import { createHook, fail } from "@tokamaq/sdk";
|
|
1198
|
+
import * as team from "plugin:team/server";
|
|
1199
|
+
import schema from "./schema";
|
|
1200
|
+
|
|
1201
|
+
const hook = createHook(schema); // use the SDK's `hook` directly if no schema is needed
|
|
1202
|
+
|
|
1203
|
+
export const moderateUsers = hook(team.api.list, {
|
|
1204
|
+
before(ctx, args) {
|
|
1205
|
+
if (ctx.auth.user.role === "member") return fail("forbidden");
|
|
1206
|
+
return { ...args, text: args.text.trim() };
|
|
1207
|
+
},
|
|
1208
|
+
async after(ctx, users, args) {
|
|
1209
|
+
const bans = await ctx.db.query("bans").collect();
|
|
1210
|
+
return users.filter((user) => !bans.some((ban) => ban.name === user.name));
|
|
1211
|
+
},
|
|
1212
|
+
});
|
|
1213
|
+
```
|
|
1214
|
+
|
|
1215
|
+
Either stage can be omitted. `before` returns valid arguments for the target
|
|
1216
|
+
or stops the call with `fail(kind, data?)`. `after` receives the function's
|
|
1217
|
+
result and the final arguments and returns a result of the same type. The
|
|
1218
|
+
server checks both stages' output against the target validators and rejects
|
|
1219
|
+
extra fields on validated objects. The result validator comes from the function's
|
|
1220
|
+
`returns` option or its TypeScript result type. Open values such as `unknown`
|
|
1221
|
+
remain unchecked inside otherwise validated results. For older bundles without
|
|
1222
|
+
a result validator, the server accepts after-hook results and warns on load.
|
|
1223
|
+
If the owner's value falls outside a derived validator, the server warns and
|
|
1224
|
+
accepts after-hook values for that call. An explicit `returns` validator remains strict.
|
|
1225
|
+
|
|
1226
|
+
A hook's `fail("forbidden", data)` rejects the window call or nested
|
|
1227
|
+
`ctx.runQuery` with an error whose `kind` is `"forbidden"` and whose `data`
|
|
1228
|
+
is the supplied value (or `null`). The error also exposes `plugin`, `hook`,
|
|
1229
|
+
and `stage`. Built-in kinds are `hookException` for a thrown error,
|
|
1230
|
+
`invalidHookResult` for an invalid return, `hookDepthLimit` for a depth or
|
|
1231
|
+
delegation budget limit, and `hookTimeout` for a timed-out stage. Hook order across plugins is unspecified;
|
|
1232
|
+
each stage receives the previous stage's value.
|
|
1233
|
+
|
|
1234
|
+
A query hook can only read its own plugin's database. It has the original
|
|
1235
|
+
caller in `ctx.auth` and shares the call note in `ctx.call` at one greater
|
|
1236
|
+
depth. Calling the hooked query again is subject to the same depth limit as
|
|
1237
|
+
any nested call. The hooks also run on server calls and live window queries;
|
|
1238
|
+
a change to data read by either the query or a hook can refresh a live result.
|
|
1239
|
+
A mutation hook can write its own tables as part of the target's save. A failure
|
|
1240
|
+
in the hook or handler rolls back all those writes, even if a caller catches a
|
|
1241
|
+
nested hook error. A write conflict retries the whole mutation and its hooks.
|
|
1242
|
+
|
|
1243
|
+
Each write to a watched table outside a trigger starts a fresh budget of 256
|
|
1244
|
+
stages and delegated calls per trigger it dispatches. This applies to writes
|
|
1245
|
+
from the root handler, its delegated mutations, and mutation hooks. Nested
|
|
1246
|
+
hooks, triggers, and delegated calls in the same trigger chain share its budget,
|
|
1247
|
+
so endless fan-out fails with the hook or trigger named. In the worst case a
|
|
1248
|
+
top-level call can spend a fresh budget on every dispatch, so the total is
|
|
1249
|
+
bounded by the call deadline and depth, not by a global count.
|
|
1250
|
+
|
|
1251
|
+
A plugin’s query hooks, mutation hooks, and triggers share a module instance
|
|
1252
|
+
within one call. A stage that is still running can share its `ctx` with another
|
|
1253
|
+
stage through module state; that `ctx` stops working when its own stage ends.
|
|
1254
|
+
|
|
1255
|
+
An action hook runs with its own plugin's network grants and environment. It can
|
|
1256
|
+
use `ctx.runQuery`, `ctx.runMutation`, and `ctx.runAction`. The selected placement,
|
|
1257
|
+
including a per-call `on` override, applies to both stages. On an attached or
|
|
1258
|
+
personal connected Runner, the server runs both stages on that Runner with the
|
|
1259
|
+
same budget as nested calls and point hooks. On the shared-server window route,
|
|
1260
|
+
stages can only call public functions; attempts to call private functions fail
|
|
1261
|
+
with `runnerCapabilityUnavailable`. If the Runner cannot execute a stage, the
|
|
1262
|
+
call fails with `hookRunnerUnavailable` and names the hook plugin. A plugin-owned
|
|
1263
|
+
machine only receives code owned by its plugin. The server rejects any action
|
|
1264
|
+
with a foreign hook or point on that machine before running it.
|
|
1265
|
+
|
|
1266
|
+
Removing the hooking plugin removes its hooks. When a target is renamed or
|
|
1267
|
+
removed, the owner's build warns and names the hooking plugin. The hooking
|
|
1268
|
+
plugin still loads; the server skips that hook and logs a warning.
|
|
1269
|
+
|
|
1270
|
+
### Hook a named point inside a function
|
|
1271
|
+
|
|
1272
|
+
A query, mutation, or action can expose a named spot in its handler with
|
|
1273
|
+
`point(ctx, name, value)` from `@tokamaq/sdk`. Use a unique, nonempty string literal
|
|
1274
|
+
without `#`. A helper in the same module can take `ctx` and call a point if the
|
|
1275
|
+
compiler can trace it to exactly one exported handler. Pass that handler’s
|
|
1276
|
+
context, or the inner context from its `withPrograms` callback: a point runs
|
|
1277
|
+
for the call whose context it is given, and fails once that call has ended.
|
|
1278
|
+
Points are not allowed in triggers or hook stages.
|
|
1279
|
+
|
|
1280
|
+
```ts
|
|
1281
|
+
import { point } from "@tokamaq/sdk";
|
|
1282
|
+
|
|
1283
|
+
const launch = await point(ctx, "launch", { env: {} as Record<string, string>, args: [] as string[] });
|
|
1284
|
+
|
|
1285
|
+
const rows = await point(ctx, "load", { search }, (input) => load(input.search));
|
|
1286
|
+
```
|
|
1287
|
+
|
|
1288
|
+
The first form lets `before` hooks change the value. A value point cannot have
|
|
1289
|
+
an `after` hook. In the second form, `before` hooks change the input, the owner
|
|
1290
|
+
runs its callback in its own process, and `after(ctx, result, input)` hooks can
|
|
1291
|
+
change the result. `input` in an after hook is the input the callback received.
|
|
1292
|
+
|
|
1293
|
+
Use `point(ctx, "launch", initial, { collect: true })` for a value point whose
|
|
1294
|
+
owner needs to combine contributions. Each `before` hook receives the same
|
|
1295
|
+
initial value. The point returns a list of `{ plugin, value }` entries, one
|
|
1296
|
+
per hook, with the plugin ID supplied by the host. Without hooks it returns
|
|
1297
|
+
an empty list. Order across plugins is unspecified. Update both server and
|
|
1298
|
+
Runner for a hooked point using this option.
|
|
1299
|
+
|
|
1300
|
+
The generated API puts each point under the function it belongs to. For example,
|
|
1301
|
+
a plugin that depends on `ai` could hook a point named `launch` on its exported
|
|
1302
|
+
`turn` action:
|
|
1303
|
+
|
|
1304
|
+
```ts
|
|
1305
|
+
import { hook } from "@tokamaq/sdk";
|
|
1306
|
+
import { api } from "plugin:ai/server";
|
|
1307
|
+
|
|
1308
|
+
export const setProxy = hook(api.turn.points.launch, {
|
|
1309
|
+
before: (_ctx, launch) => ({
|
|
1310
|
+
...launch,
|
|
1311
|
+
env: { ...launch.env, HTTPS_PROXY: "http://localhost:8080" },
|
|
1312
|
+
}),
|
|
1313
|
+
});
|
|
1314
|
+
```
|
|
1315
|
+
|
|
1316
|
+
Point references are for hooks. Their input and result types are inferred from
|
|
1317
|
+
the value or callback. These types define what hooks may return, so annotate
|
|
1318
|
+
empty literals with the types you want to allow. Use plain JSON data: a function, class instance, symbol,
|
|
1319
|
+
or promise inside point data is a build error. An async callback is fine; its
|
|
1320
|
+
resolved result is what crosses the boundary. A callback that returns
|
|
1321
|
+
`undefined` produces `null`, and object fields set to `undefined` are omitted
|
|
1322
|
+
when crossing the boundary. The build treats `unknown` and
|
|
1323
|
+
`any` as open data; a value that crosses a host boundary must still be JSON.
|
|
1324
|
+
|
|
1325
|
+
Point hooks follow the enclosing function's rules. Action hooks receive an
|
|
1326
|
+
action context: use `ctx.runQuery` or `ctx.runMutation` for your plugin's data
|
|
1327
|
+
(there is no `ctx.db`), and `ctx.call.threadId` for the thread. In a mutation they run
|
|
1328
|
+
inside the same transaction, and a failed hook rolls it back. A failed stage
|
|
1329
|
+
rejects the point with the hook's plugin, `point` name, and `pointBefore` or
|
|
1330
|
+
`pointAfter` stage. Each hook uses one level of call depth and counts against
|
|
1331
|
+
the shared 256-stage budget, including repeated calls to a point in a loop.
|
|
1332
|
+
A hooked value point returns a copy of the value. An unhooked point checks the
|
|
1333
|
+
declared and hooked names locally, then returns the original value or runs the
|
|
1334
|
+
callback directly. It spends no hook budget and makes
|
|
1335
|
+
no host call. Renaming or removing a hooked point warns the owner at build time.
|
|
1336
|
+
An installed plugin with a stale point reference still loads; the server warns
|
|
1337
|
+
and skips that hook. With a point hook on an `on: "caller"` action, every call
|
|
1338
|
+
fails with `hookRunnerUnavailable` on a desktop whose window or Runner cannot
|
|
1339
|
+
run point hooks. The error names the hooking plugin and point; update both the
|
|
1340
|
+
window and Runner.
|
|
1341
|
+
|
|
1342
|
+
## Run code when a table changes
|
|
1343
|
+
|
|
1344
|
+
Export a trigger from your plugin's server part. The owner doesn't need to
|
|
1345
|
+
register the trigger or call it from its mutations.
|
|
1346
|
+
|
|
1347
|
+
```ts
|
|
1348
|
+
import { createTrigger } from "@tokamaq/sdk";
|
|
1349
|
+
import * as chat from "plugin:chat/tables";
|
|
1350
|
+
import schema from "./schema";
|
|
1351
|
+
|
|
1352
|
+
const trigger = createTrigger(schema);
|
|
1353
|
+
|
|
1354
|
+
export const logThread = trigger(chat.tables.threads, async (ctx, change) => {
|
|
1355
|
+
if (change.operation === "insert") {
|
|
1356
|
+
await ctx.db.insert("threadLog", { thread: change.id, title: change.newDoc.title });
|
|
1357
|
+
}
|
|
1358
|
+
});
|
|
1359
|
+
```
|
|
1360
|
+
|
|
1361
|
+
Declare `chat` in `depends` to watch its tables. To watch one of your
|
|
1362
|
+
own tables, pass its name to the builder returned by `createTrigger(schema)`,
|
|
1363
|
+
for example `trigger("threadLog", handler)`. You can import `trigger` directly
|
|
1364
|
+
to watch another plugin's table when you don't need a schema for your own
|
|
1365
|
+
database. The table determines the types of `id`, `oldDoc`, and `newDoc`.
|
|
1366
|
+
Insert has a null `oldDoc`, delete has a null `newDoc`, and update has both.
|
|
1367
|
+
|
|
1368
|
+
A trigger runs after the write is applied and before the database call returns,
|
|
1369
|
+
inside the same transaction. It runs for writes from any mutation, including
|
|
1370
|
+
writes made by mutation hooks and other triggers. It gets the original caller in `ctx.auth`
|
|
1371
|
+
and the same call note at one greater depth in `ctx.call`. Its writable
|
|
1372
|
+
`ctx.db` contains only its own plugin's tables. Call the owner's functions
|
|
1373
|
+
to read or change the owner's data.
|
|
1374
|
+
|
|
1375
|
+
Deletes run one trigger chain per deleted row, including rows removed by
|
|
1376
|
+
`v.ref` cascades. The database applies the cascade before dispatching those
|
|
1377
|
+
triggers and dispatches in breadth-first order, starting with the deleted row.
|
|
1378
|
+
Patch or replace that leaves the stored document unchanged, deleting an absent row,
|
|
1379
|
+
schema resets, and startup index backfills do not run triggers.
|
|
1380
|
+
|
|
1381
|
+
If a trigger throws, the whole transaction rolls back, even if the writing
|
|
1382
|
+
mutation catches the exception. The caller's error identifies `plugin`,
|
|
1383
|
+
`hook` (the trigger export name), `stage: "trigger"`, and `table`. Its message
|
|
1384
|
+
also lists the registered triggers for that table.
|
|
1385
|
+
|
|
1386
|
+
Each write to a watched table outside a trigger starts a fresh budget of 256
|
|
1387
|
+
stages and delegated calls per trigger it dispatches. This applies to writes
|
|
1388
|
+
from the root handler, its delegated mutations, and mutation hooks. Nested
|
|
1389
|
+
hooks, triggers, and delegated calls in the same trigger chain share its budget,
|
|
1390
|
+
so endless fan-out fails with the hook or trigger named. In the worst case a
|
|
1391
|
+
top-level call can spend a fresh budget on every dispatch, so the total is
|
|
1392
|
+
bounded by the call deadline and depth, not by a global count.
|
|
1393
|
+
|
|
1394
|
+
A trigger that writes one row and calls one query added about 2 ms per row
|
|
1395
|
+
on an Apple M4 Pro; with the default 1 s deadline such a save times out near
|
|
1396
|
+
500 rows, and sooner on a slower host. Split larger writes across mutations.
|
|
1397
|
+
|
|
1398
|
+
A plugin’s query hooks, mutation hooks, and triggers share a module instance
|
|
1399
|
+
within one call. A stage that is still running can share its `ctx` with another
|
|
1400
|
+
stage through module state; that `ctx` stops working when its own stage ends.
|
|
1401
|
+
|
|
1402
|
+
The server's plugin catalog lists active triggers under `triggers`, keyed by
|
|
1403
|
+
qualified table name. A trigger whose table is missing is skipped with a
|
|
1404
|
+
warning. Removing the trigger plugin removes its registrations.
|