@segmentstream/ontology 0.99.1 → 0.100.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,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.100.0
4
+
5
+ The built-in permission `workspace_source:read` lets a role read the workspace's deployed code
6
+ through the agent. No wildcard grants it: `*:*` and `*:read` do not, `workspace_source:read` and
7
+ `workspace_source:*` do. `GET /api/ontology/agent/source` serves the agent runtime acting for a
8
+ member who holds it, page by page, from backend-next.
9
+
10
+ ## 0.99.2
11
+
12
+ Replication reads a workspace's manifest from its database once per process instead of on every
13
+ pass, page and bound query. Target reads select the manifest's hash and take the manifest from
14
+ memory for a generation and hash already read; an epoch's target and routes, which never change
15
+ after insert, are read once per epoch while its state is read every time. A large ontology's
16
+ replication bookkeeping no longer sends the whole manifest out of the database several times a
17
+ minute. Behavior is unchanged.
18
+
3
19
  ## 0.99.1
4
20
 
5
21
  `check`'s `*:*` warning names only what the role does not already grant by name: the entities an
package/README.md CHANGED
@@ -928,8 +928,15 @@ configured. This preparation does not advertise or enable exact chat posting.
928
928
  A permission is `<entity>:<verb>`. The verbs are `read`, the generated `create`, `update`,
929
929
  `delete`, `link` and `unlink`, and the names of authored actions. A role may use `*` for the
930
930
  entity, the verb or both: `lead:*`, `*:read`, `*:*`. An entity wildcard never covers the
931
- built-in `agent_chat`, `agent_review`, `app_feedback`, `app_feedback_file` or `user_identity`:
932
- reading or changing them needs a permission that names them, such as `agent_chat:read`.
931
+ built-in `agent_chat`, `agent_review`, `app_feedback`, `app_feedback_file`, `user_identity` or
932
+ `workspace_source`: reading or changing them needs a permission that names them, such as
933
+ `agent_chat:read` or `agent_chat:*`.
934
+
935
+ `workspace_source:read` (`WORKSPACE_SOURCE_PERMISSION`) is the built-in permission to read the
936
+ workspace's deployed code through the agent (see [The workspace's code](#the-workspaces-code)).
937
+ `workspace_source` is no entity: `check` refuses any other verb of it, a scoped grant of it, and
938
+ an entity or toolset named `workspace_source`. Only `workspace_source:read` or
939
+ `workspace_source:*` grants it; `*:read`, `*:*` and a pipeline workload's `*:*` do not.
933
940
 
934
941
  - Reads require `<entity>:read`: lists, queries, records, history, both entities of a
935
942
  relationship traversal, and every entity a metric query touches. `include` and a filter through a relationship require `read` on
@@ -1535,6 +1542,20 @@ provider. No other action writes `user_identity`. Revoked bindings are omitted;
1535
1542
  stable and usernames are mutable display metadata. Older databases without channel tables
1536
1543
  remain readable. Use `segmentstream ontology member list --via PROVIDER` to find a member UUID.
1537
1544
 
1545
+ ### The workspace's code
1546
+
1547
+ `GET /api/ontology/agent/source[?cursor=…]` (`WORKSPACE_SOURCE_PATH`) gives the app's agent one
1548
+ page of the workspace's deployed commit, to copy into its sandbox for the member it acts for. Only
1549
+ the production runtime bearer token authenticates, with `X-SegmentStream-Act-As` naming an
1550
+ active paired member; an API key, with delegation or not, and `X-SegmentStream-Agent-Task` are
1551
+ refused. A member who is inactive, unpaired or without `workspace_source:read` gets 403
1552
+ `permission_denied` before SegmentStream is called. The route forwards the cursor to
1553
+ SegmentStream with the request's Vercel OIDC token, the organization and the member's id, and
1554
+ answers with SegmentStream's status, body (a gzip-compressed tar archive, or a JSON error) and
1555
+ `x-segmentstream-source-*` headers unchanged. Without a Vercel OIDC token it answers 503
1556
+ `workspace_source_unavailable`. It logs `ontology.workspace_source.page` with the request, the
1557
+ member and the commit, never a path. It is no MCP tool.
1558
+
1538
1559
  ### Agent attachments
1539
1560
 
1540
1561
  Attachments remain separate member-authorized capabilities. Chat posting accepts text only;
package/dist/analyze.js CHANGED
@@ -8,7 +8,7 @@ import { CONNECTION_KEY, isConnection } from "./connection.js";
8
8
  import { isEntity } from "./entity.js";
9
9
  import { QUERY_METRICS_ROUTE, LEGACY_MEMBER_NAME, ENTITY_ID, GENERATED_ACTIONS, GENERATED_UPSERT_PREFIX, HISTORY_SUFFIX, MCP_METRIC_TOOLS, MCP_READ_TOOLS, MCP_TOOL_NAME_MAX_LENGTH, MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, mcpToolName, RESERVED_ENTITY_NAMES, RESERVED_MEMBER_NAMES, RESERVED_RELATIONSHIP_NAMES, SNAKE_CASE_NAME, SYSTEM_PROPERTIES, humanize, isSystemProperty, toCamelCase, } from "./names.js";
10
10
  import { REFERENCE_ANNOTATION, propertyDefinition, propertyOptionNames, unknownPropertyOptions, referenceTarget, } from "./property.js";
11
- import { EXPLICIT_GRANT_ENTITIES, generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, } from "./permissions.js";
11
+ import { EXPLICIT_GRANT_ENTITIES, generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, WORKSPACE_SOURCE, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
12
12
  import { ON_DELETE, isRelationship } from "./relationship.js";
13
13
  import { isRole, member, role } from "./role.js";
14
14
  import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isSignInPolicy, isSignUpChannel, } from "./sign-in.js";
@@ -920,6 +920,11 @@ function resolveToolsets(declared, entities, connections, report) {
920
920
  report("reserved-name", path, `${name} is reserved: the service's own tools or routes start with it; rename the toolset.`);
921
921
  return;
922
922
  }
923
+ if (name === WORKSPACE_SOURCE) {
924
+ report("reserved-name", path, `${name} names the built-in permission ${WORKSPACE_SOURCE_PERMISSION}, which reads the ` +
925
+ "workspace's code; rename the toolset.");
926
+ return;
927
+ }
923
928
  const definition = candidate.definition;
924
929
  if (!isPlainObject(definition)) {
925
930
  report("invalid-toolset", path, "a toolset takes { connection, api, lock, description }.");
@@ -1503,6 +1508,10 @@ function resolveEntity(candidate, scope, resolvedProperties) {
1503
1508
  else if (RESERVED_ENTITY_NAMES.includes(name)) {
1504
1509
  report("reserved-name", name, `/api/ontology/${name} is a route of the ontology service.`);
1505
1510
  }
1511
+ else if (name === WORKSPACE_SOURCE) {
1512
+ report("reserved-name", name, `${WORKSPACE_SOURCE} names the built-in permission ${WORKSPACE_SOURCE_PERMISSION}, which ` +
1513
+ "reads the workspace's code; choose another entity name.");
1514
+ }
1506
1515
  else if (APP_FEEDBACK_ENTITIES.some((feedback) => feedback.name === name) &&
1507
1516
  !scope.builtIns.has(definition)) {
1508
1517
  report("reserved-name", name, `${name} is the SDK's app feedback; configure feedback on defineOntology ` +
@@ -2239,7 +2248,8 @@ function ownMembers(candidate, entitiesByName) {
2239
2248
  /**
2240
2249
  * The verbs each entity has: `read`, its generated actions, and what its actions require. The
2241
2250
  * built-in user also has its member management verbs, and the built-in sign-in identities their
2242
- * attach and revoke, which roles may grant.
2251
+ * attach and revoke, which roles may grant. The built-in `workspace_source`, which is no entity,
2252
+ * has `read` only.
2243
2253
  */
2244
2254
  function knownVerbs(entities, toolsets = []) {
2245
2255
  const verbs = new Map();
@@ -2275,6 +2285,8 @@ function knownVerbs(entities, toolsets = []) {
2275
2285
  }
2276
2286
  }
2277
2287
  }
2288
+ // Last, so that an entity or a toolset of the name, which check refuses, adds no verb to it.
2289
+ verbs.set(WORKSPACE_SOURCE, new Set([READ_VERB]));
2278
2290
  return verbs;
2279
2291
  }
2280
2292
  /** Why a role's permission matches nothing in the ontology, or `undefined` when it matches. */
@@ -2790,6 +2802,11 @@ function checkScope(input) {
2790
2802
  "permission by name, such as staff_member:update, or list the wildcard as a string.");
2791
2803
  return;
2792
2804
  }
2805
+ if (parsed.entity === WORKSPACE_SOURCE && parsed.verb === READ_VERB) {
2806
+ report("invalid-scope", path, `${permission} reads the workspace's code, which has no records to scope; list ` +
2807
+ `${WORKSPACE_SOURCE_PERMISSION} as a string in the roles that may read the code.`);
2808
+ return;
2809
+ }
2793
2810
  const entity = entities.find((candidate) => candidate.name === parsed.entity);
2794
2811
  if (entity === undefined && verbs.get(parsed.entity)?.has(parsed.verb) === true) {
2795
2812
  report("invalid-scope", path, `${parsed.entity} is a toolset, which has no records to scope; list ${permission} as a ` +
package/dist/index.d.ts CHANGED
@@ -33,7 +33,7 @@ export { check, defineOntology } from "./ontology.js";
33
33
  export { webhookDeliveryJsonSchema } from "./analyze.js";
34
34
  export { webhookToken, webhookTokenMatches, WEBHOOK_TOKEN_CONTEXT } from "./webhook-token.js";
35
35
  export type { Ontology } from "./ontology.js";
36
- export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, } from "./permissions.js";
36
+ export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
37
37
  export type { ParsedPermission, PermissionHolder, RolePermissions, ScopedPermission, ScopeFilter, ScopeValue, ScopeWhere, UserMemberVerb, } from "./permissions.js";
38
38
  export { p, PROPERTY_TYPES, propertyDefinition } from "./property.js";
39
39
  export type { AnyProperty, NumberOptions, Property, PropertyDefinition, PropertyOf, PropertyOptions, BlobOptions, ListOptions, PropertyType, ReferenceOptions, SelectOption, SelectOptionInput, TextOptions, } from "./property.js";
@@ -90,6 +90,7 @@ export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelS
90
90
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
91
91
  export { AGENT_PATH } from "./service/agent/server.js";
92
92
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
93
+ export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
93
94
  export { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_TASK_HEADER, } from "./service/runtime-identity.js";
94
95
  export type { RuntimeIdentityConfig } from "./service/runtime-identity.js";
95
96
  export { MCP_PATH, MCP_PROTOCOL_VERSIONS } from "./service/mcp/server.js";
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire
19
19
  export { check, defineOntology } from "./ontology.js";
20
20
  export { webhookDeliveryJsonSchema } from "./analyze.js";
21
21
  export { webhookToken, webhookTokenMatches, WEBHOOK_TOKEN_CONTEXT } from "./webhook-token.js";
22
- export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, } from "./permissions.js";
22
+ export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
23
23
  export { p, PROPERTY_TYPES, propertyDefinition } from "./property.js";
24
24
  export { ON_DELETE, rel } from "./relationship.js";
25
25
  export { renderCatalog } from "./render.js";
@@ -56,6 +56,7 @@ export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from
56
56
  // workflow's user in the tasks workflows hand it.
57
57
  export { AGENT_PATH } from "./service/agent/server.js";
58
58
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
59
+ export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
59
60
  export { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_TASK_HEADER, } from "./service/runtime-identity.js";
60
61
  // The MCP server the service serves beside the HTTP API.
61
62
  export { MCP_PATH, MCP_PROTOCOL_VERSIONS } from "./service/mcp/server.js";
@@ -20,9 +20,21 @@ export declare const READ_VERB = "read";
20
20
  * identities hold every member's external accounts, such as their Telegram id and username: only a
21
21
  * role that names `user_identity` reads them. The agent's held replies hold the workspace's
22
22
  * chats with the people it serves, and approving one sends it: only a role that names
23
- * `agent_review` reads, approves or rejects them.
23
+ * `agent_review` reads, approves or rejects them. The workspace's deployed code is no entity, but
24
+ * {@link WORKSPACE_SOURCE_PERMISSION} is covered the same way: `workspace_source:read` or
25
+ * `workspace_source:*` grants it, `*:read` and `*:*` do not.
24
26
  */
25
27
  export declare const EXPLICIT_GRANT_ENTITIES: ReadonlySet<string>;
28
+ /**
29
+ * The built-in permission's entity for the workspace's deployed code. It names no entity: `check`
30
+ * refuses an entity or a toolset of this name, and any verb of it but `read`.
31
+ */
32
+ export declare const WORKSPACE_SOURCE = "workspace_source";
33
+ /**
34
+ * Reading the workspace's deployed code, which the app's agent copies into its sandbox for the
35
+ * member it acts for, through `GET /api/ontology/agent/source`. Only a role that names it grants it.
36
+ */
37
+ export declare const WORKSPACE_SOURCE_PERMISSION = "workspace_source:read";
26
38
  /**
27
39
  * The verbs of the built-in user's member management: inviting a member, granting and revoking
28
40
  * roles, and deactivating and reactivating a member. Like every other verb on `user` but `read` and
@@ -153,7 +165,7 @@ export interface PermissionHolder {
153
165
  /**
154
166
  * Whether the principal may do what `required` names: one of its permissions equals it, or covers it
155
167
  * through a wildcard. Workload wildcards exclude user administration, feedback, the agent's held
156
- * replies and writes of sign-in identities.
168
+ * replies, the workspace's code and writes of sign-in identities.
157
169
  */
158
170
  export declare function isAllowed(required: string, principal: PermissionHolder): boolean;
159
171
  /**
@@ -19,7 +19,9 @@ export const READ_VERB = "read";
19
19
  * identities hold every member's external accounts, such as their Telegram id and username: only a
20
20
  * role that names `user_identity` reads them. The agent's held replies hold the workspace's
21
21
  * chats with the people it serves, and approving one sends it: only a role that names
22
- * `agent_review` reads, approves or rejects them.
22
+ * `agent_review` reads, approves or rejects them. The workspace's deployed code is no entity, but
23
+ * {@link WORKSPACE_SOURCE_PERMISSION} is covered the same way: `workspace_source:read` or
24
+ * `workspace_source:*` grants it, `*:read` and `*:*` do not.
23
25
  */
24
26
  export const EXPLICIT_GRANT_ENTITIES = new Set([
25
27
  "agent_chat",
@@ -27,7 +29,18 @@ export const EXPLICIT_GRANT_ENTITIES = new Set([
27
29
  "app_feedback",
28
30
  "app_feedback_file",
29
31
  "user_identity",
32
+ "workspace_source",
30
33
  ]);
34
+ /**
35
+ * The built-in permission's entity for the workspace's deployed code. It names no entity: `check`
36
+ * refuses an entity or a toolset of this name, and any verb of it but `read`.
37
+ */
38
+ export const WORKSPACE_SOURCE = "workspace_source";
39
+ /**
40
+ * Reading the workspace's deployed code, which the app's agent copies into its sandbox for the
41
+ * member it acts for, through `GET /api/ontology/agent/source`. Only a role that names it grants it.
42
+ */
43
+ export const WORKSPACE_SOURCE_PERMISSION = `${WORKSPACE_SOURCE}:${READ_VERB}`;
31
44
  /** The built-in user's entity name in permissions. */
32
45
  const USER_ENTITY = "user";
33
46
  /**
@@ -154,10 +167,10 @@ function isUserAdministration(required) {
154
167
  !wildcardEntityCovers(USER_ENTITY, toSnakeCase(wanted.verb)));
155
168
  }
156
169
  /**
157
- * Feedback and the agent's held replies always need named grants, including for pipeline
158
- * workloads: nothing a pipeline runs approves a reply to a person. The workspace's own pipeline
159
- * code reads sign-in identities, for example to address a member in a chat, but nothing it runs
160
- * writes them: only the platform does.
170
+ * Feedback, the agent's held replies and the workspace's code always need named grants, including
171
+ * for pipeline workloads: nothing a pipeline runs approves a reply to a person or reads the code it
172
+ * runs from. The workspace's own pipeline code reads sign-in identities, for example to address a
173
+ * member in a chat, but nothing it runs writes them: only the platform does.
161
174
  */
162
175
  function workloadWildcardCovers(required) {
163
176
  const wanted = parsePermission(required);
@@ -166,12 +179,12 @@ function workloadWildcardCovers(required) {
166
179
  }
167
180
  return (!isUserAdministration(required) &&
168
181
  (wanted === undefined ||
169
- !["app_feedback", "app_feedback_file", "agent_review"].includes(toSnakeCase(wanted.entity))));
182
+ !["app_feedback", "app_feedback_file", "agent_review", WORKSPACE_SOURCE].includes(toSnakeCase(wanted.entity))));
170
183
  }
171
184
  /**
172
185
  * Whether the principal may do what `required` names: one of its permissions equals it, or covers it
173
186
  * through a wildcard. Workload wildcards exclude user administration, feedback, the agent's held
174
- * replies and writes of sign-in identities.
187
+ * replies, the workspace's code and writes of sign-in identities.
175
188
  */
176
189
  export function isAllowed(required, principal) {
177
190
  return (
@@ -39,13 +39,19 @@ interface BaselineInput {
39
39
  readonly newSource?: boolean;
40
40
  }
41
41
  /** Enable capture in a short fenced transaction before scanning any business records. */
42
- export declare const prepareReplicationBaseline: (sql: SqlClient.SqlClient, input: BaselineInput) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
42
+ export declare const prepareReplicationBaseline: (sql: SqlClient.SqlClient, input: BaselineInput) => Effect.Effect<Omit<ReplicationTarget, "manifest" | "manifest_hash"> & {
43
+ readonly manifest: OntologyManifest;
44
+ }, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
43
45
  /**
44
46
  * Commit one keyset page and its cursor together. Schema 5 locks source rows before allocating
45
47
  * snapshot revisions; older schemas retain their revision-zero baseline protocol. A failed page
46
48
  * retries without changing earlier pages, and capture covers inserts/deletes across pages.
47
49
  */
48
- export declare const advanceReplicationBaseline: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
50
+ export declare const advanceReplicationBaseline: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<Omit<ReplicationTarget, "manifest" | "manifest_hash"> & {
51
+ readonly manifest: OntologyManifest;
52
+ }, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
49
53
  /** Prepare once, then advance a bounded page; subsequent calls resume the same durable target. */
50
- export declare const createReplicationBaseline: (sql: SqlClient.SqlClient, input: BaselineInput) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
54
+ export declare const createReplicationBaseline: (sql: SqlClient.SqlClient, input: BaselineInput) => Effect.Effect<Omit<ReplicationTarget, "manifest" | "manifest_hash"> & {
55
+ readonly manifest: OntologyManifest;
56
+ }, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
51
57
  export {};
@@ -5,12 +5,13 @@ import { joinColumnNames, joinTableName, quoteIdentifier as qi, quoteLiteral as
5
5
  import { REPLICATION_RECORD_BYTES, validateReplicationSelection, } from "./model.js";
6
6
  import { REPLICATION_TARGET_FILLS, REPLICATION_TARGET_METADATA, snapshotExpression, } from "./schema.js";
7
7
  import { lockReplicationLifecycle, shareReplicationLifecycle } from "./transaction.js";
8
+ import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
8
9
  import { initialReplicationLineage } from "./lineage.js";
9
10
  import { scheduleReplicationScans, replicationScanScopes, advanceReplicationScan, } from "./scans.js";
10
11
  /** An initial scan cannot be created with the requested state or record projection. */
11
12
  export class ReplicationBaselineFailed extends Schema.TaggedError()("ReplicationBaselineFailed", { message: Schema.String, cause: Schema.optionalKey(Schema.Unknown) }) {
12
13
  }
13
- const targetSql = `SELECT generation::text, source_id::text, from_revision::text, manifest,
14
+ const targetSql = `SELECT generation::text, source_id::text, from_revision::text, ${TARGET_MANIFEST_HASH},
14
15
  selection, protocol, baseline_complete, backfill_complete, initial_revision::text,
15
16
  ${REPLICATION_TARGET_FILLS}, ${REPLICATION_TARGET_METADATA}, replay_complete, baseline_cursor
16
17
  FROM _ontology_replication_targets WHERE generation = $1::uuid`;
@@ -25,7 +26,9 @@ export const prepareReplicationBaseline = (sql, input) => sql.withTransaction(Ef
25
26
  message: "Run the ontology SDK migration before enabling replication.",
26
27
  });
27
28
  }
28
- const [existing] = yield* sql.unsafe(targetSql, [input.generation]);
29
+ const [existing] = yield* storedTargets(sql, targetSql, [
30
+ input.generation,
31
+ ]);
29
32
  if (existing) {
30
33
  return existing;
31
34
  }
@@ -72,7 +75,7 @@ export const prepareReplicationBaseline = (sql, input) => sql.withTransaction(Ef
72
75
  initial: true,
73
76
  });
74
77
  }
75
- const [target] = yield* sql.unsafe(targetSql, [input.generation]);
78
+ const [target] = yield* storedTargets(sql, targetSql, [input.generation]);
76
79
  if (state.version >= 6) {
77
80
  yield* enableShadowCapture(sql, target, replicationScanScopes(target));
78
81
  }
@@ -129,14 +132,14 @@ export const advanceReplicationBaseline = (sql, generation) => Effect.gen(functi
129
132
  const [version] = yield* sql.unsafe("SELECT version FROM _ontology_replication WHERE id");
130
133
  if ((version?.version ?? 4) >= 5) {
131
134
  yield* advanceReplicationScan(sql, generation);
132
- const [target] = yield* sql.unsafe(targetSql, [generation]);
135
+ const [target] = yield* storedTargets(sql, targetSql, [generation]);
133
136
  return target;
134
137
  }
135
138
  const progress = yield* sql.withTransaction(Effect.gen(function* () {
136
139
  yield* sql.unsafe("SET LOCAL statement_timeout = '30s'");
137
140
  yield* sql.unsafe("SET LOCAL lock_timeout = '5s'");
138
141
  yield* shareReplicationLifecycle(sql);
139
- const [target] = yield* sql.unsafe(`${targetSql} FOR NO KEY UPDATE`, [generation]);
142
+ const [target] = yield* storedTargets(sql, `${targetSql} FOR NO KEY UPDATE`, [generation]);
140
143
  if (!target) {
141
144
  return yield* new ReplicationBaselineFailed({
142
145
  message: "The replication target is missing.",
@@ -205,7 +208,7 @@ export const advanceReplicationBaseline = (sql, generation) => Effect.gen(functi
205
208
  yield* sql.unsafe(`UPDATE _ontology_replication_targets SET baseline_complete = true,
206
209
  initial_revision = (SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM _ontology_replication_revision)
207
210
  WHERE generation = $1::uuid AND NOT baseline_complete`, [generation]);
208
- const [target] = yield* sql.unsafe(targetSql, [generation]);
211
+ const [target] = yield* storedTargets(sql, targetSql, [generation]);
209
212
  return target;
210
213
  }));
211
214
  });
@@ -4,6 +4,7 @@ import { joinColumnNames, joinTableName, quoteIdentifier as qi, quoteLiteral as
4
4
  import { REPLICATION_RECORD_BYTES } from "./model.js";
5
5
  import { snapshotExpression } from "./schema.js";
6
6
  import { lockReplicationLifecycle, shareReplicationLifecycle } from "./transaction.js";
7
+ import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
7
8
  export function replicationScanScopes(target) {
8
9
  return target.selection.flatMap((item) => [
9
10
  { entityId: item.entityId, kind: "entity" },
@@ -58,7 +59,8 @@ export const advanceReplicationScan = (sql, generation) => Effect.gen(function*
58
59
  yield* sql.unsafe("SET LOCAL statement_timeout = '30s'");
59
60
  yield* sql.unsafe("SET LOCAL lock_timeout = '5s'");
60
61
  yield* shareReplicationLifecycle(sql);
61
- const [target] = yield* sql.unsafe(`SELECT * FROM _ontology_replication_targets WHERE generation = $1::uuid FOR NO KEY UPDATE`, [generation]);
62
+ const [target] = yield* storedTargets(sql, `SELECT generation::text, source_id::text, selection, ${TARGET_MANIFEST_HASH}
63
+ FROM _ontology_replication_targets WHERE generation = $1::uuid FOR NO KEY UPDATE`, [generation]);
62
64
  const [state] = yield* sql.unsafe("SELECT enabled, active_generation::text, version FROM _ontology_replication WHERE id");
63
65
  if (!target || !state?.enabled || state.active_generation !== generation) {
64
66
  return { finish: false, progressed: false };
@@ -7,11 +7,13 @@ import { ReplicationBaselineFailed } from "./baseline.js";
7
7
  import { initialReplicationLineage, renamedReplicationField } from "./lineage.js";
8
8
  import { replicationScanScopes, scheduleReplicationScans, } from "./scans.js";
9
9
  import { lockReplicationLifecycle } from "./transaction.js";
10
+ import { rememberJson, rememberedJson } from "./stored-manifests.js";
10
11
  export const SHADOW_HANDOFF_MS = 30_000;
11
12
  export const SHADOW_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
12
13
  export const SHADOW_QUERY_LIFETIME_MS = 60 * 60 * 1000;
13
14
  const shadowJson = (value) => JSON.stringify(value, (_key, item) => (typeof item === "bigint" ? item.toString() : item));
14
- const epochFields = `id::text, source_id::text, desired_hash, target, routes, state,
15
+ /** An epoch's state; its target and routes, which never change after insert, are read apart. */
16
+ const epochFields = `id::text, source_id::text, desired_hash, state,
15
17
  predecessor::text, boundary::text, catchup_boundary::text, token::text, fence::text,
16
18
  handoff_until::text, operation_id::text, installed, cancel_requested`;
17
19
  const segmentFields = `id::text, epoch::text, generation::text, source_id::text,
@@ -82,17 +84,38 @@ export function expandShadowRoutes(routes, target) {
82
84
  return { ...route, target: expanded };
83
85
  });
84
86
  }
85
- const expandEpoch = (row) => row && { ...row, routes: expandShadowRoutes(row.routes, row.target) };
87
+ /**
88
+ * Completes an epoch's state with its target and expanded routes. They hold whole manifests and
89
+ * never change after insert, so a process reads them once per epoch (see `stored-manifests.ts`).
90
+ * An epoch removed between the two reads is read as absent.
91
+ */
92
+ const expandEpoch = (sql, row) => Effect.gen(function* () {
93
+ if (!row) {
94
+ return undefined;
95
+ }
96
+ const key = `epoch:${row.id}:${row.desired_hash}`;
97
+ let body = rememberedJson(key);
98
+ if (!body) {
99
+ const [stored] = yield* sql.unsafe("SELECT target, routes FROM _ontology_replication_epochs WHERE id=$1::uuid", [row.id]);
100
+ if (!stored) {
101
+ return undefined;
102
+ }
103
+ body = stored;
104
+ rememberJson(key, body);
105
+ }
106
+ const target = { ...body.target };
107
+ return { ...row, target, routes: expandShadowRoutes(body.routes, target) };
108
+ });
86
109
  export const shadowEpoch = (sql, id) => sql
87
110
  .unsafe(`SELECT ${epochFields} FROM _ontology_replication_epochs WHERE id=$1::uuid`, [id])
88
- .pipe(Effect.map((rows) => expandEpoch(rows[0])));
111
+ .pipe(Effect.flatMap((rows) => expandEpoch(sql, rows[0])));
89
112
  export const servingShadowEpoch = (sql) => sql
90
113
  .unsafe(`SELECT ${epochFields} FROM _ontology_replication_epochs
91
114
  WHERE id=(SELECT serving_epoch FROM _ontology_replication WHERE id)`)
92
- .pipe(Effect.map((rows) => expandEpoch(rows[0])));
115
+ .pipe(Effect.flatMap((rows) => expandEpoch(sql, rows[0])));
93
116
  export const candidateShadowEpoch = (sql) => sql
94
117
  .unsafe(`SELECT ${epochFields} FROM _ontology_replication_epochs WHERE state='candidate'`)
95
- .pipe(Effect.map((rows) => expandEpoch(rows[0])));
118
+ .pipe(Effect.flatMap((rows) => expandEpoch(sql, rows[0])));
96
119
  export const shadowProjectionHash = (target) => createHash("sha256")
97
120
  .update(canonicalJson({
98
121
  manifest: target.manifest.hash,
@@ -341,7 +364,7 @@ export const beginShadowHandoff = (sql, id, owner, minimumFence = "0") => sql.wi
341
364
  AND id=(SELECT active_generation FROM _ontology_replication WHERE id AND enabled)
342
365
  AND NOT EXISTS(SELECT 1 FROM _ontology_replication_scans WHERE generation=$1::uuid AND NOT complete)
343
366
  RETURNING ${epochFields}`, [id, owner]);
344
- return expandEpoch(epoch);
367
+ return yield* expandEpoch(sql, epoch);
345
368
  }));
346
369
  /** Destination invalidation must have succeeded (or switched) before this transaction runs. */
347
370
  export const abandonShadowHandoff = (sql, epoch) => sql.withTransaction(Effect.gen(function* () {
@@ -9,9 +9,9 @@ export declare const startReplication: (sql: SqlClient.SqlClient, input: {
9
9
  readonly selection?: ReadonlyArray<ReplicationSelection>;
10
10
  readonly newSource?: boolean;
11
11
  }) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed | import("../index.js").CatalogInvalid | import("./legacy-baseline.js").ReplicationBaselineFailed, never>;
12
- export declare const activeReplicationTarget: (sql: SqlClient.SqlClient) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError, never>;
12
+ export declare const activeReplicationTarget: (sql: SqlClient.SqlClient) => Effect.Effect<ReplicationTarget | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
13
13
  export declare const pauseReplication: (sql: SqlClient.SqlClient) => Effect.Effect<void, import("effect/unstable/sql/SqlError").SqlError, never>;
14
- export declare const replicationTarget: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError, never>;
14
+ export declare const replicationTarget: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<ReplicationTarget | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
15
15
  export { advanceReplicationBaseline };
16
16
  export { replicationInitiallyReady as legacyReplicationInitiallyReady } from "./legacy-store.js";
17
17
  /** Retained history is recovery storage; frequent delivery reads only indexed unaccepted references. */
@@ -12,6 +12,7 @@ import { createReplicationBaseline, advanceReplicationBaseline, ReplicationBasel
12
12
  import { effectiveReplicationExclusions, migratedReplicationFills } from "./migrate.js";
13
13
  import { refreshReplicationProjection } from "./evolution.js";
14
14
  import { REPLICATION_TARGET_FILLS, REPLICATION_TARGET_METADATA } from "./schema.js";
15
+ import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
15
16
  const replicationPolicyKey = (policy) => JSON.stringify(policy
16
17
  .map((item) => ({
17
18
  entityId: item.entityId,
@@ -102,7 +103,7 @@ export const startReplication = (sql, input) => Effect.gen(function* () {
102
103
  ? createReplicationBaseline(sql, { ...input, manifest, selection })
103
104
  : createLegacyBaseline(sql, { ...input, manifest, selection }).pipe(Effect.map((target) => target));
104
105
  }).pipe(Effect.map((target) => target));
105
- const targetFields = `generation::text, source_id::text, from_revision::text, manifest, selection,
106
+ const targetFields = `generation::text, source_id::text, from_revision::text, ${TARGET_MANIFEST_HASH}, selection,
106
107
  protocol, baseline_complete, backfill_complete, initial_revision::text, replay_complete,
107
108
  ${REPLICATION_TARGET_FILLS}, ${REPLICATION_TARGET_METADATA}, 4 AS delivery_version`;
108
109
  const protocol = (sql) => sql
@@ -113,8 +114,11 @@ export const activeReplicationTarget = (sql) => Effect.gen(function* () {
113
114
  const fields = version >= 4
114
115
  ? targetFields
115
116
  : "generation::text, source_id::text, from_revision::text, manifest, selection";
116
- const rows = yield* sql.unsafe(`SELECT ${fields} FROM _ontology_replication_targets
117
- WHERE generation = (SELECT active_generation FROM _ontology_replication WHERE id)`);
117
+ const statement = `SELECT ${fields} FROM _ontology_replication_targets
118
+ WHERE generation = (SELECT active_generation FROM _ontology_replication WHERE id)`;
119
+ const rows = version >= 4
120
+ ? yield* storedTargets(sql, statement)
121
+ : yield* sql.unsafe(statement);
118
122
  return rows[0];
119
123
  });
120
124
  export const pauseReplication = (sql) => sql.withTransaction(Effect.gen(function* () {
@@ -126,7 +130,10 @@ export const replicationTarget = (sql, generation) => Effect.gen(function* () {
126
130
  const fields = version >= 4
127
131
  ? targetFields
128
132
  : "generation::text, source_id::text, from_revision::text, manifest, selection";
129
- const rows = yield* sql.unsafe(`SELECT ${fields} FROM _ontology_replication_targets WHERE generation = $1::uuid`, [generation]);
133
+ const statement = `SELECT ${fields} FROM _ontology_replication_targets WHERE generation = $1::uuid`;
134
+ const rows = version >= 4
135
+ ? yield* storedTargets(sql, statement, [generation])
136
+ : yield* sql.unsafe(statement, [generation]);
130
137
  return rows[0];
131
138
  });
132
139
  export { advanceReplicationBaseline };
@@ -309,7 +316,7 @@ export const advanceReplicationReplay = (sql, generation) => sql.withTransaction
309
316
  /** Static pre-upgrade histories have no new inserts: v4 writers atomically enqueue new history. */
310
317
  export const advanceReplicationBackfill = (sql, generation) => sql.withTransaction(Effect.gen(function* () {
311
318
  yield* shareReplicationLifecycle(sql);
312
- const [target] = yield* sql.unsafe(`SELECT ${targetFields}, backfill_cursor, backfill_revision::text
319
+ const [target] = yield* storedTargets(sql, `SELECT ${targetFields}, backfill_cursor, backfill_revision::text
313
320
  FROM _ontology_replication_targets WHERE generation = $1::uuid FOR NO KEY UPDATE`, [generation]);
314
321
  if (!target || target.backfill_complete) {
315
322
  return true;
@@ -0,0 +1,25 @@
1
+ import { Effect } from "effect";
2
+ import type { SqlClient } from "effect/unstable/sql";
3
+ import type { OntologyManifest } from "../manifest.js";
4
+ /** The value stored under a key, marked as most recently used; undefined when not remembered. */
5
+ export declare function rememberedJson<A>(key: string): A | undefined;
6
+ /** Keep a value under a key, evicting the least recently used entries past the length bound. */
7
+ export declare function rememberJson(key: string, value: unknown): void;
8
+ /** Forget every remembered value; for tests that reuse ids across databases. */
9
+ export declare function forgetStoredManifests(): void;
10
+ /** Selects a target's manifest hash in place of its manifest; `storedTargets` restores it. */
11
+ export declare const TARGET_MANIFEST_HASH = "manifest->>'hash' AS manifest_hash";
12
+ type WithManifest<T> = Omit<T, "manifest_hash" | "manifest"> & {
13
+ readonly manifest: OntologyManifest;
14
+ };
15
+ /**
16
+ * Run a target read that selects `TARGET_MANIFEST_HASH` (and `generation`) instead of the manifest,
17
+ * and return its rows with the manifest restored: from memory for a generation and hash already
18
+ * read, otherwise from the target row itself. A migration can change a target between the read and
19
+ * its manifest's read; the whole read is then repeated, so a target never pairs one version's
20
+ * fields with another version's manifest.
21
+ */
22
+ export declare const storedTargets: <T extends {
23
+ readonly generation: string;
24
+ }>(sql: SqlClient.SqlClient, statement: string, parameters?: ReadonlyArray<unknown>) => Effect.Effect<WithManifest<T>[], import("effect/unstable/sql/SqlError").SqlError, never>;
25
+ export {};
@@ -0,0 +1,93 @@
1
+ import { Effect } from "effect";
2
+ /**
3
+ * A replication target carries the workspace's whole manifest, megabytes for a large ontology, and
4
+ * replication reads its targets and epochs on every pass, page and bound query. A stored target's
5
+ * manifest changes only together with its hash, and an epoch's target and routes never change after
6
+ * the epoch is inserted. Readers therefore select the hash or the epoch's identity instead, and take
7
+ * the large JSON from this process's memory, reading it from the database once per process for each
8
+ * one it has not seen. Keys hold the generation or epoch id, so no two workspaces share an entry.
9
+ */
10
+ /** The JSON length a process keeps; a large ontology's target and epoch fit many times over. */
11
+ const REMEMBERED_LENGTH = 64 * 1024 * 1024;
12
+ const remembered = new Map();
13
+ let rememberedLength = 0;
14
+ /** The value stored under a key, marked as most recently used; undefined when not remembered. */
15
+ export function rememberedJson(key) {
16
+ const entry = remembered.get(key);
17
+ if (entry === undefined) {
18
+ return undefined;
19
+ }
20
+ remembered.delete(key);
21
+ remembered.set(key, entry);
22
+ return entry.value;
23
+ }
24
+ /** Keep a value under a key, evicting the least recently used entries past the length bound. */
25
+ export function rememberJson(key, value) {
26
+ const length = JSON.stringify(value)?.length ?? 0;
27
+ const previous = remembered.get(key);
28
+ if (previous) {
29
+ remembered.delete(key);
30
+ rememberedLength -= previous.length;
31
+ }
32
+ if (length > REMEMBERED_LENGTH) {
33
+ return;
34
+ }
35
+ remembered.set(key, { value, length });
36
+ rememberedLength += length;
37
+ for (const [oldest, entry] of remembered) {
38
+ if (rememberedLength <= REMEMBERED_LENGTH) {
39
+ break;
40
+ }
41
+ remembered.delete(oldest);
42
+ rememberedLength -= entry.length;
43
+ }
44
+ }
45
+ /** Forget every remembered value; for tests that reuse ids across databases. */
46
+ export function forgetStoredManifests() {
47
+ remembered.clear();
48
+ rememberedLength = 0;
49
+ }
50
+ /** Selects a target's manifest hash in place of its manifest; `storedTargets` restores it. */
51
+ export const TARGET_MANIFEST_HASH = "manifest->>'hash' AS manifest_hash";
52
+ /** Reads of a target that a concurrent migration may change between its two statements. */
53
+ const CONSISTENT_READ_ATTEMPTS = 5;
54
+ /**
55
+ * Run a target read that selects `TARGET_MANIFEST_HASH` (and `generation`) instead of the manifest,
56
+ * and return its rows with the manifest restored: from memory for a generation and hash already
57
+ * read, otherwise from the target row itself. A migration can change a target between the read and
58
+ * its manifest's read; the whole read is then repeated, so a target never pairs one version's
59
+ * fields with another version's manifest.
60
+ */
61
+ export const storedTargets = (sql, statement, parameters = []) => Effect.gen(function* () {
62
+ for (let attempt = 1; attempt <= CONSISTENT_READ_ATTEMPTS; attempt += 1) {
63
+ const targets = yield* readStoredTargets(sql, statement, parameters);
64
+ if (targets) {
65
+ return targets;
66
+ }
67
+ }
68
+ return yield* Effect.die(new Error("A replication target kept changing while it was read; the next pass retries."));
69
+ });
70
+ /** One attempt: the rows with their manifests, or undefined when a row changed between reads. */
71
+ const readStoredTargets = (sql, statement, parameters) => Effect.gen(function* () {
72
+ const rows = yield* sql.unsafe(statement, parameters);
73
+ const targets = [];
74
+ for (const row of rows) {
75
+ const { manifest_hash: hash, ...rest } = row;
76
+ const key = `target:${row.generation}:${hash}`;
77
+ let manifest = hash ? rememberedJson(key) : undefined;
78
+ if (!manifest) {
79
+ const [stored] = yield* sql.unsafe(`SELECT manifest, ${TARGET_MANIFEST_HASH} FROM _ontology_replication_targets
80
+ WHERE generation = $1::uuid`, [row.generation]);
81
+ // Removed or migrated since the first read: read the whole target again.
82
+ if (!stored || (stored.manifest_hash ?? null) !== (hash ?? null)) {
83
+ return undefined;
84
+ }
85
+ manifest = stored.manifest;
86
+ if (hash) {
87
+ rememberJson(key, manifest);
88
+ }
89
+ }
90
+ targets.push({ ...rest, manifest });
91
+ }
92
+ return targets;
93
+ });
@@ -2,6 +2,7 @@ import { Effect, Redacted } from "effect";
2
2
  import { HttpServerRequest } from "effect/unstable/http";
3
3
  import type { AttachmentCaller } from "../../storage/attachments.js";
4
4
  import { RequestId } from "../errors.js";
5
+ import type { Principal } from "../../runtime.js";
5
6
  import type { AgentStore, OntologyBackend } from "../runtime-contract.js";
6
7
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
7
8
  export declare const CHAT_HEADER = "x-segmentstream-agent-chat";
@@ -26,6 +27,25 @@ export declare function authenticateAgentCaller(input: {
26
27
  readonly caller: AttachmentCaller;
27
28
  readonly response?: undefined;
28
29
  }, never, RequestId | HttpServerRequest.ParsedSearchParams>;
30
+ /**
31
+ * Authenticate the deployment's own runtime acting for the member `X-SegmentStream-Act-As` names,
32
+ * on a route only that runtime calls: an API key, with delegation or not, and a task's secret are
33
+ * refused. `member` is the member with the roles they hold now, or `undefined` when the header names
34
+ * nobody who is active and paired with the agent; the route decides how to refuse them.
35
+ */
36
+ export declare function authenticateAgentRuntimeMember(input: {
37
+ readonly request: HttpServerRequest.HttpServerRequest;
38
+ readonly agents: AgentStore;
39
+ readonly verify: RuntimeTokenVerifier;
40
+ }): Effect.Effect<{
41
+ readonly ok: false;
42
+ readonly response: import("effect/unstable/http/HttpServerResponse").HttpServerResponse;
43
+ readonly member?: undefined;
44
+ } | {
45
+ readonly ok: true;
46
+ readonly member: Principal | undefined;
47
+ readonly response?: undefined;
48
+ }, never, RequestId | HttpServerRequest.ParsedSearchParams>;
29
49
  /** Resolves an `ssk_` key to its user and whether it acts with delegation. */
30
50
  export type ApiKeyCredentialResolver = NonNullable<OntologyBackend["Service"]["resolveApiKeyCredential"]>;
31
51
  /**
@@ -29,21 +29,9 @@ export function authenticateAgentCaller(input) {
29
29
  }
30
30
  return agentCaller(request, requestId, delegated.member, delegated.client);
31
31
  }
32
- const verified = token === "" ? undefined : yield* Effect.promise(() => verify(token));
33
- switch (verified?.status) {
34
- case "valid":
35
- break;
36
- case "invalid":
37
- yield* logRuntimeRejection(verified.reason);
38
- return denied(unauthorized(requestId, "The bearer token is invalid, expired or revoked."));
39
- case "unavailable":
40
- return denied(unavailable(requestId));
41
- default:
42
- return denied(forbidden(requestId, "Only the app's agent calls this route."));
43
- }
44
- // Attachments and member files are a member's; a task, acting as a workflow's user, has none.
45
- if (agentTaskSecret(request) !== undefined) {
46
- return denied(forbidden(requestId, `This route does not accept ${AGENT_TASK_HEADER}.`));
32
+ const refused = yield* refuseUnlessRuntime(request, token, verify);
33
+ if (refused !== undefined) {
34
+ return { ok: false, response: refused };
47
35
  }
48
36
  const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
49
37
  const member = actAs === ""
@@ -59,6 +47,52 @@ export function authenticateAgentCaller(input) {
59
47
  return agentCaller(request, requestId, member);
60
48
  });
61
49
  }
50
+ /**
51
+ * The answer refusing an agent route's bearer token unless it is the deployment's own runtime token
52
+ * and the request presents no task's secret; `undefined` when it is admitted.
53
+ */
54
+ function refuseUnlessRuntime(request, token, verify) {
55
+ return Effect.gen(function* () {
56
+ const requestId = yield* RequestId;
57
+ const verified = token === "" ? undefined : yield* Effect.promise(() => verify(token));
58
+ switch (verified?.status) {
59
+ case "valid":
60
+ break;
61
+ case "invalid":
62
+ yield* logRuntimeRejection(verified.reason);
63
+ return toServerResponse(unauthorized(requestId, "The bearer token is invalid, expired or revoked."));
64
+ case "unavailable":
65
+ return toServerResponse(unavailable(requestId));
66
+ default:
67
+ return toServerResponse(forbidden(requestId, "Only the app's agent calls this route."));
68
+ }
69
+ // Attachments, member files and the workspace's code are a member's; a task, acting as a
70
+ // workflow's user, has none.
71
+ return agentTaskSecret(request) === undefined
72
+ ? undefined
73
+ : toServerResponse(forbidden(requestId, `This route does not accept ${AGENT_TASK_HEADER}.`));
74
+ });
75
+ }
76
+ /**
77
+ * Authenticate the deployment's own runtime acting for the member `X-SegmentStream-Act-As` names,
78
+ * on a route only that runtime calls: an API key, with delegation or not, and a task's secret are
79
+ * refused. `member` is the member with the roles they hold now, or `undefined` when the header names
80
+ * nobody who is active and paired with the agent; the route decides how to refuse them.
81
+ */
82
+ export function authenticateAgentRuntimeMember(input) {
83
+ return Effect.gen(function* () {
84
+ const { request, agents, verify } = input;
85
+ const credential = HttpApiBuilder.securityDecode(HttpApiSecurity.bearer);
86
+ const bearer = yield* Effect.provideService(credential, HttpServerRequest.HttpServerRequest, request);
87
+ const refused = yield* refuseUnlessRuntime(request, Redacted.value(bearer), verify);
88
+ if (refused !== undefined) {
89
+ return { ok: false, response: refused };
90
+ }
91
+ const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
92
+ const member = actAs === "" ? undefined : yield* agents.actingMember(actAs);
93
+ return { ok: true, member: member?.kind === "member" ? member : undefined };
94
+ });
95
+ }
62
96
  /** The chat and session every agent request names, with the member it acts for. */
63
97
  function agentCaller(request, requestId, member, delegatedBy) {
64
98
  const chat = (request.headers[CHAT_HEADER] ?? request.headers[EARLIER_CHAT_HEADER])?.trim() ?? "";
@@ -0,0 +1,29 @@
1
+ import { Layer } from "effect";
2
+ import { HttpRouter } from "effect/unstable/http";
3
+ import { RequestId } from "../errors.js";
4
+ import { OntologyBackend } from "../runtime-contract.js";
5
+ import type { RuntimeTokenVerifier } from "../runtime-identity.js";
6
+ /** `GET /api/ontology/agent/source[?cursor=…]`: a page of the workspace's deployed code. */
7
+ export declare const WORKSPACE_SOURCE_PATH = "/api/ontology/agent/source";
8
+ /** Where the deployed ontology service reaches backend-next, as its connection calls do. */
9
+ export interface WorkspaceSourceEnvironment {
10
+ readonly segmentstreamUrl: string;
11
+ readonly workspaceId: string;
12
+ readonly organizationId: string;
13
+ }
14
+ /**
15
+ * `GET /api/ontology/agent/source[?cursor=…]` (runtime): the app's agent, acting for a member,
16
+ * reads the workspace's deployed code a page at a time to copy it into its sandbox. Only the
17
+ * deployment's runtime token authenticates, never an API key or a task's secret; the member named
18
+ * by `X-SegmentStream-Act-As` must be active, paired with the agent and hold
19
+ * `workspace_source:read`, which no wildcard grants, before backend-next is called. The route
20
+ * forwards the cursor with the request's Vercel OIDC token and answers with backend-next's status,
21
+ * body and `x-segmentstream-source-*` headers as they are. It is no MCP tool, and it is not served
22
+ * without runtime authentication or the agent's tables.
23
+ */
24
+ export declare function workspaceSourceLayer(options: {
25
+ readonly environment: WorkspaceSourceEnvironment;
26
+ readonly verifyRuntime: RuntimeTokenVerifier | undefined;
27
+ /** How the route calls backend-next: `fetch` by default. Tests replace it. */
28
+ readonly fetch?: typeof fetch;
29
+ }): Layer.Layer<never, never, OntologyBackend | HttpRouter.HttpRouter | HttpRouter.Request<"Requires", RequestId>>;
@@ -0,0 +1,128 @@
1
+ import { Effect, Layer, Result } from "effect";
2
+ import { HttpRouter, HttpServerResponse } from "effect/unstable/http";
3
+ import { isAllowed, WORKSPACE_SOURCE_PERMISSION } from "../../permissions.js";
4
+ import { RequestId, errorBodyForWire } from "../errors.js";
5
+ import { describeError } from "../metric-query-platform.js";
6
+ import { identityToken } from "../operations.js";
7
+ import { OntologyBackend } from "../runtime-contract.js";
8
+ import { authenticateAgentRuntimeMember } from "./authentication.js";
9
+ import { AGENT_PATH } from "./server.js";
10
+ /** `GET /api/ontology/agent/source[?cursor=…]`: a page of the workspace's deployed code. */
11
+ export const WORKSPACE_SOURCE_PATH = `${AGENT_PATH}/source`;
12
+ /** The headers of a page that the route passes on as backend-next sent them. */
13
+ const SOURCE_HEADER_PREFIX = "x-segmentstream-source-";
14
+ const COMMIT_HEADER = `${SOURCE_HEADER_PREFIX}commit`;
15
+ /** A page is at most a few megabytes, which backend-next reads from the workspace's repository. */
16
+ const PAGE_TIMEOUT_MS = 60_000;
17
+ const UNAVAILABLE = "workspace_source_unavailable";
18
+ function refusal(status, error, detail, requestId) {
19
+ return HttpServerResponse.jsonUnsafe(errorBodyForWire({ error, detail, requestId }), {
20
+ status,
21
+ headers: { "cache-control": "no-store" },
22
+ });
23
+ }
24
+ /**
25
+ * One page of the deployed commit's files from backend-next, which admits the deployment by its
26
+ * Vercel OIDC token and takes the member's id for its log only.
27
+ */
28
+ function fetchPage(input) {
29
+ const { environment, token, member, cursor, requestId } = input;
30
+ const url = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
31
+ `${encodeURIComponent(environment.workspaceId)}/ontology/source` +
32
+ (cursor === null ? "" : `?cursor=${encodeURIComponent(cursor)}`);
33
+ return Effect.tryPromise({
34
+ try: async (signal) => {
35
+ const response = await input.fetch(url, {
36
+ method: "GET",
37
+ redirect: "error",
38
+ headers: {
39
+ "x-segmentstream-runtime-identity": token,
40
+ "x-segmentstream-organization-id": environment.organizationId,
41
+ "x-segmentstream-ontology-principal": member.id,
42
+ "x-segmentstream-request-id": requestId,
43
+ },
44
+ signal: AbortSignal.any([signal, AbortSignal.timeout(PAGE_TIMEOUT_MS)]),
45
+ });
46
+ const headers = {};
47
+ response.headers.forEach((value, name) => {
48
+ if (name === "content-type" || name.startsWith(SOURCE_HEADER_PREFIX)) {
49
+ headers[name] = value;
50
+ }
51
+ });
52
+ return {
53
+ status: response.status,
54
+ headers,
55
+ body: new Uint8Array(await response.arrayBuffer()),
56
+ };
57
+ },
58
+ catch: (cause) => cause,
59
+ });
60
+ }
61
+ /**
62
+ * `GET /api/ontology/agent/source[?cursor=…]` (runtime): the app's agent, acting for a member,
63
+ * reads the workspace's deployed code a page at a time to copy it into its sandbox. Only the
64
+ * deployment's runtime token authenticates, never an API key or a task's secret; the member named
65
+ * by `X-SegmentStream-Act-As` must be active, paired with the agent and hold
66
+ * `workspace_source:read`, which no wildcard grants, before backend-next is called. The route
67
+ * forwards the cursor with the request's Vercel OIDC token and answers with backend-next's status,
68
+ * body and `x-segmentstream-source-*` headers as they are. It is no MCP tool, and it is not served
69
+ * without runtime authentication or the agent's tables.
70
+ */
71
+ export function workspaceSourceLayer(options) {
72
+ return Layer.effectDiscard(Effect.gen(function* () {
73
+ const router = yield* HttpRouter.HttpRouter;
74
+ const { agents } = yield* OntologyBackend;
75
+ const verify = options.verifyRuntime;
76
+ const fetchImpl = options.fetch ?? fetch;
77
+ if (agents === undefined || verify === undefined) {
78
+ return;
79
+ }
80
+ const page = (request) => Effect.gen(function* () {
81
+ const requestId = yield* RequestId;
82
+ const authenticated = yield* authenticateAgentRuntimeMember({ request, agents, verify });
83
+ if (!authenticated.ok) {
84
+ return authenticated.response;
85
+ }
86
+ const { member } = authenticated;
87
+ if (member === undefined) {
88
+ return refusal(403, "permission_denied", "The member is inactive or has not paired with the agent.", requestId);
89
+ }
90
+ if (!isAllowed(WORKSPACE_SOURCE_PERMISSION, member)) {
91
+ return refusal(403, "permission_denied", `${WORKSPACE_SOURCE_PERMISSION} is required.`, requestId);
92
+ }
93
+ const token = identityToken(request);
94
+ if (token === undefined || token === "") {
95
+ return refusal(503, UNAVAILABLE, "The request carries no Vercel OIDC token. The workspace's code is available to " +
96
+ "production deployments.", requestId);
97
+ }
98
+ const cursor = new URL(request.url, "https://ontology.invalid").searchParams.get("cursor");
99
+ const answered = yield* Effect.result(fetchPage({
100
+ environment: options.environment,
101
+ fetch: fetchImpl,
102
+ token,
103
+ member,
104
+ cursor,
105
+ requestId,
106
+ }));
107
+ if (Result.isFailure(answered)) {
108
+ yield* Effect.logWarning("ontology.workspace_source.unavailable").pipe(Effect.annotateLogs({
109
+ requestId,
110
+ error: describeError(answered.failure, (text) => text.split(token).join("[redacted]")),
111
+ }));
112
+ return refusal(503, UNAVAILABLE, "The workspace's code could not be read.", requestId);
113
+ }
114
+ const { status, headers, body } = answered.success;
115
+ // The member and the commit only: never a path, a cursor or a file.
116
+ yield* Effect.logInfo("ontology.workspace_source.page").pipe(Effect.annotateLogs({
117
+ requestId,
118
+ memberId: member.id,
119
+ commit: headers[COMMIT_HEADER] ?? null,
120
+ }));
121
+ return HttpServerResponse.uint8Array(body, {
122
+ status,
123
+ headers: { ...headers, "cache-control": "no-store" },
124
+ });
125
+ });
126
+ yield* router.add("GET", WORKSPACE_SOURCE_PATH, page);
127
+ }));
128
+ }
@@ -15,6 +15,7 @@ import { neonSignInLinks, segmentstreamSignInLinks } from "../runtime/sign-in-li
15
15
  import { memberFileRoutes } from "./member-file-routes.js";
16
16
  import { attachmentsLayer } from "./agent/attachments.js";
17
17
  import { filesLayer } from "./agent/files.js";
18
+ import { workspaceSourceLayer } from "./agent/source.js";
18
19
  import { platformChatArchive } from "./agent/chat-archive.js";
19
20
  import { archiveRoutes } from "./agent/archive-routes.js";
20
21
  import { makeChatDelivery } from "./chat/delivery.js";
@@ -409,7 +410,7 @@ export function createOntologyService(ontology, config) {
409
410
  chatDelivery,
410
411
  verifyToken,
411
412
  exchangeSession,
412
- }), preview ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), chatHistory === undefined
413
+ }), preview ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
413
414
  ? Layer.empty
414
415
  : archiveRoutes({
415
416
  transport: chatHistory,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.99.1",
3
+ "version": "0.100.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",