@segmentstream/ontology 0.188.0 → 0.189.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.189.1
4
+
5
+ `segmentstream-ontology check` first compares its own release with the one the component's
6
+ `package-lock.json` pins, which a deployment installs. When they differ, as after a `git pull`
7
+ that brings a new lockfile without reinstalling `node_modules`, it checks nothing and says so,
8
+ naming both releases and the reinstall command, such as `npm --prefix ontology ci`. Before, it
9
+ judged the new code by the installed release's rules and could report errors, such as a lower
10
+ limit, that the deployment does not have.
11
+
12
+ ## 0.189.0
13
+
14
+ A staff read of a chat may ask for what the agent kept in it for staff.
15
+ `POST /api/ontology/chat/history` and the MCP tool `chat_history` take `internal: true`, which also
16
+ returns the chat's internal messages from the workspace's chat store, never sent: the agent's
17
+ `note` for staff on a turn's `reply` and the questions it could not answer
18
+ (`segmentstream__unanswered`), as events of kind `internal` with their `sessionId` and `turnId`.
19
+ Only a member or workflow whose `agent_chat:read`, within its scope, holds the private chat it
20
+ reads by its `agent_chat` id receives them. Every other read, the chat's own person's, a group's
21
+ and a search's among them, leaves them out whether it asks or not, and a read that does not ask
22
+ answers as before.
23
+
3
24
  ## 0.188.0
4
25
 
5
26
  List, search and read deployed workspace code with the current member’s explicit
package/README.md CHANGED
@@ -1642,14 +1642,17 @@ history_recorded }`; private chats may have no URL. A receipt-write failure leav
1642
1642
  `history_recorded: false` without sending again. An older archive lacking the claim protocol
1643
1643
  cannot authorize delivery. Local provider proxies alone cannot replace the production archive.
1644
1644
 
1645
- `chat_history({ chat, before?, after?, limit? })` and `chat_search` read a chat with independent
1645
+ `chat_history({ chat, before?, after?, limit?, internal? })` and `chat_search` read a chat with independent
1646
1646
  chat authorization: a member reads the group chats they are in (the chat's `members`,
1647
1647
  like its attachments), `agent_chat:read` reads every group, and a private message is read by the
1648
1648
  participants it names. A posting service cannot read member chats. They read the workspace's
1649
1649
  `_chat_messages` once it holds the chat, with each message's `direction`, `author`, `sender`,
1650
1650
  `parts`, `files`, `reply_to`, `reactions`, `edited`, `deleted`, `delivery`, `disposition` and
1651
1651
  `reason` beside the archive's fields, and the platform's chat archive before; `after`, a revision,
1652
- reads the chat's changes since. `chat.retentionDays` (1–3650, 365 by default) sets how long the
1652
+ reads the chat's changes since. `internal: true` also returns the agent's internal messages, never
1653
+ sent (its notes for staff and the questions it could not answer), to a member or workflow whose
1654
+ `agent_chat:read` holds the private chat it reads by its `agent_chat` id, and to no other reader.
1655
+ `chat.retentionDays` (1–3650, 365 by default) sets how long the
1653
1656
  workspace keeps them. The canonical
1654
1657
  REST facade is `/api/ontology/chat/{list,history,search}`, and `send` is
1655
1658
  `POST /api/ontology/agent_chat/actions/send`, with the standard
@@ -1790,6 +1793,9 @@ npx segmentstream-ontology migrate [entry] # plan and apply the migrat
1790
1793
  ```
1791
1794
 
1792
1795
  - `check` prints errors and warnings on stderr with their paths. It fails on any error.
1796
+ When the folder's `package-lock.json` pins another release of the SDK than the one installed,
1797
+ which a deployment would install instead, `check` judges nothing and names the reinstall
1798
+ command, such as `npm --prefix ontology ci`.
1793
1799
  - `migrate` checks the ontology, reads the catalog recorded in the database, plans the
1794
1800
  migration and applies it with the planner and applier the deploy pipeline uses. Use
1795
1801
  the owner connection string (`ontology_owner`, direct connection) of a Neon development
@@ -10,6 +10,11 @@ export interface CheckInput {
10
10
  export interface CheckDependencies {
11
11
  readonly load: OntologyLoader;
12
12
  readonly output: Output;
13
+ /**
14
+ * Why this SDK must not judge the ontology at an entry, such as another release pinned in the
15
+ * project's lockfile; see `lockedReleaseMismatch`. Without it, nothing is compared.
16
+ */
17
+ readonly lockedRelease?: (entry: string) => Promise<string | undefined>;
13
18
  }
14
19
  type Loaded = Extract<LoadResult, {
15
20
  readonly _tag: "Loaded";
package/dist/bin/check.js CHANGED
@@ -78,6 +78,13 @@ export async function loadCheckedOntology(entry, dependencies) {
78
78
  */
79
79
  export async function checkCommand(input, dependencies) {
80
80
  const { output } = dependencies;
81
+ // Checked by another release than a deployment installs, the ontology could fail on rules the
82
+ // deployment does not have, or pass ones it does.
83
+ const mismatch = await dependencies.lockedRelease?.(input.entry);
84
+ if (mismatch !== undefined) {
85
+ output.stderr(`${mismatch}\n`);
86
+ return EXIT_CODES.failed;
87
+ }
81
88
  const loaded = await loadCheckedOntology(input.entry, dependencies);
82
89
  if (loaded === undefined) {
83
90
  return EXIT_CODES.failed;
@@ -0,0 +1,23 @@
1
+ /** The SDK's name, as a project's package-lock.json lists it. */
2
+ export declare const SDK_PACKAGE = "@segmentstream/ontology";
3
+ /** Reads a file's text, or undefined when there is none. */
4
+ export type ReadText = (path: string) => Promise<string | undefined>;
5
+ /**
6
+ * Why this SDK must not check the ontology at `entry`: its package's package-lock.json pins
7
+ * another release of the SDK, the one a deployment installs. That happens after a pull brings a
8
+ * new lockfile and node_modules is not reinstalled; the check would then judge the ontology by an
9
+ * older or newer release's rules. Undefined when they agree, when the package has no
10
+ * package-lock.json, and for an unreleased build of the SDK (version 0.0.0).
11
+ */
12
+ export declare function lockedReleaseMismatch(input: {
13
+ readonly entry: string;
14
+ readonly cwd: string;
15
+ /**
16
+ * Where the person or agent ran the command, which the reinstall command is relative to:
17
+ * `npm --prefix ontology run check` runs in ontology/ but is typed above it. Defaults to `cwd`.
18
+ */
19
+ readonly invokedFrom?: string | undefined;
20
+ /** The version of the SDK running this command. */
21
+ readonly version: string | undefined;
22
+ readonly read: ReadText;
23
+ }): Promise<string | undefined>;
@@ -0,0 +1,62 @@
1
+ import { dirname, join, relative, resolve } from "node:path";
2
+ /** The SDK's name, as a project's package-lock.json lists it. */
3
+ export const SDK_PACKAGE = "@segmentstream/ontology";
4
+ function record(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value)
6
+ ? value
7
+ : undefined;
8
+ }
9
+ function parsed(text) {
10
+ if (text === undefined) {
11
+ return undefined;
12
+ }
13
+ try {
14
+ return record(JSON.parse(text));
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ /** The directory of the package that holds the entry: the nearest one with a package.json. */
21
+ async function packageDirectory(entry, read) {
22
+ let directory = dirname(entry);
23
+ for (;;) {
24
+ if ((await read(join(directory, "package.json"))) !== undefined) {
25
+ return directory;
26
+ }
27
+ const parent = dirname(directory);
28
+ if (parent === directory) {
29
+ return undefined;
30
+ }
31
+ directory = parent;
32
+ }
33
+ }
34
+ /**
35
+ * Why this SDK must not check the ontology at `entry`: its package's package-lock.json pins
36
+ * another release of the SDK, the one a deployment installs. That happens after a pull brings a
37
+ * new lockfile and node_modules is not reinstalled; the check would then judge the ontology by an
38
+ * older or newer release's rules. Undefined when they agree, when the package has no
39
+ * package-lock.json, and for an unreleased build of the SDK (version 0.0.0).
40
+ */
41
+ export async function lockedReleaseMismatch(input) {
42
+ const { version, read } = input;
43
+ if (version === undefined || version === "0.0.0") {
44
+ return undefined;
45
+ }
46
+ const directory = await packageDirectory(resolve(input.cwd, input.entry), read);
47
+ if (directory === undefined) {
48
+ return undefined;
49
+ }
50
+ const lock = parsed(await read(join(directory, "package-lock.json")));
51
+ const pinned = record(record(lock?.packages)?.[`node_modules/${SDK_PACKAGE}`]);
52
+ const locked = pinned?.version;
53
+ if (typeof locked !== "string" || pinned?.link === true || locked === version) {
54
+ return undefined;
55
+ }
56
+ const prefix = relative(input.invokedFrom ?? input.cwd, directory) || ".";
57
+ const command = prefix === "." ? "npm ci" : `npm --prefix ${prefix} ci`;
58
+ return (`This command runs ${SDK_PACKAGE} ${version} from node_modules, but ` +
59
+ `${join(prefix, "package-lock.json")} pins ${locked}, which a deployment installs. Their ` +
60
+ `rules can differ, so the ontology was not checked: run \`${command}\` and run the command ` +
61
+ "again.");
62
+ }
@@ -26,6 +26,8 @@ export interface MainDependencies {
26
26
  readonly output: Output;
27
27
  readonly load: OntologyLoader;
28
28
  readonly connect: OwnerConnection;
29
+ /** See `CheckDependencies.lockedRelease`. */
30
+ readonly lockedRelease?: (entry: string) => Promise<string | undefined>;
29
31
  }
30
32
  /** Runs one command line and returns the process exit code. */
31
33
  export declare function runMain(args: ReadonlyArray<string>, dependencies: MainDependencies): Promise<ExitCode>;
package/dist/bin.js CHANGED
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // The `segmentstream-ontology` binary: wires the process to the commands in ./bin/.
3
+ import { readFile } from "node:fs/promises";
4
+ import { lockedReleaseMismatch } from "./bin/installed.js";
3
5
  import { importWithTsx, loadOntology } from "./bin/load.js";
4
6
  import { runMain } from "./bin/main.js";
5
7
  import { connectOwnerDatabase } from "./bin/migrate.js";
@@ -20,11 +22,25 @@ function flushed(stream) {
20
22
  });
21
23
  }
22
24
  const cwd = process.cwd();
25
+ const readText = (path) => readFile(path, "utf8").catch(() => undefined);
26
+ // This file is dist/bin.js; the package's own package.json carries the released version.
27
+ const sdk = JSON.parse((await readText(new URL("../package.json", import.meta.url))) ?? "{}");
28
+ const version = typeof sdk === "object" && sdk !== null && "version" in sdk && typeof sdk.version === "string"
29
+ ? sdk.version
30
+ : undefined;
23
31
  const exitCode = await runMain(process.argv.slice(2), {
24
32
  environment: process.env,
25
33
  output: { stdout: writer(process.stdout), stderr: writer(process.stderr) },
26
34
  load: (entry) => loadOntology({ entry, cwd }, importWithTsx),
27
35
  connect: connectOwnerDatabase,
36
+ lockedRelease: (entry) => lockedReleaseMismatch({
37
+ entry,
38
+ cwd,
39
+ // npm names the directory a script was started from; see `invokedFrom`.
40
+ invokedFrom: process.env.INIT_CWD,
41
+ version,
42
+ read: readText,
43
+ }),
28
44
  });
29
45
  await Promise.all([flushed(process.stdout), flushed(process.stderr)]);
30
46
  // The ontology's modules may hold timers or sockets open; the command is done.
@@ -261,8 +261,9 @@ export interface ChatMessageSearch {
261
261
  * `participantId`, row by row. A search of several chats names, by `<channel>:<chat id>`, the
262
262
  * groups the reader is in (`groupChats`), read as `groups` reads every group, and the chats the
263
263
  * ontology checked (`chats`), each read as `chat` reads the one searched. Every rule reads only
264
- * what reached the provider: never an internal row, a send still unsent, or one that failed
265
- * before the provider took it.
264
+ * what reached the provider: never a send still unsent, or one that failed before the provider
265
+ * took it, and never an internal row, unless a staff read of the one chat `chat` admits asks for
266
+ * them (`internal`).
266
267
  */
267
268
  export interface ChatMessageReader {
268
269
  readonly participantId: string | null;
@@ -270,6 +271,11 @@ export interface ChatMessageReader {
270
271
  readonly chat: boolean;
271
272
  readonly groupChats?: ReadonlyArray<string>;
272
273
  readonly chats?: ReadonlyArray<string>;
274
+ /**
275
+ * With `chat`, the chat's internal rows too, never sent: the agent's notes for staff and the
276
+ * questions it could not answer. Without `chat`, nothing.
277
+ */
278
+ readonly internal?: boolean;
273
279
  }
274
280
  export interface ChatMessagePage {
275
281
  readonly messages: ReadonlyArray<ChatMessage>;
@@ -669,14 +669,16 @@ export function sqlChatMessageStore(sql) {
669
669
  return Effect.succeed({ messages: [], nextCursor: null });
670
670
  }
671
671
  conditions.push(`(${rules.join(" OR ")})`);
672
- // Every rule reads what reached the provider: never an internal row, a send still unsent, nor
673
- // one that failed before the provider took it; a send becomes readable under the revision its
674
- // receipt takes. One the provider took and later failed stays, `failed`, and an echo a send
675
- // took over stays a change, so a reader polling after a revision sees the same chat as one
676
- // reading it whole.
672
+ // Every rule reads what reached the provider: never a send still unsent, nor one that failed
673
+ // before the provider took it; a send becomes readable under the revision its receipt takes.
674
+ // One the provider took and later failed stays, `failed`, and an echo a send took over stays a
675
+ // change, so a reader polling after a revision sees the same chat as one reading it whole. An
676
+ // internal row is no rule's, unless a staff read of the one chat it checked asks for it.
677
677
  conditions.push(`("direction" = 'inbound' OR "replaced_by" IS NOT NULL OR ("direction" = 'outbound' AND ` +
678
678
  `("status" IS NULL OR "status" IN ('sent', 'delivered', 'read') OR ` +
679
- `("status" = 'failed' AND "message_id" IS NOT NULL))))`);
679
+ `("status" = 'failed' AND "message_id" IS NOT NULL)))` +
680
+ (reader.chat && reader.internal === true ? ` OR "direction" = 'internal'` : "") +
681
+ `)`);
680
682
  return page(conditions, params, input);
681
683
  };
682
684
  const holds = (chat) => rows(chat === undefined
@@ -45,6 +45,12 @@ export type ChatArchiveTransport = (input: {
45
45
  * first: a read of the store alone (`withChatStore`).
46
46
  */
47
47
  readonly after?: string;
48
+ /**
49
+ * A staff read of one of `chats` asks for its internal messages too, never sent (the agent's
50
+ * notes for staff and the questions it could not answer), which only the workspace's chat store
51
+ * keeps. Any other read leaves them out.
52
+ */
53
+ readonly internal?: boolean;
48
54
  }) => Effect.Effect<ChatPage, ChatArchiveUnavailable | PermissionDenied | ActionRejected>;
49
55
  /**
50
56
  * The authenticated ontology service forwards its resolved member, never a caller-supplied ID.
@@ -65,8 +65,9 @@ export declare function chatMessageEvent(message: ChatMessage): {
65
65
  /**
66
66
  * Reads a chat from the workspace's chat store, `_chat_messages`, when the store holds its
67
67
  * messages, and a search of several chats once the store holds any message, the evidence that the
68
- * agent records there; each as the reader the chat archive's rule admits, row by row. Reads after
69
- * a `revision`, or before a cursor of the store, are the store's alone. Any other read goes to
70
- * `transport`, within the retention the ontology declares, `retentionDays`.
68
+ * agent records there; each as the reader the chat archive's rule admits, row by row, with the
69
+ * chat's internal messages only for a read of a chat the ontology checked that asks for them
70
+ * (`internal`). Reads after a `revision`, or before a cursor of the store, are the store's alone.
71
+ * Any other read goes to `transport`, within the retention the ontology declares, `retentionDays`.
71
72
  */
72
73
  export declare function withChatStore(transport: ChatArchiveTransport, backend: OntologyBackend["Service"], retentionDays: number | undefined): ChatArchiveTransport;
@@ -91,9 +91,10 @@ function withinRetention(input, retentionDays, now) {
91
91
  /**
92
92
  * Reads a chat from the workspace's chat store, `_chat_messages`, when the store holds its
93
93
  * messages, and a search of several chats once the store holds any message, the evidence that the
94
- * agent records there; each as the reader the chat archive's rule admits, row by row. Reads after
95
- * a `revision`, or before a cursor of the store, are the store's alone. Any other read goes to
96
- * `transport`, within the retention the ontology declares, `retentionDays`.
94
+ * agent records there; each as the reader the chat archive's rule admits, row by row, with the
95
+ * chat's internal messages only for a read of a chat the ontology checked that asks for them
96
+ * (`internal`). Reads after a `revision`, or before a cursor of the store, are the store's alone.
97
+ * Any other read goes to `transport`, within the retention the ontology declares, `retentionDays`.
97
98
  */
98
99
  export function withChatStore(transport, backend, retentionDays) {
99
100
  return (input) => Effect.gen(function* () {
@@ -129,13 +130,17 @@ export function withChatStore(transport, backend, retentionDays) {
129
130
  return yield* new ActionRejected({ message: "invalid_chat_search" });
130
131
  }
131
132
  // One chat's reader is decided for the chat; several chats' row by row, by each row's chat.
133
+ // Only a read of one chat the ontology checked may ask for its internal messages too.
134
+ const checked = key !== undefined && (chats ?? []).includes(key);
135
+ const internal = checked && input.internal === true ? { internal: true } : {};
132
136
  const reader = key !== undefined
133
137
  ? service
134
- ? { participantId: null, groups: false, chat: (chats ?? []).includes(key) }
138
+ ? { participantId: null, groups: false, chat: checked, ...internal }
135
139
  : {
136
140
  participantId: principal.id,
137
141
  groups: isAllowed("agent_chat:read", principal) || (memberGroups ?? []).includes(key),
138
- chat: (chats ?? []).includes(key),
142
+ chat: checked,
143
+ ...internal,
139
144
  }
140
145
  : service
141
146
  ? { participantId: null, groups: false, chat: false, chats: chats ?? [] }
@@ -95,9 +95,9 @@ export function chatReads(backend, options) {
95
95
  return yield* new ActionRejected({ message: "The chat archive is not configured." });
96
96
  }
97
97
  const key = `${registered.provider}:${registered.externalId}`;
98
- // Staff read the chat's messages whoever wrote them; its person reads the messages they
99
- // took part in, as in any private chat, so an account paired with someone else since
100
- // shows the earlier person nothing newer.
98
+ // Staff read the chat's messages whoever wrote them, and on request its internal ones;
99
+ // its person reads the messages they took part in, as in any private chat, so an account
100
+ // paired with someone else since shows the earlier person nothing newer.
101
101
  return yield* chatHistory({
102
102
  principal,
103
103
  identityToken,
@@ -108,7 +108,9 @@ export function chatReads(backend, options) {
108
108
  ...(input.limit === undefined ? {} : { limit: input.limit }),
109
109
  },
110
110
  memberGroups: [],
111
- ...(registered.staff ? { chats: [key] } : {}),
111
+ ...(registered.staff
112
+ ? { chats: [key], ...(input.internal === true ? { internal: true } : {}) }
113
+ : {}),
112
114
  ...after,
113
115
  });
114
116
  }
@@ -73,6 +73,11 @@ export declare const ChatHistory: Schema.Struct<{
73
73
  */
74
74
  readonly after: Schema.optionalKey<Schema.String>;
75
75
  readonly limit: Schema.optionalKey<Schema.Int>;
76
+ /**
77
+ * A staff read's request for more than reached the provider: the chat's internal messages too,
78
+ * each never sent. A read that may not have them reads the chat as without it.
79
+ */
80
+ readonly internal: Schema.optionalKey<Schema.Boolean>;
76
81
  }>;
77
82
  export declare const ChatDestination: Schema.Struct<{
78
83
  readonly id: Schema.String;
@@ -25,6 +25,16 @@ export const ChatHistory = Schema.Struct({
25
25
  */
26
26
  after: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^\d{1,18}$/))),
27
27
  limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))),
28
+ /**
29
+ * A staff read's request for more than reached the provider: the chat's internal messages too,
30
+ * each never sent. A read that may not have them reads the chat as without it.
31
+ */
32
+ internal: Schema.optionalKey(Schema.Boolean.annotate({
33
+ description: "Also return the chat's internal messages (kind internal), which were never sent: the " +
34
+ "agent's notes for staff on its replies and the questions it could not answer. Only for " +
35
+ "a private chat read by its agent_chat id with agent_chat:read within your scope; any " +
36
+ "other read leaves them out.",
37
+ })),
28
38
  });
29
39
  export const ChatDestination = Schema.Struct({
30
40
  id: Id,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.188.0",
3
+ "version": "0.189.1",
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",