@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.
- package/CHANGELOG.md +52 -0
- package/README.md +9 -1
- package/dist/action.d.ts +11 -6
- package/dist/analyze.d.ts +3 -2
- package/dist/analyze.js +21 -10
- package/dist/app-feedback.js +6 -5
- package/dist/chat.d.ts +2 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/migrate/apply.js +5 -17
- package/dist/replication/baseline.d.ts +1 -2
- package/dist/replication/baseline.js +3 -2
- package/dist/replication/legacy-baseline.d.ts +1 -2
- package/dist/replication/legacy-baseline.js +3 -6
- package/dist/replication/migrate.d.ts +1 -10
- package/dist/replication/migrate.js +0 -37
- package/dist/replication/model.d.ts +6 -9
- package/dist/replication/model.js +13 -47
- package/dist/replication/schema.js +3 -0
- package/dist/replication/shadow.d.ts +7 -3
- package/dist/replication/shadow.js +9 -9
- package/dist/replication/store.d.ts +6 -2
- package/dist/replication/store.js +21 -46
- package/dist/runtime/agents.js +58 -0
- package/dist/runtime/service-binding.d.ts +5 -1
- package/dist/runtime/service-binding.js +14 -5
- package/dist/service/agent/chat-archive.d.ts +2 -1
- package/dist/service/agent/chat-archive.js +12 -8
- package/dist/service/agent/web-tokens.js +9 -1
- package/dist/service/chat/reads.js +5 -1
- package/dist/service/mcp/server.js +5 -5
- package/dist/service/mcp/tools.js +7 -3
- package/dist/service/runtime-contract.d.ts +7 -0
- package/dist/storage/memory.d.ts +100 -0
- package/dist/storage/memory.js +281 -0
- package/dist/storage/sessions.d.ts +2 -2
- package/package.json +1 -1
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import type { SqlClient } from "effect/unstable/sql";
|
|
3
|
-
import { type ReplicationEvent, type ReplicationSelection
|
|
3
|
+
import { type ReplicationEvent, type ReplicationSelection } from "./model.js";
|
|
4
4
|
import { advanceReplicationBaseline, ReplicationBaselineFailed, type ReplicationTarget } from "./baseline.js";
|
|
5
5
|
export type { ReplicationTarget } from "./baseline.js";
|
|
6
6
|
export declare const startReplication: (sql: SqlClient.SqlClient, input: {
|
|
7
7
|
readonly generation: string;
|
|
8
|
-
readonly exclusions?: ReadonlyArray<ReplicationExclusion>;
|
|
9
8
|
readonly selection?: ReadonlyArray<ReplicationSelection>;
|
|
10
9
|
readonly newSource?: boolean;
|
|
11
10
|
}) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed | import("../index.js").CatalogInvalid | import("./legacy-baseline.js").ReplicationBaselineFailed, never>;
|
|
12
11
|
export declare const activeReplicationTarget: (sql: SqlClient.SqlClient) => Effect.Effect<ReplicationTarget | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
12
|
+
/**
|
|
13
|
+
* Disables source capture under the lifecycle fence: the state a preview branch's binding, or an
|
|
14
|
+
* earlier release's retired pause, leaves behind. Starting replication resumes such a source with a
|
|
15
|
+
* fresh incarnation; nothing in the platform offers capture as an opt-out.
|
|
16
|
+
*/
|
|
13
17
|
export declare const pauseReplication: (sql: SqlClient.SqlClient) => Effect.Effect<void, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
14
18
|
export declare const replicationTarget: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<ReplicationTarget | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
15
19
|
export { advanceReplicationBaseline };
|
|
@@ -9,18 +9,10 @@ import { readCatalog } from "../migrate/apply.js";
|
|
|
9
9
|
import { historyTableName, quoteIdentifier as qi } from "../migrate/storage.js";
|
|
10
10
|
import { REPLICATION_BATCH_BYTES, REPLICATION_BATCH_SIZE, publishMessage, replicationEventId, resolveReplicationSelection, } from "./model.js";
|
|
11
11
|
import { createReplicationBaseline, advanceReplicationBaseline, ReplicationBaselineFailed, } from "./baseline.js";
|
|
12
|
-
import {
|
|
12
|
+
import { migratedReplicationFills } from "./migrate.js";
|
|
13
13
|
import { refreshReplicationProjection } from "./evolution.js";
|
|
14
14
|
import { REPLICATION_TARGET_FILLS, REPLICATION_TARGET_METADATA } from "./schema.js";
|
|
15
15
|
import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
|
|
16
|
-
const replicationPolicyKey = (policy) => JSON.stringify(policy
|
|
17
|
-
.map((item) => ({
|
|
18
|
-
entityId: item.entityId,
|
|
19
|
-
disabled: item.disabled ?? false,
|
|
20
|
-
fields: [...new Set(item.fields ?? [])].sort(),
|
|
21
|
-
relationships: [...new Set(item.relationships ?? [])].sort(),
|
|
22
|
-
}))
|
|
23
|
-
.sort((a, b) => a.entityId.localeCompare(b.entityId)));
|
|
24
16
|
export const startReplication = (sql, input) => Effect.gen(function* () {
|
|
25
17
|
const manifest = yield* readCatalog({ sql });
|
|
26
18
|
if (!manifest) {
|
|
@@ -29,27 +21,31 @@ export const startReplication = (sql, input) => Effect.gen(function* () {
|
|
|
29
21
|
});
|
|
30
22
|
}
|
|
31
23
|
const version = yield* protocol(sql);
|
|
32
|
-
|
|
24
|
+
// @legacy ontology.replication-exclusion-remnants
|
|
25
|
+
// A source can still record the exclusions of retired per-workspace export policies. Clearing
|
|
26
|
+
// them is a policy change through the same scoped recovery and cutover as any other.
|
|
27
|
+
const [state] = yield* sql.unsafe(`SELECT enabled,
|
|
28
|
+
COALESCE(to_jsonb(_ontology_replication)->'exclusions','[]'::jsonb)<>'[]'::jsonb AS restricted
|
|
29
|
+
FROM _ontology_replication WHERE id`);
|
|
33
30
|
const requested = yield* replicationTarget(sql, input.generation);
|
|
34
31
|
const previous = version >= 6 && requested ? ((yield* activeReplicationTarget(sql)) ?? requested) : requested;
|
|
35
|
-
const
|
|
36
|
-
const persisted = replicationPolicyKey(policy) === replicationPolicyKey(state?.exclusions ?? []);
|
|
32
|
+
const restricted = state?.restricted === true;
|
|
37
33
|
const paused = version >= 6 && state?.enabled === false;
|
|
38
34
|
if (previous &&
|
|
39
35
|
!paused &&
|
|
40
|
-
|
|
36
|
+
!restricted &&
|
|
41
37
|
previous.manifest.hash === manifest.hash &&
|
|
42
38
|
input.selection === undefined) {
|
|
43
39
|
return previous;
|
|
44
40
|
}
|
|
45
41
|
const selection = input.selection ??
|
|
46
42
|
(yield* Effect.try({
|
|
47
|
-
try: () => resolveReplicationSelection(manifest
|
|
48
|
-
catch: (cause) => new ReplicationBaselineFailed({ message: "Invalid replication
|
|
43
|
+
try: () => resolveReplicationSelection(manifest),
|
|
44
|
+
catch: (cause) => new ReplicationBaselineFailed({ message: "Invalid replication projection.", cause }),
|
|
49
45
|
}));
|
|
50
46
|
if (previous &&
|
|
51
47
|
(paused ||
|
|
52
|
-
|
|
48
|
+
restricted ||
|
|
53
49
|
previous.manifest.hash !== manifest.hash ||
|
|
54
50
|
canonicalJson(previous.selection) !== canonicalJson(selection))) {
|
|
55
51
|
if (version >= 5) {
|
|
@@ -67,10 +63,9 @@ export const startReplication = (sql, input) => Effect.gen(function* () {
|
|
|
67
63
|
}
|
|
68
64
|
const fills = yield* migratedReplicationFills(sql, current, manifest, selection);
|
|
69
65
|
yield* refreshReplicationProjection(sql, current, { ...current, manifest, selection, fills }, undefined, { resuming: version >= 6 && capture?.enabled === false });
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
]);
|
|
66
|
+
// @legacy ontology.replication-exclusion-remnants
|
|
67
|
+
// An older backend release still reads the retired exclusions; record that none remain.
|
|
68
|
+
yield* sql.unsafe("UPDATE _ontology_replication SET selection=$1::jsonb,exclusions='[]'::jsonb,enabled=true WHERE id", [JSON.stringify(Object.fromEntries(selection.map((item) => [item.entityId, item])))]);
|
|
74
69
|
if (version >= 6) {
|
|
75
70
|
yield* sql.unsafe(`UPDATE _ontology_replication_epochs SET policy_installed=false
|
|
76
71
|
WHERE id=(SELECT active_generation FROM _ontology_replication WHERE id)`);
|
|
@@ -121,6 +116,11 @@ export const activeReplicationTarget = (sql) => Effect.gen(function* () {
|
|
|
121
116
|
: yield* sql.unsafe(statement);
|
|
122
117
|
return rows[0];
|
|
123
118
|
});
|
|
119
|
+
/**
|
|
120
|
+
* Disables source capture under the lifecycle fence: the state a preview branch's binding, or an
|
|
121
|
+
* earlier release's retired pause, leaves behind. Starting replication resumes such a source with a
|
|
122
|
+
* fresh incarnation; nothing in the platform offers capture as an opt-out.
|
|
123
|
+
*/
|
|
124
124
|
export const pauseReplication = (sql) => sql.withTransaction(Effect.gen(function* () {
|
|
125
125
|
yield* lockReplicationLifecycle(sql);
|
|
126
126
|
yield* sql.unsafe("UPDATE _ontology_replication SET enabled = false WHERE id");
|
|
@@ -166,7 +166,7 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
|
|
|
166
166
|
ORDER BY revision,event_id LIMIT ${REPLICATION_BATCH_SIZE}`, shadow
|
|
167
167
|
? [target.generation, options.bulk ?? false, options.through ?? null]
|
|
168
168
|
: [target.generation]);
|
|
169
|
-
// An idle pass ends here: the bindings
|
|
169
|
+
// An idle pass ends here: the wire bindings below shape only queued events.
|
|
170
170
|
if (references.length === 0) {
|
|
171
171
|
return [];
|
|
172
172
|
}
|
|
@@ -196,10 +196,6 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
|
|
|
196
196
|
? yield* sql.unsafe("SELECT capture_bindings,capture_versions FROM _ontology_replication_targets WHERE generation=$1::uuid", [target.generation])
|
|
197
197
|
: [];
|
|
198
198
|
const batchBytes = options.bulk ? 32_000_000 : REPLICATION_BATCH_BYTES;
|
|
199
|
-
const [policy] = shadow
|
|
200
|
-
? yield* sql.unsafe("SELECT exclusions FROM _ontology_replication WHERE id")
|
|
201
|
-
: [];
|
|
202
|
-
const suppressed = [];
|
|
203
199
|
let size = 32;
|
|
204
200
|
const result = [];
|
|
205
201
|
for (const reference of references) {
|
|
@@ -216,23 +212,6 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
|
|
|
216
212
|
const bindings = wire.capture_versions?.find((version) => version.through === undefined || BigInt(event.revision) <= BigInt(version.through))?.bindings ?? wire.capture_bindings;
|
|
217
213
|
event = shadowWireEvent(event, bindings, target.selection);
|
|
218
214
|
}
|
|
219
|
-
const restriction = policy?.exclusions.find((item) => item.entityId === event.entity_id);
|
|
220
|
-
if (restriction?.disabled ||
|
|
221
|
-
(event.record_kind.startsWith("edge:") &&
|
|
222
|
-
restriction?.relationships?.includes(event.record_kind.slice(5)))) {
|
|
223
|
-
suppressed.push(reference.id);
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
if (restriction && event.record_kind === "entity" && !event.deleted) {
|
|
227
|
-
const fields = new Set([
|
|
228
|
-
...(restriction.fields ?? []),
|
|
229
|
-
...(restriction.relationships ?? []).map((name) => `${name}_id`),
|
|
230
|
-
]);
|
|
231
|
-
event = {
|
|
232
|
-
...event,
|
|
233
|
-
payload: JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(event.payload)).filter(([key]) => !fields.has(wire?.capture_bindings?.[event.entity_id]?.[key] ?? key)))),
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
215
|
const bytes = Buffer.byteLength(JSON.stringify(publishMessage(event))) + 1;
|
|
237
216
|
if (bytes + 32 > REPLICATION_BATCH_BYTES) {
|
|
238
217
|
return yield* Effect.die(new Error("A replication event exceeds the publish request limit."));
|
|
@@ -243,10 +222,6 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
|
|
|
243
222
|
size += bytes;
|
|
244
223
|
result.push({ historyId: reference.id, event });
|
|
245
224
|
}
|
|
246
|
-
if (suppressed.length) {
|
|
247
|
-
yield* sql.unsafe(`UPDATE _ontology_replication_delivery SET suppressed_at=now()
|
|
248
|
-
WHERE generation=$1::uuid AND event_id IN (SELECT value::uuid FROM jsonb_array_elements_text($2::jsonb))`, [target.generation, JSON.stringify(suppressed)]);
|
|
249
|
-
}
|
|
250
225
|
return result;
|
|
251
226
|
});
|
|
252
227
|
/** Lost publish responses deliberately leave the same immutable IDs pending. */
|
package/dist/runtime/agents.js
CHANGED
|
@@ -7,6 +7,7 @@ import { chatChannelKind } from "../chat-channel.js";
|
|
|
7
7
|
import { AgentReview } from "../agent-review.js";
|
|
8
8
|
import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
|
|
9
9
|
import { inboxRolesOf } from "../manifest.js";
|
|
10
|
+
import { GUEST_ROLE } from "../names.js";
|
|
10
11
|
import { MAX_QUERY_LIMIT } from "../query.js";
|
|
11
12
|
import { beginReplicationWrite } from "../replication/transaction.js";
|
|
12
13
|
import { IdentityInUse, } from "../service/runtime-contract.js";
|
|
@@ -15,6 +16,7 @@ import { resolveAgentIdentity } from "./resolve-agent-identity.js";
|
|
|
15
16
|
import { completeAgentLimitNotice } from "./agent-counters.js";
|
|
16
17
|
import { isMemberBlocked, setMemberBlocked, resolveMemberById } from "./principals.js";
|
|
17
18
|
import { sqlAgentWebStore } from "./agent-web.js";
|
|
19
|
+
import { guestChat } from "./guests.js";
|
|
18
20
|
import { WEB_PROVIDER } from "../service/runtime-identity.js";
|
|
19
21
|
import { isRecordId } from "./records.js";
|
|
20
22
|
import { makeOntologyRuntime } from "./sql-runtime.js";
|
|
@@ -548,6 +550,62 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
548
550
|
};
|
|
549
551
|
}));
|
|
550
552
|
}).pipe(Effect.orDie),
|
|
553
|
+
seeGuestChat: (guestId) => Effect.gen(function* () {
|
|
554
|
+
// Only the visitors' chats of an inbox that takes the guests.
|
|
555
|
+
if (!isRecordId(guestId) || !inboxRolesOf(ontology.manifest).has(GUEST_ROLE)) {
|
|
556
|
+
return undefined;
|
|
557
|
+
}
|
|
558
|
+
const externalId = guestChat(guestId);
|
|
559
|
+
return yield* sql.withTransaction(Effect.gen(function* () {
|
|
560
|
+
yield* beginReplicationWrite(sql);
|
|
561
|
+
// Turns of one visitor run one after the other: the first creates it, the rest find it.
|
|
562
|
+
yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
|
|
563
|
+
`chat:${WEB_PROVIDER}:${externalId}`,
|
|
564
|
+
]);
|
|
565
|
+
const runtime = makeOntologyRuntime(ontology, sql, {
|
|
566
|
+
action: `${AgentChat.name}.seen`,
|
|
567
|
+
actionId: randomUUID(),
|
|
568
|
+
principalId: null,
|
|
569
|
+
});
|
|
570
|
+
const [found] = yield* runtime.find({
|
|
571
|
+
entity: AgentChat.name,
|
|
572
|
+
options: {
|
|
573
|
+
where: { provider: WEB_PROVIDER, external_id: externalId },
|
|
574
|
+
limit: 1,
|
|
575
|
+
forUpdate: true,
|
|
576
|
+
},
|
|
577
|
+
});
|
|
578
|
+
if (found !== undefined && found.kind !== "private") {
|
|
579
|
+
return undefined;
|
|
580
|
+
}
|
|
581
|
+
const now = new Date();
|
|
582
|
+
// A visitor has no name: the chat is titled by its key, as the archive keeps it.
|
|
583
|
+
const chat = found === undefined
|
|
584
|
+
? yield* runtime.create({
|
|
585
|
+
entity: AgentChat.name,
|
|
586
|
+
values: {
|
|
587
|
+
provider: WEB_PROVIDER,
|
|
588
|
+
external_id: externalId,
|
|
589
|
+
kind: "private",
|
|
590
|
+
title: externalId,
|
|
591
|
+
last_message_at: now.toISOString(),
|
|
592
|
+
},
|
|
593
|
+
})
|
|
594
|
+
: messageDue(found.last_message_at, now)
|
|
595
|
+
? yield* runtime.update({
|
|
596
|
+
entity: AgentChat.name,
|
|
597
|
+
id: String(found.id),
|
|
598
|
+
values: { last_message_at: now.toISOString() },
|
|
599
|
+
})
|
|
600
|
+
: found;
|
|
601
|
+
return {
|
|
602
|
+
id: String(chat.id),
|
|
603
|
+
title: String(chat.title),
|
|
604
|
+
purpose: nullableText(chat.purpose),
|
|
605
|
+
whenToUse: nullableText(chat.when_to_use),
|
|
606
|
+
};
|
|
607
|
+
}));
|
|
608
|
+
}).pipe(Effect.orDie),
|
|
551
609
|
holdReply: (input) => sql
|
|
552
610
|
.withTransaction(Effect.gen(function* () {
|
|
553
611
|
if (!isRecordId(input.memberId)) {
|
|
@@ -7,7 +7,11 @@ import type { Ontology } from "../ontology.js";
|
|
|
7
7
|
import { OntologyBackend, type OntologyServiceRuntime } from "../service/runtime-contract.js";
|
|
8
8
|
import { SignInLinks } from "./sign-in-links.js";
|
|
9
9
|
import { WorkflowStarter } from "./workflow-starts.js";
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* The service's backend on the runtime, over the SQL client in context. `blobStorage` is the
|
|
12
|
+
* deployment's file storage, or a test's `memoryFileStorage().blobStorage`; without it, actions
|
|
13
|
+
* that upload, stage or open files are refused.
|
|
14
|
+
*/
|
|
11
15
|
export declare function backendLayer(ontology: Ontology, blobStorage?: Redacted.Redacted<BlobStorageBinding>, workflowStarter?: WorkflowStarter["Service"], deployment?: DeploymentObservation, signInLinks?: SignInLinks["Service"]): Layer.Layer<OntologyBackend, never, SqlClient.SqlClient>;
|
|
12
16
|
/**
|
|
13
17
|
* `@effect/sql-pg` on the pooled `ontology_app` connection string, with the TLS server name a
|
|
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import { Effect, Layer, Redacted } from "effect";
|
|
4
4
|
import { SqlClient } from "effect/unstable/sql";
|
|
5
5
|
import { isSqlError } from "effect/unstable/sql/SqlError";
|
|
6
|
+
import { memoryFileStore } from "../storage/memory.js";
|
|
6
7
|
import { neonBlobProvider } from "../storage/neon.js";
|
|
7
8
|
import { maintainBlobStorage } from "../storage/maintenance.js";
|
|
8
9
|
import { attachmentRuntime } from "../storage/attachments.js";
|
|
@@ -42,7 +43,11 @@ function rejectedAs(operation) {
|
|
|
42
43
|
...(rejection.diagnostic === undefined ? {} : { diagnostic: rejection.diagnostic }),
|
|
43
44
|
}), Effect.as(undefined));
|
|
44
45
|
}
|
|
45
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* The service's backend on the runtime, over the SQL client in context. `blobStorage` is the
|
|
48
|
+
* deployment's file storage, or a test's `memoryFileStorage().blobStorage`; without it, actions
|
|
49
|
+
* that upload, stage or open files are refused.
|
|
50
|
+
*/
|
|
46
51
|
export function backendLayer(ontology, blobStorage, workflowStarter, deployment, signInLinks) {
|
|
47
52
|
return Layer.effect(OntologyBackend, Effect.gen(function* () {
|
|
48
53
|
const sql = yield* SqlClient.SqlClient;
|
|
@@ -134,10 +139,14 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
|
|
|
134
139
|
.pipe(Effect.orDie);
|
|
135
140
|
}
|
|
136
141
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const
|
|
142
|
+
// A test's in-memory store answers its own transfer grants; a deployment's binding names
|
|
143
|
+
// the branch storage of its database.
|
|
144
|
+
const memory = memoryFileStore(blobStorage);
|
|
145
|
+
const provider = memory?.provider ??
|
|
146
|
+
(binding
|
|
147
|
+
? yield* Effect.acquireRelease(Effect.sync(() => neonBlobProvider(binding, deployment)), (provider) => Effect.sync(() => provider.close?.()))
|
|
148
|
+
: undefined);
|
|
149
|
+
const blobs = provider ? blobRuntime(ontology, sql, provider, memory?.fetch) : undefined;
|
|
141
150
|
const attachments = provider ? attachmentRuntime(ontology, sql, provider) : undefined;
|
|
142
151
|
return OntologyBackend.of({
|
|
143
152
|
workflowAdmissions: {
|
|
@@ -36,7 +36,8 @@ export type ChatArchiveTransport = (input: {
|
|
|
36
36
|
readonly memberGroups?: ReadonlyArray<string>;
|
|
37
37
|
/**
|
|
38
38
|
* Chats (`provider:chatId`) of any type the ontology checked the member may read, such as a
|
|
39
|
-
* private chat its inbox registered, which `agent_chat:read` within its scope reads.
|
|
39
|
+
* private chat its inbox registered, which `agent_chat:read` within its scope reads. A service
|
|
40
|
+
* principal, such as a workflow's user, reads these alone.
|
|
40
41
|
*/
|
|
41
42
|
readonly chats?: ReadonlyArray<string>;
|
|
42
43
|
}) => Effect.Effect<ChatPage, ChatArchiveUnavailable | PermissionDenied>;
|
|
@@ -23,7 +23,9 @@ export class ChatArchiveUnavailable extends Schema.TaggedError()("ChatArchiveUna
|
|
|
23
23
|
/** The authenticated ontology service forwards its resolved member, never a caller-supplied ID. */
|
|
24
24
|
export function platformChatArchive(environment, fetchImpl = fetch) {
|
|
25
25
|
return ({ search, principal, identityToken, memberGroups, chats }) => {
|
|
26
|
-
|
|
26
|
+
// A service, such as a workflow's user, reads only the exact chats the ontology checked.
|
|
27
|
+
const service = principal.kind === "service" && chats !== undefined && chats.length > 0;
|
|
28
|
+
if (principal.kind !== "member" && !service) {
|
|
27
29
|
return Effect.fail(new PermissionDenied({
|
|
28
30
|
message: "Only members may read chats.",
|
|
29
31
|
permission: "chat:participant",
|
|
@@ -45,13 +47,15 @@ export function platformChatArchive(environment, fetchImpl = fetch) {
|
|
|
45
47
|
},
|
|
46
48
|
body: JSON.stringify({
|
|
47
49
|
search,
|
|
48
|
-
reader:
|
|
49
|
-
participantId:
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
50
|
+
reader: service
|
|
51
|
+
? { participantId: null, groups: false, groupChats: [], chats, admin: false }
|
|
52
|
+
: {
|
|
53
|
+
participantId: principal.id,
|
|
54
|
+
groups: isAllowed("agent_chat:read", principal),
|
|
55
|
+
groupChats: memberGroups ?? [],
|
|
56
|
+
...(chats === undefined || chats.length === 0 ? {} : { chats }),
|
|
57
|
+
admin: false,
|
|
58
|
+
},
|
|
55
59
|
}),
|
|
56
60
|
signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]),
|
|
57
61
|
});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { Effect, Result, Schema } from "effect";
|
|
2
|
+
import { Cause, Effect, Exit, Result, Schema } from "effect";
|
|
3
3
|
import { HttpServerResponse } from "effect/unstable/http";
|
|
4
4
|
import { schemaIssues } from "../../runtime/validation.js";
|
|
5
5
|
import { BASE_PATH } from "../api.js";
|
|
@@ -130,6 +130,14 @@ export function introspectAgentToken(store, web, oauth, agentTools, guests) {
|
|
|
130
130
|
const limited = decoded.success.turn === true && web.countGuestTurn !== undefined
|
|
131
131
|
? yield* web.countGuestTurn(guest.id, limits)
|
|
132
132
|
: undefined;
|
|
133
|
+
// An admitted turn is a message in the visitor's chat: the inbox, where it takes guests,
|
|
134
|
+
// records the chat. The turn goes on whether or not the record could be written.
|
|
135
|
+
if (decoded.success.turn === true && limited === undefined && store.seeGuestChat) {
|
|
136
|
+
const seen = yield* Effect.exit(store.seeGuestChat(guest.id));
|
|
137
|
+
if (Exit.isFailure(seen)) {
|
|
138
|
+
yield* Effect.logWarning("ontology.agent.guest_chat_unrecorded").pipe(Effect.annotateLogs({ requestId, cause: Cause.pretty(seen.cause) }));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
133
141
|
return json({
|
|
134
142
|
active: true,
|
|
135
143
|
guest_id: guest.id,
|
|
@@ -76,7 +76,7 @@ export function chatReads(backend, options) {
|
|
|
76
76
|
}),
|
|
77
77
|
history: (input, identityToken) => Effect.gen(function* () {
|
|
78
78
|
const principal = yield* CurrentPrincipal;
|
|
79
|
-
if (principal.kind !== "member") {
|
|
79
|
+
if (principal.kind !== "member" && principal.kind !== "service") {
|
|
80
80
|
return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
|
|
81
81
|
}
|
|
82
82
|
const registered = UUID.test(input.chat)
|
|
@@ -103,6 +103,10 @@ export function chatReads(backend, options) {
|
|
|
103
103
|
...(registered.staff ? { chats: [key] } : {}),
|
|
104
104
|
});
|
|
105
105
|
}
|
|
106
|
+
// A service, such as a workflow's user, reads only the registered chats its scope holds.
|
|
107
|
+
if (principal.kind !== "member") {
|
|
108
|
+
return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
|
|
109
|
+
}
|
|
106
110
|
// History reads the chats of Telegram channels only. Other channels archive a chat under
|
|
107
111
|
// their session's address with private coordinates, not under the chat a destination
|
|
108
112
|
// names, so their history would be incomplete until the archive keys them the same way.
|
|
@@ -627,9 +627,9 @@ export const FEEDBACK_INSTRUCTIONS = "Feedback: this app accepts feedback for it
|
|
|
627
627
|
"something works badly or asks for something new. Do not offer what you can do yourself; offer " +
|
|
628
628
|
"once per problem. Before submitting, look for the user's open app_feedback with the same " +
|
|
629
629
|
"subject. Submit with app_feedback_submit only after the user agrees to the title and summary you " +
|
|
630
|
-
"show in their language.
|
|
631
|
-
"
|
|
632
|
-
"
|
|
630
|
+
"show in their language. When the user asks about their feedback, read only their own: filter " +
|
|
631
|
+
"app_feedback by reporter, their user id from me, since builders can read everyone's. Tell " +
|
|
632
|
+
"them the builders' response, then call app_feedback_acknowledge with its responded_at.";
|
|
633
633
|
export const AUTOMATIC_FAILURE_REPORT_INSTRUCTIONS = "Feedback: During requested work, this workspace preauthorizes minimal technical failure reports. " +
|
|
634
634
|
"Automatically record unexpected or persistent tool/connection failures through app_feedback_submit; " +
|
|
635
635
|
"first reuse the caller's open report with the same subject. Include only the operation, safe technical " +
|
|
@@ -637,8 +637,8 @@ export const AUTOMATIC_FAILURE_REPORT_INSTRUCTIONS = "Feedback: During requested
|
|
|
637
637
|
"reason and that the report was recorded in one or two sentences; do not merely offer to report it, " +
|
|
638
638
|
"and never claim it was recorded before a successful submission or existing-item read. " +
|
|
639
639
|
"Feature/change requests and sharing task contents or files still require the member's agreement " +
|
|
640
|
-
"to the title and summary.
|
|
641
|
-
"acknowledge only the response you
|
|
640
|
+
"to the title and summary. Asked about their feedback, read only the caller's own items " +
|
|
641
|
+
"(reporter is their user id from me) and acknowledge only the response you relayed.";
|
|
642
642
|
/**
|
|
643
643
|
* Fixed guidance keeps initialization independent of ontology size: the feedback paragraph depends
|
|
644
644
|
* only on whether the caller may run `app_feedback_submit`.
|
|
@@ -801,13 +801,17 @@ export function mcpTools(built, chatHistory = false, storage = {}, navigation =
|
|
|
801
801
|
title: "Read chat history",
|
|
802
802
|
description: "Read messages for an exact chat ID/title, with their own pagination. " +
|
|
803
803
|
"Reads a group chat you are in (every group with agent_chat:read), your own private chat, " +
|
|
804
|
-
"or, by its agent_chat id, a
|
|
805
|
-
"agent_chat:read within your scope.",
|
|
804
|
+
"or, by its agent_chat id, a private chat the inbox registered (a person's, or a website " +
|
|
805
|
+
"visitor's), with agent_chat:read within your scope. A workflow's task reads only these.",
|
|
806
806
|
inputSchema: encodedJsonSchema(ChatHistory),
|
|
807
807
|
annotations: READ,
|
|
808
808
|
permissions: [],
|
|
809
809
|
target: { kind: "chat-history" },
|
|
810
|
-
inputSchemaFor: (caller) => "kind" in caller &&
|
|
810
|
+
inputSchemaFor: (caller) => "kind" in caller &&
|
|
811
|
+
(caller.kind === "member" ||
|
|
812
|
+
(caller.kind === "service" && isAllowed("agent_chat:read", caller)))
|
|
813
|
+
? encodedJsonSchema(ChatHistory)
|
|
814
|
+
: undefined,
|
|
811
815
|
});
|
|
812
816
|
tools.push({
|
|
813
817
|
name: "chat_search",
|
|
@@ -642,6 +642,13 @@ export interface AgentStore {
|
|
|
642
642
|
* stores that predate the inbox.
|
|
643
643
|
*/
|
|
644
644
|
readonly seeInboxChat?: (input: InboxChatInput) => Effect.Effect<SeenChat | undefined>;
|
|
645
|
+
/**
|
|
646
|
+
* Records a website visitor's chat with the agent, `guest:<id>` on the `web` channel, for the
|
|
647
|
+
* inbox: creates the `agent_chat` of kind `private`, without members, and records when it last
|
|
648
|
+
* had a message, as `seeChat` does. `undefined`, recording nothing, unless the inbox takes
|
|
649
|
+
* `guest`. Absent on stores that predate it.
|
|
650
|
+
*/
|
|
651
|
+
readonly seeGuestChat?: (guestId: string) => Effect.Effect<SeenChat | undefined>;
|
|
645
652
|
/**
|
|
646
653
|
* A reply the agent held for review becomes a pending `agent_review` for the member it answers,
|
|
647
654
|
* once per `key`: a repeated report answers the review it created. `undefined` when the member is
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Effect, Redacted } from "effect";
|
|
2
|
+
import type { BlobUpload, BlobValue } from "../blob.js";
|
|
3
|
+
import { type ActionError } from "../errors.js";
|
|
4
|
+
import type { OpenFile } from "../files.js";
|
|
5
|
+
import type { Principal } from "../runtime.js";
|
|
6
|
+
import { OntologyBackend } from "../service/runtime-contract.js";
|
|
7
|
+
import { type BlobProvider, type BlobStorageBinding } from "./provider.js";
|
|
8
|
+
export interface MemoryFileStorageOptions {
|
|
9
|
+
/** The workspace's storage quota in bytes, which uploads count against. 1 GiB by default. */
|
|
10
|
+
readonly quotaBytes?: number;
|
|
11
|
+
}
|
|
12
|
+
/** A file to upload for an action's `uploads.for(entity, property)` input. */
|
|
13
|
+
export interface MemoryFileUpload {
|
|
14
|
+
/** Who uploads: the member or service user that then runs the action, with its roles stored. */
|
|
15
|
+
readonly principal: Principal;
|
|
16
|
+
/** The entity and file property of the action's `uploads.for` input. */
|
|
17
|
+
readonly entity: string;
|
|
18
|
+
readonly property: string;
|
|
19
|
+
/** The action that consumes the ticket, on `entity`. */
|
|
20
|
+
readonly action: string;
|
|
21
|
+
/** The record the action changes. Omit it for a record the action creates. */
|
|
22
|
+
readonly recordId?: string;
|
|
23
|
+
/** Names the record the action creates; the idempotency key by default, without `recordId`. */
|
|
24
|
+
readonly createIntent?: string;
|
|
25
|
+
/** The upload's and the action's idempotency key, a UUID; a new one by default. */
|
|
26
|
+
readonly idempotencyKey?: string;
|
|
27
|
+
readonly filename: string;
|
|
28
|
+
readonly contentType: string;
|
|
29
|
+
/** The file's bytes; a string is stored as UTF-8. */
|
|
30
|
+
readonly bytes: Uint8Array | string;
|
|
31
|
+
}
|
|
32
|
+
/** A completed upload, ready for the action it was made for. */
|
|
33
|
+
export interface UploadedFile {
|
|
34
|
+
/**
|
|
35
|
+
* The ticket an `uploads.for` input takes: `{ uploadId }` in an entity handle's action call,
|
|
36
|
+
* `{ upload_id: ticket.uploadId }` in an action's JSON input over HTTP or `runAction`.
|
|
37
|
+
*/
|
|
38
|
+
readonly ticket: BlobUpload;
|
|
39
|
+
/** The action options that consume the ticket: its idempotency key and, for a new record, create intent. */
|
|
40
|
+
readonly options: {
|
|
41
|
+
readonly idempotencyKey: string;
|
|
42
|
+
readonly createIntent?: string;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** A stored file revision read back, with its bytes. */
|
|
46
|
+
export interface StoredFile {
|
|
47
|
+
readonly file: BlobValue;
|
|
48
|
+
readonly bytes: Uint8Array;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* File storage held in memory, for tests that run the ontology in process. The backend built on
|
|
52
|
+
* it uploads, stages, opens and downloads files as on a deployment, with the same permission
|
|
53
|
+
* checks and upload lifecycle in the database; only the bytes stay in this process.
|
|
54
|
+
*/
|
|
55
|
+
export interface MemoryFileStorage {
|
|
56
|
+
/**
|
|
57
|
+
* The file storage to run the backend on: `backendLayer(ontology, files.blobStorage)`, or the
|
|
58
|
+
* `blobStorage` of `createOntologyService`'s configuration, which then also needs a
|
|
59
|
+
* `storageMaintenanceKey`.
|
|
60
|
+
*/
|
|
61
|
+
readonly blobStorage: Redacted.Redacted<BlobStorageBinding>;
|
|
62
|
+
/**
|
|
63
|
+
* Answers the transfer grants the store signs, as storage does: `PUT` stores an upload's bytes
|
|
64
|
+
* and `GET` returns a file's. A test that uploads over HTTP sends the bytes with it, such as
|
|
65
|
+
* `createBlobStorageClient(transport, files.fetch)` of the App SDK.
|
|
66
|
+
*/
|
|
67
|
+
readonly fetch: typeof fetch;
|
|
68
|
+
/**
|
|
69
|
+
* Uploads `bytes` as `principal` for `entity.action`'s `uploads.for(entity, property)` input
|
|
70
|
+
* and completes the upload: what an app's upload does, through the backend in context, which
|
|
71
|
+
* must run on this store. It checks the action's permission, the property's file policy and
|
|
72
|
+
* the quota as the service does.
|
|
73
|
+
*/
|
|
74
|
+
readonly upload: (input: MemoryFileUpload) => Effect.Effect<UploadedFile, ActionError, OntologyBackend>;
|
|
75
|
+
/**
|
|
76
|
+
* Reads a stored file revision back as `principal`, with the entity's read permission and
|
|
77
|
+
* scopes checked as `Files.open` checks them: the record's current file, or `revisionId`.
|
|
78
|
+
*/
|
|
79
|
+
readonly read: (input: OpenFile & {
|
|
80
|
+
readonly principal: Principal;
|
|
81
|
+
}) => Effect.Effect<StoredFile, ActionError, OntologyBackend>;
|
|
82
|
+
}
|
|
83
|
+
interface MemoryStore {
|
|
84
|
+
readonly provider: BlobProvider["Service"];
|
|
85
|
+
readonly fetch: typeof fetch;
|
|
86
|
+
}
|
|
87
|
+
/** The in-memory store `blobStorage` names, when `memoryFileStorage` made it. */
|
|
88
|
+
export declare function memoryFileStore(blobStorage: Redacted.Redacted<BlobStorageBinding> | undefined): MemoryStore | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* File storage held in memory, for tests that run an ontology's actions with files in process:
|
|
91
|
+
* `uploads.for` inputs, `Files.stage`, `Files.open`, downloads and the agent's attachments. Each
|
|
92
|
+
* call makes an empty store.
|
|
93
|
+
*
|
|
94
|
+
* ```ts
|
|
95
|
+
* const files = memoryFileStorage();
|
|
96
|
+
* const backend = backendLayer(ontology, files.blobStorage).pipe(Layer.provide(database));
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export declare function memoryFileStorage(options?: MemoryFileStorageOptions): MemoryFileStorage;
|
|
100
|
+
export {};
|