@segmentstream/ontology 0.121.0 → 0.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +9 -1
  3. package/dist/action.d.ts +11 -6
  4. package/dist/analyze.d.ts +3 -2
  5. package/dist/analyze.js +21 -10
  6. package/dist/app-feedback.js +6 -5
  7. package/dist/chat.d.ts +2 -1
  8. package/dist/index.d.ts +2 -0
  9. package/dist/index.js +2 -0
  10. package/dist/migrate/apply.js +5 -17
  11. package/dist/replication/baseline.d.ts +1 -2
  12. package/dist/replication/baseline.js +3 -2
  13. package/dist/replication/legacy-baseline.d.ts +1 -2
  14. package/dist/replication/legacy-baseline.js +3 -6
  15. package/dist/replication/migrate.d.ts +1 -10
  16. package/dist/replication/migrate.js +0 -37
  17. package/dist/replication/model.d.ts +6 -9
  18. package/dist/replication/model.js +13 -47
  19. package/dist/replication/schema.js +3 -0
  20. package/dist/replication/shadow.d.ts +7 -3
  21. package/dist/replication/shadow.js +9 -9
  22. package/dist/replication/store.d.ts +6 -2
  23. package/dist/replication/store.js +21 -46
  24. package/dist/runtime/agents.js +58 -0
  25. package/dist/runtime/service-binding.d.ts +5 -1
  26. package/dist/runtime/service-binding.js +14 -5
  27. package/dist/service/agent/chat-archive.d.ts +2 -1
  28. package/dist/service/agent/chat-archive.js +12 -8
  29. package/dist/service/agent/web-tokens.js +9 -1
  30. package/dist/service/chat/reads.js +5 -1
  31. package/dist/service/mcp/server.js +5 -5
  32. package/dist/service/mcp/tools.js +7 -3
  33. package/dist/service/runtime-contract.d.ts +7 -0
  34. package/dist/storage/memory.d.ts +100 -0
  35. package/dist/storage/memory.js +281 -0
  36. package/dist/storage/sessions.d.ts +2 -2
  37. package/package.json +1 -1
@@ -0,0 +1,281 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { Effect, Redacted, Stream } from "effect";
3
+ import { isSqlError } from "effect/unstable/sql/SqlError";
4
+ import { nameToWire } from "../authoring-names.js";
5
+ import { ActionRejected, Conflict } from "../errors.js";
6
+ import { OntologyBackend } from "../service/runtime-contract.js";
7
+ import { BlobStorageError, } from "./provider.js";
8
+ /** A reserved domain: the grants a store signs, under its own host, never reach a network. */
9
+ const DOMAIN = "files.invalid";
10
+ /** How long storage honours a part upload grant and a download grant, as deployed storage does. */
11
+ const PART_GRANT_SECONDS = 300;
12
+ const DOWNLOAD_GRANT_SECONDS = 60;
13
+ /** The bytes `readPrefix` returns, which completion sniffs. */
14
+ const PREFIX_BYTES = 512;
15
+ const DEFAULT_QUOTA_BYTES = 1024 * 1024 * 1024;
16
+ /** The stores `memoryFileStorage` made, by the binding it handed out. */
17
+ const stores = new WeakMap();
18
+ /** The in-memory store `blobStorage` names, when `memoryFileStorage` made it. */
19
+ export function memoryFileStore(blobStorage) {
20
+ return blobStorage === undefined ? undefined : stores.get(blobStorage);
21
+ }
22
+ function failure(operation, message) {
23
+ return new BlobStorageError({ operation, cause: new Error(message) });
24
+ }
25
+ function sha256(bytes) {
26
+ return createHash("sha256").update(bytes).digest("hex");
27
+ }
28
+ function concat(chunks) {
29
+ const bytes = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
30
+ let offset = 0;
31
+ for (const chunk of chunks) {
32
+ bytes.set(chunk, offset);
33
+ offset += chunk.byteLength;
34
+ }
35
+ return bytes;
36
+ }
37
+ function text(status, body) {
38
+ return new Response(body, { status, headers: { "content-type": "text/plain" } });
39
+ }
40
+ /** The provider and the transfer endpoint of one store: the multipart lifecycle of object storage. */
41
+ function memoryStore(binding) {
42
+ const objects = new Map();
43
+ const uploads = new Map();
44
+ const grants = new Map();
45
+ const sign = (grant, method) => {
46
+ const token = randomUUID();
47
+ grants.set(token, grant);
48
+ return {
49
+ url: `${binding.endpoint}/${encodeURIComponent(grant.key)}?grant=${token}`,
50
+ method,
51
+ headers: {},
52
+ expiresAt: new Date(grant.expiresAt).toISOString(),
53
+ };
54
+ };
55
+ const upload = (operation, key, uploadId) => Effect.suspend(() => {
56
+ const pending = uploads.get(uploadId);
57
+ return pending?.key === key
58
+ ? Effect.succeed(pending)
59
+ : Effect.fail(failure(operation, "No such multipart upload."));
60
+ });
61
+ const object = (operation, key) => Effect.suspend(() => {
62
+ const stored = objects.get(key);
63
+ return stored ? Effect.succeed(stored) : Effect.fail(failure(operation, "No such object."));
64
+ });
65
+ const provider = {
66
+ binding,
67
+ initiate: ({ key, contentType, sessionId }) => Effect.sync(() => {
68
+ const uploadId = randomUUID();
69
+ uploads.set(uploadId, { key, contentType, sessionId, parts: new Map() });
70
+ return uploadId;
71
+ }),
72
+ signPart: ({ key, uploadId, partNumber, size }) => upload("blob.sign_part", key, uploadId).pipe(Effect.map(() => sign({
73
+ kind: "part",
74
+ key,
75
+ uploadId,
76
+ partNumber,
77
+ size,
78
+ expiresAt: Date.now() + PART_GRANT_SECONDS * 1000,
79
+ }, "PUT"))),
80
+ parts: ({ key, uploadId }) => upload("blob.parts", key, uploadId).pipe(Effect.map((pending) => [...pending.parts]
81
+ .sort(([left], [right]) => left - right)
82
+ .map(([number, part]) => ({ number, size: part.size, etag: part.etag })))),
83
+ complete: ({ key, uploadId, parts }) => upload("blob.complete", key, uploadId).pipe(Effect.flatMap((pending) => {
84
+ const chunks = parts.map((part) => {
85
+ const stored = pending.parts.get(part.number);
86
+ return stored?.etag === part.etag ? stored.bytes : undefined;
87
+ });
88
+ if (parts.length === 0 || chunks.some((chunk) => chunk === undefined)) {
89
+ return Effect.fail(failure("blob.complete", "The parts do not match the upload."));
90
+ }
91
+ return Effect.sync(() => {
92
+ const bytes = concat(chunks);
93
+ objects.set(key, {
94
+ bytes,
95
+ size: bytes.byteLength,
96
+ contentType: pending.contentType,
97
+ sessionId: pending.sessionId,
98
+ });
99
+ uploads.delete(uploadId);
100
+ });
101
+ })),
102
+ inspect: (key) => Effect.sync(() => {
103
+ const stored = objects.get(key);
104
+ return stored
105
+ ? { size: stored.size, contentType: stored.contentType, sessionId: stored.sessionId }
106
+ : undefined;
107
+ }),
108
+ sha256: (key, size) => object("blob.sha256", key).pipe(Effect.flatMap((stored) => stored.size === size
109
+ ? Effect.succeed(sha256(stored.bytes))
110
+ : Effect.fail(failure("blob.sha256", "The object does not match its declared size.")))),
111
+ readPrefix: (key) => object("blob.read_prefix", key).pipe(Effect.map((stored) => stored.bytes.slice(0, PREFIX_BYTES))),
112
+ read: (key, maxBytes) => object("blob.read", key).pipe(Effect.flatMap((stored) => stored.size <= maxBytes
113
+ ? Effect.succeed(stored.bytes.slice())
114
+ : Effect.fail(failure("blob.read", "The object exceeds the size it may have.")))),
115
+ download: ({ key, contentType }) => object("blob.download", key).pipe(Effect.map(() => sign({
116
+ kind: "download",
117
+ key,
118
+ contentType,
119
+ expiresAt: Date.now() + DOWNLOAD_GRANT_SECONDS * 1000,
120
+ }, "GET"))),
121
+ abort: ({ key, uploadId }) => Effect.sync(() => {
122
+ if (uploads.get(uploadId)?.key === key) {
123
+ uploads.delete(uploadId);
124
+ }
125
+ }),
126
+ remove: (key) => Effect.sync(() => {
127
+ objects.delete(key);
128
+ }),
129
+ pending: (key) => Effect.sync(() => [...uploads].flatMap(([uploadId, pending]) => (pending.key === key ? [uploadId] : []))),
130
+ };
131
+ const transfer = async (input, init) => {
132
+ const request = input instanceof Request ? input : undefined;
133
+ const url = new URL(request?.url ?? (input instanceof URL ? input.href : String(input)));
134
+ const method = (init?.method ?? request?.method ?? "GET").toUpperCase();
135
+ (init?.signal ?? request?.signal)?.throwIfAborted();
136
+ const grant = url.origin === binding.endpoint ? grants.get(url.searchParams.get("grant") ?? "") : undefined;
137
+ if (grant === undefined ||
138
+ grant.key !== decodeURIComponent(url.pathname.slice(1)) ||
139
+ grant.expiresAt <= Date.now() ||
140
+ method !== (grant.kind === "part" ? "PUT" : "GET")) {
141
+ return text(403, "The transfer grant is not valid for this request.");
142
+ }
143
+ if (grant.kind === "download") {
144
+ const stored = objects.get(grant.key);
145
+ return stored
146
+ ? new Response(stored.bytes.slice(), {
147
+ status: 200,
148
+ headers: {
149
+ "content-type": grant.contentType,
150
+ "content-length": String(stored.size),
151
+ },
152
+ })
153
+ : text(404, "No such object.");
154
+ }
155
+ const bytes = new Uint8Array(await new Response(init?.body ?? request?.body).arrayBuffer());
156
+ const pending = uploads.get(grant.uploadId);
157
+ if (pending === undefined) {
158
+ return text(404, "No such multipart upload.");
159
+ }
160
+ // The grant signs the part's length; storage refuses any other.
161
+ if (bytes.byteLength !== grant.size) {
162
+ return text(400, "The body does not match the signed content length.");
163
+ }
164
+ const etag = `"${sha256(bytes).slice(0, 32)}"`;
165
+ pending.parts.set(grant.partNumber, { size: bytes.byteLength, etag, bytes });
166
+ return new Response(null, { status: 200, headers: { etag } });
167
+ };
168
+ return { provider, fetch: transfer };
169
+ }
170
+ /**
171
+ * File storage held in memory, for tests that run an ontology's actions with files in process:
172
+ * `uploads.for` inputs, `Files.stage`, `Files.open`, downloads and the agent's attachments. Each
173
+ * call makes an empty store.
174
+ *
175
+ * ```ts
176
+ * const files = memoryFileStorage();
177
+ * const backend = backendLayer(ontology, files.blobStorage).pipe(Layer.provide(database));
178
+ * ```
179
+ */
180
+ export function memoryFileStorage(options = {}) {
181
+ const quotaBytes = options.quotaBytes ?? DEFAULT_QUOTA_BYTES;
182
+ if (!Number.isSafeInteger(quotaBytes) || quotaBytes <= 0) {
183
+ throw new Error("memoryFileStorage takes a positive integer quotaBytes.");
184
+ }
185
+ const secret = randomUUID();
186
+ // Each store is a branch of its own: files another store holds are not found in this one.
187
+ const branchId = `memory-${secret.slice(0, 8)}`;
188
+ const binding = {
189
+ projectId: "memory",
190
+ branchId,
191
+ endpoint: `https://${branchId}.${DOMAIN}`,
192
+ region: "memory",
193
+ bucket: "ontology-files",
194
+ accessKeyId: `memory-key-${secret}`,
195
+ secretAccessKey: `memory-secret-${secret}`,
196
+ quotaBytes,
197
+ };
198
+ const store = memoryStore(binding);
199
+ const blobStorage = Redacted.make(binding, { label: "memoryFileStorage" });
200
+ stores.set(blobStorage, store);
201
+ const blobsOf = Effect.gen(function* () {
202
+ const backend = yield* OntologyBackend;
203
+ if (backend.blobs === undefined) {
204
+ return yield* Effect.die(new Error("The ontology backend has no file storage. Build it on this store: " +
205
+ "backendLayer(ontology, files.blobStorage)."));
206
+ }
207
+ return backend.blobs;
208
+ });
209
+ // Storage and database failures are defects of the test's setup, not outcomes of the action.
210
+ const expected = (effect) => effect.pipe(Effect.catchIf((error) => isSqlError(error) || error instanceof BlobStorageError, (error) => Effect.die(error)));
211
+ return {
212
+ blobStorage,
213
+ fetch: store.fetch,
214
+ upload: (input) => expected(Effect.gen(function* () {
215
+ const blobs = yield* blobsOf;
216
+ const bytes = typeof input.bytes === "string" ? new TextEncoder().encode(input.bytes) : input.bytes;
217
+ const idempotencyKey = input.idempotencyKey ?? randomUUID();
218
+ const createIntent = input.recordId === undefined ? (input.createIntent ?? idempotencyKey) : undefined;
219
+ let session = yield* blobs.begin({
220
+ entity: nameToWire(input.entity),
221
+ property: nameToWire(input.property),
222
+ action: nameToWire(input.action),
223
+ ...(input.recordId === undefined ? {} : { recordId: input.recordId }),
224
+ ...(createIntent === undefined ? {} : { createIntent }),
225
+ idempotencyKey,
226
+ filename: input.filename,
227
+ contentType: input.contentType,
228
+ size: bytes.byteLength,
229
+ }, input.principal);
230
+ if (session.ticket === undefined) {
231
+ if (session.state !== "completing") {
232
+ const grant = yield* blobs.part(session.id, input.principal);
233
+ if (!grant.url.startsWith(`${binding.endpoint}/`)) {
234
+ return yield* Effect.die(new Error("The ontology backend stores files elsewhere. Build it on this store: " +
235
+ "backendLayer(ontology, files.blobStorage)."));
236
+ }
237
+ const response = yield* Effect.promise(() => store.fetch(grant.url, {
238
+ method: grant.method,
239
+ headers: grant.headers,
240
+ // A copy typed as an ArrayBuffer view: fetch's BodyInit refuses a view of any ArrayBufferLike.
241
+ body: new Uint8Array(bytes),
242
+ }));
243
+ if (!response.ok) {
244
+ return yield* new ActionRejected({
245
+ message: "file_transfer_failed",
246
+ cause: {
247
+ status: response.status,
248
+ detail: yield* Effect.promise(() => response.text()),
249
+ },
250
+ });
251
+ }
252
+ }
253
+ session = yield* blobs.complete(session.id, input.principal);
254
+ }
255
+ if (session.ticket === undefined) {
256
+ return yield* new Conflict({ entity: "upload", message: "The upload is not ready." });
257
+ }
258
+ return {
259
+ ticket: session.ticket,
260
+ options: { idempotencyKey, ...(createIntent === undefined ? {} : { createIntent }) },
261
+ };
262
+ })),
263
+ read: (input) => expected(Effect.gen(function* () {
264
+ const blobs = yield* blobsOf;
265
+ if (blobs.files === undefined) {
266
+ return yield* Effect.die(new Error("The ontology backend's file storage does not open files."));
267
+ }
268
+ const files = blobs.files({ principal: input.principal });
269
+ return yield* Effect.scoped(Effect.gen(function* () {
270
+ const opened = yield* files.open({
271
+ entity: nameToWire(input.entity),
272
+ id: input.id,
273
+ property: nameToWire(input.property),
274
+ ...(input.revisionId === undefined ? {} : { revisionId: input.revisionId }),
275
+ });
276
+ const chunks = yield* Stream.runCollect(opened.body);
277
+ return { file: opened.file, bytes: concat([...chunks]) };
278
+ }));
279
+ })),
280
+ };
281
+ }
@@ -160,12 +160,12 @@ export declare function blobRuntime(ontology: Ontology, sql: SqlClient.SqlClient
160
160
  expiresAt: string;
161
161
  }, import("../errors.js").PermissionDenied | Conflict | NotFound | SqlError, never>;
162
162
  download: (entityName: string, recordId: string, propertyName: string, input: {
163
- readonly inline?: boolean | undefined;
164
163
  readonly revisionId?: string | undefined;
164
+ readonly inline?: boolean | undefined;
165
165
  }, principal: Principal) => Effect.Effect<import("./provider.js").TransferGrant, import("../errors.js").PermissionDenied | NotFound | SqlError | BlobStorageError, never>;
166
166
  downloadFile: (entityName: string, recordId: string, propertyName: string, input: {
167
- readonly inline?: boolean | undefined;
168
167
  readonly revisionId?: string | undefined;
168
+ readonly inline?: boolean | undefined;
169
169
  }, principal: Principal) => Effect.Effect<{
170
170
  file: {
171
171
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.121.0",
3
+ "version": "0.123.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",