@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.1

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.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1403 -2
  3. package/build-internals.ts +25 -0
  4. package/caller/agent-launch.ts +60 -0
  5. package/client.tsx +498 -0
  6. package/component-actions.ts +327 -0
  7. package/component-alerts.ts +136 -0
  8. package/component-attributes.ts +340 -0
  9. package/component-parts.tsx +1177 -0
  10. package/core-contracts/auth.ts +40 -0
  11. package/package.json +98 -4
  12. package/quit.ts +58 -0
  13. package/regions.tsx +94 -0
  14. package/screen-search.ts +211 -0
  15. package/send-file.ts +175 -0
  16. package/server-build-internals.ts +11 -0
  17. package/solid.ts +132 -0
  18. package/src/agent-command.ts +48 -0
  19. package/src/agent-info-cache.ts +34 -0
  20. package/src/agent-reports.ts +140 -0
  21. package/src/agent-turn.ts +289 -0
  22. package/src/api.ts +174 -0
  23. package/src/auth.ts +39 -0
  24. package/src/call-error.ts +37 -0
  25. package/src/caller-storage.ts +32 -0
  26. package/src/client.ts +163 -0
  27. package/src/database.ts +322 -0
  28. package/src/functions.ts +726 -0
  29. package/src/hooks.ts +141 -0
  30. package/src/host.ts +211 -0
  31. package/src/http-action.ts +55 -0
  32. package/src/index.ts +126 -0
  33. package/src/internal/contracts.ts +260 -0
  34. package/src/internal/machine-scope.ts +21 -0
  35. package/src/local.ts +22 -0
  36. package/src/plugin.ts +162 -0
  37. package/src/points.ts +79 -0
  38. package/src/protocol.ts +64 -0
  39. package/src/schema.ts +136 -0
  40. package/src/storage.ts +193 -0
  41. package/src/thread-context.ts +42 -0
  42. package/src/transport.ts +421 -0
  43. package/src/triggers.ts +87 -0
  44. package/src/unstable.ts +66 -0
  45. package/src/validators.ts +248 -0
  46. package/src/values.ts +98 -0
  47. package/src/visibility.ts +8 -0
  48. package/src/websocket-transport.ts +91 -0
  49. package/src/window-state-protocol.ts +7 -0
  50. package/src/within.ts +24 -0
  51. package/src/worker-limits.ts +5 -0
  52. package/tools/bundle.mjs +490 -0
  53. package/tools/client-entry.mjs +10 -0
  54. package/tools/contracts.mjs +254 -0
  55. package/tools/http-actions.mjs +42 -0
  56. package/tools/placement.mjs +535 -0
  57. package/tools/plugin-boundary.mjs +592 -0
  58. package/tools/plugin-compiler.mjs +125 -0
  59. package/tools/plugin-descriptor.ts +75 -0
  60. package/tools/points.mjs +340 -0
  61. package/tools/result-validator.mjs +83 -0
  62. package/tools/server-builtins.mjs +82 -0
  63. package/tools/server-files.mjs +34 -0
  64. package/tools/table-references.mjs +98 -0
  65. package/tools/worker.mjs +110 -0
  66. package/tsconfig.plugin-server.json +12 -0
  67. package/tsconfig.plugin-window.json +15 -0
  68. package/view.ts +27 -0
  69. package/web.d.ts +6 -0
  70. package/window-state-host.ts +228 -0
  71. package/window-state.ts +43 -0
@@ -0,0 +1,322 @@
1
+ // Database capabilities are scoped to a handler. Query objects are immutable
2
+ // plans: reusing a base builder never inherits another caller's filters/limit.
3
+ // Only terminal methods reach the host, which owns storage and atomicity.
4
+ import type { EqualityClause, HostBridge, IndexQuery, RangeClause, StoredDocument } from "./host";
5
+ import { callHost } from "./host";
6
+ import type { DataModel, Indexes, IndexesFor, SchemaDefinition } from "./schema";
7
+ import { assertIndexName } from "./schema";
8
+ import type { Fields } from "./validators";
9
+ import { validate } from "./validators";
10
+ import type { Id, JsonObject, JsonValue } from "./values";
11
+ import { assertId, assertJson, assertTable, isPlainObject, jsonSnapshot } from "./values";
12
+
13
+ type Table<M extends DataModel> = Extract<keyof M, string>;
14
+
15
+ export type Doc<M extends DataModel, T extends Table<M>> = M[T] & {
16
+ _id: Id<T>;
17
+ _creationTime: number;
18
+ };
19
+
20
+ declare const rangeType: unique symbol;
21
+ export interface IndexBounds {
22
+ readonly [rangeType]: true;
23
+ }
24
+ type FieldValue<D, K extends string> = K extends keyof D ? D[K] : never;
25
+ type Lower<D, K extends string, R> = {
26
+ gt(field: K, value: NoInfer<FieldValue<D, K>>): R;
27
+ gte(field: K, value: NoInfer<FieldValue<D, K>>): R;
28
+ };
29
+ type Upper<D, K extends string, R> = {
30
+ lt(field: K, value: NoInfer<FieldValue<D, K>>): R;
31
+ lte(field: K, value: NoInfer<FieldValue<D, K>>): R;
32
+ };
33
+ export type IndexRange<D, F extends readonly string[]> = IndexBounds &
34
+ (F extends readonly [infer K extends string, ...infer Rest extends string[]]
35
+ ? { eq(field: K, value: NoInfer<FieldValue<D, K>>): IndexRange<D, Rest> } & Lower<
36
+ D,
37
+ K,
38
+ IndexBounds & Upper<D, K, IndexBounds>
39
+ > &
40
+ Upper<D, K, IndexBounds & Lower<D, K, IndexBounds>>
41
+ : number extends F["length"]
42
+ ? { eq<K extends Extract<keyof D, string>>(field: K, value: NoInfer<D[K]>): IndexRange<D, F> } & Lower<
43
+ D,
44
+ Extract<keyof D, string>,
45
+ IndexBounds & Upper<D, Extract<keyof D, string>, IndexBounds>
46
+ > &
47
+ Upper<D, Extract<keyof D, string>, IndexBounds & Lower<D, Extract<keyof D, string>, IndexBounds>>
48
+ : Record<never, never>);
49
+
50
+ export interface QueryResult<D extends object> {
51
+ order(direction: "asc" | "desc"): QueryResult<D>;
52
+ take(count: number): Promise<D[]>;
53
+ first(): Promise<D | null>;
54
+ collect(): Promise<D[]>;
55
+ }
56
+ // A query that already has a `where` filter. It has no `withIndex`: filters and
57
+ // an index cannot be mixed (the host rejects it), so the type removes the
58
+ // method instead of letting the chain compile and fail at runtime.
59
+ export interface FilteredQuery<D extends object> extends QueryResult<D> {
60
+ where<K extends Extract<keyof D, string>>(field: K, operator: "=", value: NoInfer<D[K]>): FilteredQuery<D>;
61
+ order(direction: "asc" | "desc"): FilteredQuery<D>;
62
+ }
63
+ export interface TableQuery<D extends object, I extends Indexes = Indexes> extends QueryResult<D> {
64
+ where<K extends Extract<keyof D, string>>(field: K, operator: "=", value: NoInfer<D[K]>): FilteredQuery<D>;
65
+ order(direction: "asc" | "desc"): TableQuery<D, I>;
66
+ withIndex<N extends Extract<keyof I, string>>(
67
+ name: N,
68
+ range?: (q: IndexRange<D, I[N]>) => IndexBounds,
69
+ ): QueryResult<D>;
70
+ }
71
+
72
+ export interface DatabaseReader<M extends DataModel = DataModel> {
73
+ get<T extends Table<M>>(id: Id<T>): Promise<Doc<M, T> | null>;
74
+ query<T extends Table<M>>(table: T): TableQuery<Doc<M, T>, IndexesFor<M, T>>;
75
+ }
76
+
77
+ export interface DatabaseWriter<M extends DataModel = DataModel> extends DatabaseReader<M> {
78
+ insert<T extends Table<M>>(table: T, value: NoInfer<M[T]>): Promise<Id<T>>;
79
+ patch<T extends Table<M>>(id: Id<T>, value: NoInfer<Partial<M[T]>>): Promise<null>;
80
+ replace<T extends Table<M>>(id: Id<T>, value: NoInfer<M[T]>): Promise<null>;
81
+ delete<T extends Table<M>>(id: Id<T>): Promise<null>;
82
+ }
83
+
84
+ function document(value: unknown, table?: string): asserts value is StoredDocument {
85
+ assertJson(value, "host document");
86
+ if (!isPlainObject(value)) throw new Error("Host returned a non-object document");
87
+ assertId(value._id, table);
88
+ if (typeof value._creationTime !== "number" || !Number.isFinite(value._creationTime)) {
89
+ throw new Error("Host document needs a finite _creationTime in epoch milliseconds");
90
+ }
91
+ }
92
+
93
+ function writeValue(value: unknown): JsonObject {
94
+ assertJson(value, "document");
95
+ if (!isPlainObject(value)) throw new Error("Document must be an object");
96
+ if (Object.hasOwn(value, "_id") || Object.hasOwn(value, "_creationTime")) {
97
+ throw new Error("Writes cannot set _id or _creationTime");
98
+ }
99
+ return jsonSnapshot(value) as JsonObject;
100
+ }
101
+
102
+ const rangeState = Symbol("tokamaq.indexRange");
103
+ interface RangeState {
104
+ owner: object;
105
+ eq: EqualityClause[];
106
+ range: RangeClause[];
107
+ }
108
+ function indexRange(state: RangeState, fields?: readonly string[], validators?: Fields): object {
109
+ const append = (operator: "eq" | RangeClause["operator"], field: string, value: unknown) => {
110
+ if (typeof field !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(field))
111
+ throw new Error("Index field must be a single ASCII identifier");
112
+ if (fields && fields[state.eq.length] !== field)
113
+ throw new Error(
114
+ operator === "eq"
115
+ ? "Index equalities must follow its leading field order"
116
+ : "Index range must constrain the field after the equality prefix",
117
+ );
118
+ const snapshot = jsonSnapshot(value, "index value");
119
+ if (validators?.[field]) validate(validators[field].description, snapshot, `index ${field}`);
120
+ if (operator === "eq") {
121
+ if (state.range.length) throw new Error("Cannot add equality after an index range");
122
+ if (state.eq.some((clause) => clause.field === field)) throw new Error("Repeated index equality field");
123
+ return indexRange({ ...state, eq: [...state.eq, { field, value: snapshot }] }, fields, validators);
124
+ }
125
+ const lower = operator === "gt" || operator === "gte";
126
+ if (
127
+ state.eq.some((clause) => clause.field === field) ||
128
+ state.range.some((clause) => clause.field !== field)
129
+ )
130
+ throw new Error("Index range must constrain the field after the equality prefix");
131
+ if (state.range.some((clause) => (clause.operator === "gt" || clause.operator === "gte") === lower))
132
+ throw new Error("An index range accepts one lower and one upper bound");
133
+ return indexRange(
134
+ { ...state, range: [...state.range, { field, operator, value: snapshot }] },
135
+ fields,
136
+ validators,
137
+ );
138
+ };
139
+ return Object.freeze({
140
+ [rangeState]: state,
141
+ eq: (field: string, value: unknown) => append("eq", field, value),
142
+ gt: (field: string, value: unknown) => append("gt", field, value),
143
+ gte: (field: string, value: unknown) => append("gte", field, value),
144
+ lt: (field: string, value: unknown) => append("lt", field, value),
145
+ lte: (field: string, value: unknown) => append("lte", field, value),
146
+ });
147
+ }
148
+
149
+ function plan<D extends object, I extends Indexes = Indexes>(
150
+ host: HostBridge,
151
+ table: string,
152
+ where: EqualityClause[] = [],
153
+ direction: "asc" | "desc" = "asc",
154
+ schema?: SchemaDefinition,
155
+ index?: IndexQuery,
156
+ ): TableQuery<D, I> {
157
+ const collect = async (limit: number | null): Promise<D[]> => {
158
+ const rows = await callHost(host, "db.query", {
159
+ table,
160
+ where,
161
+ order: direction,
162
+ limit,
163
+ ...(index ? { index } : {}),
164
+ });
165
+ if (!Array.isArray(rows)) throw new Error("Host db.query must return an array");
166
+ for (const row of rows) document(row, table);
167
+ if (limit !== null && rows.length > limit) throw new Error("Host db.query exceeded its limit");
168
+ return rows as unknown as D[];
169
+ };
170
+
171
+ return Object.freeze({
172
+ where<K extends Extract<keyof D, string>>(field: K, operator: "=", value: D[K]) {
173
+ if (index) throw new Error("where cannot be combined with withIndex");
174
+ if (typeof field !== "string" || field.length === 0)
175
+ throw new Error("Filter field must be a nonempty top-level name");
176
+ if (operator !== "=") throw new Error("Only equality filters are supported");
177
+ return plan<D, I>(
178
+ host,
179
+ table,
180
+ [...where, { field, value: jsonSnapshot(value, "filter value") }],
181
+ direction,
182
+ schema,
183
+ );
184
+ },
185
+ order(order: "asc" | "desc") {
186
+ if (order !== "asc" && order !== "desc") throw new Error("Order must be asc or desc");
187
+ return plan<D, I>(host, table, where, order, schema, index);
188
+ },
189
+ withIndex(name: string, range?: (q: IndexRange<D, readonly string[]>) => IndexBounds) {
190
+ assertIndexName(name);
191
+ if (index || where.length) throw new Error("withIndex must be selected once before any where filters");
192
+ const definition = schema?.tables[table]?.indexes.find((index) => index.name === name);
193
+ if (schema && !definition) throw new Error(`Unknown index on ${table}: ${name}`);
194
+ if (range !== undefined && typeof range !== "function")
195
+ throw new Error("Index range must be a callback");
196
+ const owner = {};
197
+ const base = indexRange(
198
+ { owner, eq: [], range: [] },
199
+ definition?.fields,
200
+ schema?.tables[table]?.fields,
201
+ );
202
+ const result = range ? range(base as IndexRange<D, readonly string[]>) : base;
203
+ const state = (result as { [rangeState]?: RangeState } | null)?.[rangeState];
204
+ if (!state || state.owner !== owner) throw new Error("Index callback must return its range builder");
205
+ return plan<D, I>(host, table, [], direction, schema, { name, eq: state.eq, range: state.range });
206
+ },
207
+ take(count: number) {
208
+ if (!Number.isSafeInteger(count) || count < 0)
209
+ throw new Error("take count must be a nonnegative safe integer");
210
+ return collect(count);
211
+ },
212
+ async first() {
213
+ return (await collect(1))[0] ?? null;
214
+ },
215
+ collect() {
216
+ return collect(null);
217
+ },
218
+ }) as unknown as TableQuery<D, I>;
219
+ }
220
+
221
+ /** Separate objects, not just erased TS types: a query has no write methods. */
222
+ function* fileFields(schema: SchemaDefinition | undefined, table: string, value: JsonObject) {
223
+ const tables = schema?.tables;
224
+ if (!tables || !Object.hasOwn(tables, table)) return;
225
+ const fields = tables[table].fields;
226
+ for (const [name, id] of Object.entries(value)) {
227
+ if (!Object.hasOwn(fields, name)) continue;
228
+ const field = fields[name].description;
229
+ const description = field.kind === "optional" ? field.inner : field;
230
+ if (description.kind === "file") yield [`${table}.${name}`, id] as const;
231
+ }
232
+ }
233
+
234
+ async function checkFile(host: HostBridge, target: string, id: JsonValue) {
235
+ if (typeof id !== "string") throw new Error(`${target}: expected file id string`);
236
+ const file = await callHost(host, "storage.get", { id });
237
+ if (!file) throw new Error(`${target}: file does not exist`);
238
+ if (file.field !== target) throw new Error(`${target}: file was uploaded for ${file.field}`);
239
+ }
240
+
241
+ function idTable(id: Id): string {
242
+ const logical = id.slice(id.indexOf("/") + 1);
243
+ return logical.slice(0, logical.indexOf(":"));
244
+ }
245
+
246
+ export function createDatabase<M extends DataModel>(
247
+ host: HostBridge,
248
+ writable: false,
249
+ schema?: SchemaDefinition,
250
+ ): DatabaseReader<M>;
251
+ export function createDatabase<M extends DataModel>(
252
+ host: HostBridge,
253
+ writable: true,
254
+ schema?: SchemaDefinition,
255
+ ): DatabaseWriter<M>;
256
+ export function createDatabase<M extends DataModel>(
257
+ host: HostBridge,
258
+ writable: boolean,
259
+ schema?: SchemaDefinition,
260
+ ): DatabaseReader<M> | DatabaseWriter<M> {
261
+ const reader: DatabaseReader<M> = {
262
+ async get<T extends Table<M>>(id: Id<T>): Promise<Doc<M, T> | null> {
263
+ assertId(id);
264
+ const row = await callHost(host, "db.get", { id });
265
+ if (row === null) return null;
266
+ document(row);
267
+ if (row._id !== id) throw new Error("Host db.get returned the wrong id");
268
+ return row as unknown as Doc<M, T>;
269
+ },
270
+ query(table) {
271
+ assertTable(table);
272
+ return plan<Doc<M, typeof table>, IndexesFor<M, typeof table>>(host, table, [], "asc", schema);
273
+ },
274
+ };
275
+ if (!writable) return Object.freeze(reader);
276
+ const fileSchema = host.bundleSchema ?? schema;
277
+ const writer: DatabaseWriter<M> = {
278
+ ...reader,
279
+ async insert(table, value) {
280
+ assertTable(table);
281
+ const snapshot = writeValue(value);
282
+ for (const [field, file] of fileFields(fileSchema, table, snapshot)) await checkFile(host, field, file);
283
+ const id = await callHost(host, "db.insert", {
284
+ table,
285
+ value: snapshot,
286
+ });
287
+ assertId(id, table);
288
+ return id as Id<typeof table>;
289
+ },
290
+ async patch(id, value) {
291
+ assertId(id);
292
+ const snapshot = writeValue(value);
293
+ for (const [field, file] of fileFields(fileSchema, idTable(id), snapshot))
294
+ await checkFile(host, field, file);
295
+ const result = await callHost(host, "db.patch", {
296
+ id,
297
+ value: snapshot,
298
+ });
299
+ if (result !== null) throw new Error("Host db.patch must return null");
300
+ return result;
301
+ },
302
+ async replace(id, value) {
303
+ assertId(id);
304
+ const snapshot = writeValue(value);
305
+ for (const [field, file] of fileFields(fileSchema, idTable(id), snapshot))
306
+ await checkFile(host, field, file);
307
+ const result = await callHost(host, "db.replace", {
308
+ id,
309
+ value: snapshot,
310
+ });
311
+ if (result !== null) throw new Error("Host db.replace must return null");
312
+ return result;
313
+ },
314
+ async delete(id) {
315
+ assertId(id);
316
+ const result = await callHost(host, "db.delete", { id });
317
+ if (result !== null) throw new Error("Host db.delete must return null");
318
+ return result;
319
+ },
320
+ };
321
+ return Object.freeze(writer);
322
+ }