@segmentstream/ontology 0.149.0 → 0.150.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.150.0
4
+
5
+ The chat store's runtime routes take what the agent's dispatch needs: `release`, a change that gives
6
+ up a claim on a message before it was dispatched, so the next delivery of the message takes it at
7
+ once; a skipped message can be claimed, since a later revision of it may address the agent; a
8
+ `meta` change can name the meta it replaces in `expected`, and applies only while the message still
9
+ holds it; a `content` change sets what a channel read of a message after recording it, in one write with
10
+ its routing state and only while the message holds the `meta` the channel read: its text with what
11
+ was transcribed of it, such as a voice message's transcript after its caption, and the files it
12
+ stored, by their attachments' ids, never as an edit, and under a new revision; an `edit` may
13
+ carry its files, which replace the message's, and its revision's `meta` under the `meta` it
14
+ replaces, so an edit that only replaced a file is an edit, and an edit and its routing state are
15
+ one write; `messages/read` with `senderId` reads what a sender wrote in every chat of a
16
+ channel, newest first; and with `pending`, `pendingBefore` lists only the sends requested by a
17
+ time, chosen before the limit, so newer sends never crowd out older ones due (`pendingBefore`
18
+ without `pending` is refused, `pending_required`). The agent SDK uses the chat store only with an
19
+ ontology service that answers `release`.
20
+
21
+ A deleted message keeps none of its content in the channel's private `meta` either: a deletion
22
+ clears `meta` with the text, parts, files and reactions, a send that takes its echo's deletion
23
+ loses its `meta` too, and a `meta` change no longer applies to a deleted message. Its disposition
24
+ stays, so a deleted message never starts another turn.
25
+
3
26
  ## 0.149.0
4
27
 
5
28
  The ontology keeps the chats' messages in the workspace's own database: the system table
@@ -103,10 +103,20 @@ interface Target {
103
103
  readonly messageId: string;
104
104
  }
105
105
  /** One change to a message. `sent` finds its message by the send's `operation` instead. */
106
- export type ChatMessageChange = (Target & {
106
+ export type ChatMessageChange =
107
+ /**
108
+ * The person's edit, or the agent's of its own message. It may carry the revision's routing
109
+ * state, in the same write and only while the message holds the `meta` it replaces
110
+ * (`expected`, `null` for none), and its files, which replace the message's: an edit that only
111
+ * replaced a file is an edit too.
112
+ */
113
+ (Target & {
107
114
  readonly change: "edit";
108
115
  readonly text: string;
109
116
  readonly at?: string;
117
+ readonly meta?: unknown;
118
+ readonly expected?: unknown;
119
+ readonly files?: ReadonlyArray<ChatMessageFile>;
110
120
  }) | (Target & {
111
121
  readonly change: "delete";
112
122
  readonly at?: string;
@@ -132,9 +142,31 @@ export type ChatMessageChange = (Target & {
132
142
  readonly status: "sent" | "failed" | "uncertain";
133
143
  readonly providerMessageId?: string;
134
144
  readonly failure?: string;
135
- } | (Target & {
145
+ }
146
+ /** A claim given up before its message was dispatched: the message is unclaimed again. */
147
+ | (Target & {
148
+ readonly change: "release";
149
+ })
150
+ /**
151
+ * What a channel read of the message after recording it, with its routing state, in one write
152
+ * that applies only while the message holds the `meta` it replaces (`null` for none): its `text`
153
+ * with what was transcribed of it, such as a voice message's transcript after its caption, and
154
+ * its stored files, by their `_agent_attachments` rows. Never an edit: `edited_at` stays.
155
+ */
156
+ | (Target & {
157
+ readonly change: "content";
158
+ readonly meta: unknown;
159
+ readonly expected: unknown;
160
+ readonly text?: string;
161
+ readonly files?: ReadonlyArray<ChatMessageFile>;
162
+ }) | (Target & {
136
163
  readonly change: "meta";
137
164
  readonly meta: unknown;
165
+ /**
166
+ * The `meta` the change replaces, when present: it applies only while the message still holds
167
+ * it (`null` for none), so two writers of one message never lose each other's state.
168
+ */
169
+ readonly expected?: unknown;
138
170
  });
139
171
  /**
140
172
  * A place in a chat, newest first: messages before `at`, and at `at` those whose id sorts before
@@ -147,7 +179,9 @@ export interface ChatCursor {
147
179
  /** The cursor a page continues at; `undefined` for text that is none. */
148
180
  export declare function parseChatCursor(value: string): ChatCursor | undefined;
149
181
  export declare function chatCursorOf(message: Pick<ChatMessage, "at" | "id">): string;
150
- /** The runtime's reads of one chat, or with `pending` of every chat of a channel. */
182
+ /**
183
+ * The runtime's reads of one chat, or with `pending` or `senderId` of every chat of a channel.
184
+ */
151
185
  export interface ChatMessageQuery {
152
186
  readonly channel: string;
153
187
  readonly chatId?: string;
@@ -159,6 +193,10 @@ export interface ChatMessageQuery {
159
193
  readonly messageId?: string;
160
194
  /** Outbound messages still `pending`: sends still to deliver. */
161
195
  readonly pending?: boolean;
196
+ /** With `pending`, only the sends requested no later than this time (ISO 8601). */
197
+ readonly pendingBefore?: string;
198
+ /** The messages a sender wrote, such as the chat a person last wrote from. */
199
+ readonly senderId?: string;
162
200
  readonly limit: number;
163
201
  }
164
202
  /** A reader's search of one chat, as `chat_history` and `chat_search` ask it. */
@@ -312,6 +312,7 @@ export function sqlChatMessageStore(sql) {
312
312
  `"deleted_at" = coalesce($6::timestamptz, "deleted_at"), ` +
313
313
  `"parts" = CASE WHEN ${deleted} THEN '[]' ELSE "parts" END, ` +
314
314
  `"files" = CASE WHEN ${deleted} THEN '[]' ELSE "files" END, ` +
315
+ `"meta" = CASE WHEN ${deleted} THEN NULL ELSE "meta" END, ` +
315
316
  `"reactions" = CASE WHEN ${deleted} THEN '[]' ` +
316
317
  `WHEN coalesce($8::jsonb, '[]') <> '[]' THEN $8::jsonb ELSE "reactions" END, ` +
317
318
  `${revised} WHERE "id" = $1::uuid`, [
@@ -332,20 +333,40 @@ export function sqlChatMessageStore(sql) {
332
333
  case "edit": {
333
334
  const edited = params.add(input.text, "text");
334
335
  const at = `date_trunc('milliseconds', coalesce(${params.add(input.at ?? null, "timestamptz")}, now()))`;
336
+ const files = input.files === undefined ? `"files"` : params.add(JSON.stringify(input.files), "jsonb");
337
+ const meta = input.meta === undefined ? `"meta"` : params.add(JSON.stringify(input.meta), "jsonb");
338
+ // The routing state of the revision goes with it, only while the message holds what the
339
+ // writer read.
340
+ const guarded = input.meta === undefined
341
+ ? []
342
+ : [
343
+ `coalesce("meta", 'null'::jsonb) = ${params.add(JSON.stringify(input.expected ?? null), "jsonb")}`,
344
+ ];
335
345
  // An edit older than the one applied, a late or retried delivery, changes nothing.
336
- return update(input, params, [`"text" = ${edited}`, `"edited_at" = ${at}`, revised], [
346
+ return update(input, params, [
347
+ `"text" = ${edited}`,
348
+ `"files" = ${files}`,
349
+ `"meta" = ${meta}`,
350
+ `"edited_at" = ${at}`,
351
+ revised,
352
+ ], [
337
353
  `"deleted_at" IS NULL`,
338
- `"text" IS DISTINCT FROM ${edited}`,
354
+ `("text" IS DISTINCT FROM ${edited} OR "files" IS DISTINCT FROM ${files} ` +
355
+ `OR "meta" IS DISTINCT FROM ${meta})`,
339
356
  `("edited_at" IS NULL OR "edited_at" <= ${at})`,
357
+ ...guarded,
340
358
  ]);
341
359
  }
342
360
  case "delete":
343
- // The person retracted it: its content goes, the row stays as the message's place.
361
+ // The person retracted it: its content goes, the row stays as the message's place. The
362
+ // channel's `meta` goes with it: it holds the message's file references and what a turn
363
+ // read of it, and the dispatch fence that outlives the deletion is the disposition.
344
364
  return update(input, params, [
345
365
  `"text" = NULL`,
346
366
  `"parts" = '[]'`,
347
367
  `"files" = '[]'`,
348
368
  `"reactions" = '[]'`,
369
+ `"meta" = NULL`,
349
370
  `"deleted_at" = date_trunc('milliseconds', coalesce(${params.add(input.at ?? null, "timestamptz")}, now()))`,
350
371
  revised,
351
372
  ], [`"deleted_at" IS NULL`]);
@@ -396,9 +417,11 @@ export function sqlChatMessageStore(sql) {
396
417
  const unchanged = `"reason" IS NOT DISTINCT FROM coalesce(${reason}, "reason") ` +
397
418
  `AND "session_id" IS NOT DISTINCT FROM coalesce(${session}, "session_id") ` +
398
419
  `AND "turn_id" IS NOT DISTINCT FROM coalesce(${turn}, "turn_id")`;
399
- // The dispatch fence: one conditional update, so only one caller's claim returns the row.
420
+ // The dispatch fence: one conditional update, so only one caller's claim returns the row. A
421
+ // skipped message can still be taken: a later revision of it may address the agent.
400
422
  const allowed = {
401
- claimed: `("disposition" IS NULL OR ("disposition" = 'claimed' AND ${expired}))`,
423
+ claimed: `("disposition" IS NULL OR "disposition" = 'skipped' ` +
424
+ `OR ("disposition" = 'claimed' AND ${expired}))`,
402
425
  turn: `("disposition" IS NULL OR "disposition" = 'claimed' ` +
403
426
  `OR ("disposition" = 'turn' AND NOT (${unchanged})))`,
404
427
  skipped: `("disposition" IS NULL OR ("disposition" = 'claimed' AND ${expired}) ` +
@@ -408,10 +431,33 @@ export function sqlChatMessageStore(sql) {
408
431
  }
409
432
  case "sent":
410
433
  return sent(input);
434
+ case "content": {
435
+ const meta = params.add(JSON.stringify(input.meta), "jsonb");
436
+ const expected = params.add(JSON.stringify(input.expected ?? null), "jsonb");
437
+ const text = input.text === undefined ? `"text"` : params.add(input.text, "text");
438
+ const files = input.files === undefined ? `"files"` : params.add(JSON.stringify(input.files), "jsonb");
439
+ // What a channel read of a message is read with it, so it takes a new revision: a reader
440
+ // that read the message before learns what was read of it.
441
+ return update(input, params, [`"meta" = ${meta}`, `"text" = ${text}`, `"files" = ${files}`, revised], [
442
+ `"deleted_at" IS NULL`,
443
+ `coalesce("meta", 'null'::jsonb) = ${expected}`,
444
+ `("meta" IS DISTINCT FROM ${meta} OR "text" IS DISTINCT FROM ${text} ` +
445
+ `OR "files" IS DISTINCT FROM ${files})`,
446
+ ]);
447
+ }
448
+ case "release":
449
+ // Only a claim is given up: a turn or a skip stays as it is.
450
+ return update(input, params, [`"disposition" = NULL`, `"reason" = NULL`, `"disposition_at" = now()`, revised], [`"direction" = 'inbound'`, `"disposition" = 'claimed'`]);
411
451
  case "meta": {
412
452
  const meta = params.add(JSON.stringify(input.meta), "jsonb");
453
+ // A deleted message keeps no routing state: nothing writes its content back.
454
+ const guard = [`"deleted_at" IS NULL`, `"meta" IS DISTINCT FROM ${meta}`];
455
+ if ("expected" in input) {
456
+ // Compare and set; no meta and JSON's null are alike.
457
+ guard.push(`coalesce("meta", 'null'::jsonb) = ${params.add(JSON.stringify(input.expected ?? null), "jsonb")}`);
458
+ }
413
459
  // Channel-private routing state: no reader sees it, so it takes no revision.
414
- return update(input, params, [`"meta" = ${meta}`], [`"meta" IS DISTINCT FROM ${meta}`]);
460
+ return update(input, params, [`"meta" = ${meta}`], guard);
415
461
  }
416
462
  }
417
463
  };
@@ -431,6 +477,13 @@ export function sqlChatMessageStore(sql) {
431
477
  }
432
478
  if (input.pending === true) {
433
479
  conditions.push(`"direction" = 'outbound'`, `"status" = 'pending'`);
480
+ // Before the limit, so newer sends never fill a page ahead of older ones due.
481
+ if (input.pendingBefore !== undefined) {
482
+ conditions.push(`"at" <= ${params.add(input.pendingBefore, "timestamptz")}`);
483
+ }
484
+ }
485
+ if (input.senderId !== undefined) {
486
+ conditions.push(`"sender_id" = ${params.add(input.senderId)}`);
434
487
  }
435
488
  return page(conditions, params, input);
436
489
  };
@@ -37,6 +37,14 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
37
37
  readonly change: Schema.Literal<"edit">;
38
38
  readonly text: Schema.String;
39
39
  readonly at: Schema.optionalKey<Schema.String>;
40
+ readonly meta: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
41
+ readonly expected: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
42
+ readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
43
+ readonly id: Schema.String;
44
+ readonly name: Schema.optionalKey<Schema.String>;
45
+ readonly type: Schema.optionalKey<Schema.String>;
46
+ readonly size: Schema.optionalKey<Schema.Int>;
47
+ }>>>;
40
48
  readonly channel: Schema.String;
41
49
  readonly chatId: Schema.String;
42
50
  readonly messageId: Schema.String;
@@ -77,9 +85,29 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
77
85
  readonly status: Schema.Literals<readonly ["sent", "failed", "uncertain"]>;
78
86
  readonly providerMessageId: Schema.optionalKey<Schema.String>;
79
87
  readonly failure: Schema.optionalKey<Schema.String>;
88
+ }>, Schema.Struct<{
89
+ readonly change: Schema.Literal<"release">;
90
+ readonly channel: Schema.String;
91
+ readonly chatId: Schema.String;
92
+ readonly messageId: Schema.String;
93
+ }>, Schema.Struct<{
94
+ readonly change: Schema.Literal<"content">;
95
+ readonly meta: Schema.Codec<Schema.Json, Schema.Json, never, never>;
96
+ readonly expected: Schema.Codec<Schema.Json, Schema.Json, never, never>;
97
+ readonly text: Schema.optionalKey<Schema.String>;
98
+ readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
99
+ readonly id: Schema.String;
100
+ readonly name: Schema.optionalKey<Schema.String>;
101
+ readonly type: Schema.optionalKey<Schema.String>;
102
+ readonly size: Schema.optionalKey<Schema.Int>;
103
+ }>>>;
104
+ readonly channel: Schema.String;
105
+ readonly chatId: Schema.String;
106
+ readonly messageId: Schema.String;
80
107
  }>, Schema.Struct<{
81
108
  readonly change: Schema.Literal<"meta">;
82
109
  readonly meta: Schema.Codec<Schema.Json, Schema.Json, never, never>;
110
+ readonly expected: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
83
111
  readonly channel: Schema.String;
84
112
  readonly chatId: Schema.String;
85
113
  readonly messageId: Schema.String;
@@ -87,7 +115,9 @@ export declare const ChatMessageChangeRequest: Schema.Union<readonly [Schema.Str
87
115
  /**
88
116
  * `POST /api/ontology/agent/chats/messages/read`: one chat's messages, newest first, before a
89
117
  * cursor; or those changed after a revision; or one by its provider id; or, with `pending`, the
90
- * sends still to deliver, of every chat of the channel unless `chatId` names one.
118
+ * sends still to deliver, of every chat of the channel unless `chatId` names one, and with
119
+ * `pendingBefore` only those requested by then; or, with `senderId`, what a sender wrote, newest
120
+ * first, in every chat of the channel unless `chatId` names one.
91
121
  */
92
122
  export declare const ChatMessageReadRequest: Schema.Struct<{
93
123
  readonly channel: Schema.String;
@@ -97,6 +127,8 @@ export declare const ChatMessageReadRequest: Schema.Struct<{
97
127
  readonly before: Schema.optionalKey<Schema.String>;
98
128
  readonly messageId: Schema.optionalKey<Schema.String>;
99
129
  readonly pending: Schema.optionalKey<Schema.Boolean>;
130
+ readonly pendingBefore: Schema.optionalKey<Schema.String>;
131
+ readonly senderId: Schema.optionalKey<Schema.String>;
100
132
  readonly limit: Schema.optionalKey<Schema.Int>;
101
133
  }>;
102
134
  type Answer = Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
@@ -62,6 +62,10 @@ export const ChatMessageChangeRequest = Schema.Union([
62
62
  change: Schema.Literal("edit"),
63
63
  text: Schema.String.check(Schema.isMaxLength(100_000)),
64
64
  at: Schema.optionalKey(Instant),
65
+ // The revision's routing state, while the message holds `expected`, and its files.
66
+ meta: Schema.optionalKey(BoundedJson),
67
+ expected: Schema.optionalKey(BoundedJson),
68
+ files: Schema.optionalKey(Schema.Array(ChatFile).check(Schema.isMaxLength(50))),
65
69
  }),
66
70
  Schema.Struct({ ...Target, change: Schema.Literal("delete"), at: Schema.optionalKey(Instant) }),
67
71
  Schema.Struct({
@@ -95,12 +99,32 @@ export const ChatMessageChangeRequest = Schema.Union([
95
99
  providerMessageId: Schema.optionalKey(MessageId),
96
100
  failure: Schema.optionalKey(Code),
97
101
  }),
98
- Schema.Struct({ ...Target, change: Schema.Literal("meta"), meta: BoundedJson }),
102
+ // A claim given up before its message was dispatched.
103
+ Schema.Struct({ ...Target, change: Schema.Literal("release") }),
104
+ // What a channel read of the message after recording it: its text with what was transcribed
105
+ // of it, its stored files and its routing state, while the message holds the meta it replaces.
106
+ Schema.Struct({
107
+ ...Target,
108
+ change: Schema.Literal("content"),
109
+ meta: BoundedJson,
110
+ expected: BoundedJson,
111
+ text: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(100_000))),
112
+ files: Schema.optionalKey(Schema.Array(ChatFile).check(Schema.isMaxLength(50))),
113
+ }),
114
+ Schema.Struct({
115
+ ...Target,
116
+ change: Schema.Literal("meta"),
117
+ meta: BoundedJson,
118
+ // Compare and set: the change applies only while the message holds this meta.
119
+ expected: Schema.optionalKey(BoundedJson),
120
+ }),
99
121
  ]);
100
122
  /**
101
123
  * `POST /api/ontology/agent/chats/messages/read`: one chat's messages, newest first, before a
102
124
  * cursor; or those changed after a revision; or one by its provider id; or, with `pending`, the
103
- * sends still to deliver, of every chat of the channel unless `chatId` names one.
125
+ * sends still to deliver, of every chat of the channel unless `chatId` names one, and with
126
+ * `pendingBefore` only those requested by then; or, with `senderId`, what a sender wrote, newest
127
+ * first, in every chat of the channel unless `chatId` names one.
104
128
  */
105
129
  export const ChatMessageReadRequest = Schema.Struct({
106
130
  channel: Provider,
@@ -110,6 +134,8 @@ export const ChatMessageReadRequest = Schema.Struct({
110
134
  before: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(128))),
111
135
  messageId: Schema.optionalKey(MessageId),
112
136
  pending: Schema.optionalKey(Schema.Boolean),
137
+ pendingBefore: Schema.optionalKey(Instant),
138
+ senderId: Schema.optionalKey(Text(256)),
113
139
  limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))),
114
140
  });
115
141
  function json(body) {
@@ -194,9 +220,12 @@ export function readChatMessages(store) {
194
220
  if (before !== undefined && cursor === undefined) {
195
221
  return refused(requestId, 400, "invalid_cursor");
196
222
  }
197
- if (input.chatId === undefined && input.pending !== true) {
223
+ if (input.chatId === undefined && input.pending !== true && input.senderId === undefined) {
198
224
  return refused(requestId, 400, "chat_required");
199
225
  }
226
+ if (input.pendingBefore !== undefined && input.pending !== true) {
227
+ return refused(requestId, 400, "pending_required");
228
+ }
200
229
  const modes = [input.after, input.messageId, input.pending === true ? true : undefined];
201
230
  if (modes.filter((mode) => mode !== undefined).length > 1 ||
202
231
  (input.after !== undefined && cursor !== undefined)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.149.0",
3
+ "version": "0.150.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",