@segmentstream/ontology 0.99.2 → 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,12 @@
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
+
3
10
  ## 0.99.2
4
11
 
5
12
  Replication reads a workspace's manifest from its database once per process instead of on every
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 (
@@ -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.2",
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",