@segmentstream/ontology 0.162.0 → 0.163.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.163.0
4
+
5
+ The ontology of an app preview can serve the workspace's agent, built from the preview's commit,
6
+ for the preview app's web chat and for evals. The platform turns it on by giving the preview the
7
+ runtime identity of its hosting project (`SEGMENTSTREAM_RUNTIME_OIDC_ISSUER` and
8
+ `SEGMENTSTREAM_RUNTIME_OIDC_AUDIENCE`); the deployment observation then says `agent: true`, and
9
+ `previewRunsAgent()` reads it. The preview trusts only its hosting project's function tokens that
10
+ name `preview`, and only with `X-SegmentStream-Ontology-Deployment-Id` naming its own deployment
11
+ (`ONTOLOGY_DEPLOYMENT_HEADER`), because every preview of a workspace shares one hosting project.
12
+ It serves agent tokens, their introspection, the chat store, held replies, and members' attachments
13
+ and files, and still none of channels, pairings, accounts, visitors or tasks. Production never
14
+ trusts a preview's tokens. Manifests advertise `workspace-app-preview-agent-v1`.
15
+
16
+ Evals reach that agent as a test member with an agent token of the new first-party client
17
+ `agent-eval` (`AGENT_EVAL_CLIENT_ID`), on the existing grant and token tables. Only the platform
18
+ issues one, with its workload token bound to the preview, at `POST /api/ontology/agent/eval-tokens`
19
+ (`AGENT_EVAL_TOKENS_PATH`), which only a preview that runs the agent mounts. A token works 30
20
+ minutes by default and an hour at most (`EVAL_TOKEN_DEFAULT_SECONDS`, `EVAL_TOKEN_MAX_SECONDS`),
21
+ never past the preview's expiry, has no refresh token, and issuing another ends the member's earlier
22
+ eval session. Introspection answers it as the member's, with `eval: true`, and counts its turns
23
+ against no limit. Outside such a preview the client is refused: introspection answers its tokens
24
+ `active: false` and the agent cannot act with its grants.
25
+
3
26
  ## 0.162.0
4
27
 
5
28
  A draft can carry record files. `agent_draft.files` lists each file the reply carries as
@@ -19,9 +19,19 @@ export type DeploymentObservation = {
19
19
  * Workflow SDK's local world records runs; absent on a hosted preview.
20
20
  */
21
21
  readonly host?: "local";
22
+ /**
23
+ * `true` when the platform runs the workspace's agent in this hosted preview, built from the
24
+ * same commit: it answers the preview app's web chat and evals, with no channels, tasks or
25
+ * connections. The platform marks it by giving the preview the runtime identity its agent
26
+ * authenticates with (`SEGMENTSTREAM_RUNTIME_OIDC_ISSUER` and `…_AUDIENCE`). The managed agent
27
+ * capability, `capabilities.agents`, stays `false`.
28
+ */
29
+ readonly agent?: true;
22
30
  readonly capabilities: DeploymentCapabilities;
23
31
  };
24
- export type DeploymentAdmissionCode = "preview_configuration_invalid" | "preview_expired" | "preview_capability_unavailable" | "preview_authentication_unavailable" | "preview_storage_binding_invalid";
32
+ export type DeploymentAdmissionCode = "preview_configuration_invalid" | "preview_expired" | "preview_capability_unavailable" | "preview_authentication_unavailable"
33
+ /** The runtime of another preview of the workspace called this one. */
34
+ | "preview_deployment_mismatch" | "preview_storage_binding_invalid";
25
35
  /** Stable codes only: workspace code owns explanations and presentation. */
26
36
  export declare class DeploymentAdmissionError extends Error {
27
37
  readonly code: DeploymentAdmissionCode;
@@ -31,5 +41,7 @@ export declare class DeploymentAdmissionError extends Error {
31
41
  get status(): number;
32
42
  }
33
43
  export declare function deploymentFromEnv(environment?: Readonly<Record<string, string | undefined>>): DeploymentObservation;
44
+ /** Whether the platform runs the workspace's agent, without channels, in this hosted preview. */
45
+ export declare function previewRunsAgent(deployment: DeploymentObservation | undefined): boolean;
34
46
  /** Recheck the deadline on every admission, including a warm process and cached sessions. */
35
47
  export declare function requireDeploymentCapability(deployment: DeploymentObservation, capability?: keyof DeploymentCapabilities, now?: number): void;
@@ -45,11 +45,15 @@ export function deploymentFromEnv(environment = process.env) {
45
45
  !Number.isFinite(Date.parse(expiresAt))) {
46
46
  throw new DeploymentAdmissionError("preview_configuration_invalid");
47
47
  }
48
+ const agent = host === undefined &&
49
+ Boolean(environment.SEGMENTSTREAM_RUNTIME_OIDC_ISSUER?.trim()) &&
50
+ Boolean(environment.SEGMENTSTREAM_RUNTIME_OIDC_AUDIENCE?.trim());
48
51
  return Object.freeze({
49
52
  target,
50
53
  deploymentId,
51
54
  expiresAt,
52
55
  ...(host === undefined ? {} : { host }),
56
+ ...(agent ? { agent: true } : {}),
53
57
  capabilities: Object.freeze({
54
58
  warehouseRead: true,
55
59
  pipelineRuns: false,
@@ -59,6 +63,10 @@ export function deploymentFromEnv(environment = process.env) {
59
63
  }),
60
64
  });
61
65
  }
66
+ /** Whether the platform runs the workspace's agent, without channels, in this hosted preview. */
67
+ export function previewRunsAgent(deployment) {
68
+ return (deployment?.target === "preview" && deployment.agent === true && deployment.host === undefined);
69
+ }
62
70
  /** Recheck the deadline on every admission, including a warm process and cached sessions. */
63
71
  export function requireDeploymentCapability(deployment, capability, now = Date.now()) {
64
72
  if (deployment.target !== "preview") {
package/dist/index.d.ts CHANGED
@@ -94,17 +94,18 @@ export type { Decide, DecisionRequest } from "./service/decisions.js";
94
94
  export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-contract.js";
95
95
  export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, AgentWebStore, GuestIssue, GuestUpgrade, VisitorSignUp, WebTurnLimit, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
96
96
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
97
- export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, GUEST_EMAIL_CODE_PATH, GUEST_SIGN_UP_PATH, GUEST_USAGE_PATH, GUEST_LINK_PATH, } from "./service/agent/server.js";
97
+ export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_EVAL_TOKENS_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, GUEST_EMAIL_CODE_PATH, GUEST_SIGN_UP_PATH, GUEST_USAGE_PATH, GUEST_LINK_PATH, } from "./service/agent/server.js";
98
98
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
99
99
  export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
100
- export { AGENT_WEB_CLIENT_ID, agentResource } from "./service/agent/web-tokens.js";
101
- export { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, } from "./service/runtime-identity.js";
100
+ export { AGENT_EVAL_CLIENT_ID, AGENT_WEB_CLIENT_ID, agentResource, } from "./service/agent/web-tokens.js";
101
+ export { EVAL_TOKEN_DEFAULT_SECONDS, EVAL_TOKEN_MAX_SECONDS } from "./service/agent/eval-tokens.js";
102
+ export { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, ONTOLOGY_DEPLOYMENT_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, } from "./service/runtime-identity.js";
102
103
  export type { RuntimeIdentityConfig } from "./service/runtime-identity.js";
103
104
  export { MCP_PATH, MCP_PROTOCOL_VERSIONS } from "./service/mcp/server.js";
104
105
  export { MCP_TOOL_NAME_MAX_LENGTH, mcpToolName } from "./names.js";
105
106
  export type { OntologyService } from "./service/service.js";
106
107
  export { applyMigration, CatalogInvalid, CatalogMismatch, isNoopMigration, migrate, MIGRATION_REFUSAL_CODES, MIGRATION_STEP_CLASSIFICATIONS, MIGRATION_STEP_KINDS, MigrationFailed, MigrationPlan, MigrationRefusal, MigrationRefused, MigrationStep, OntologyStorage, planMigration, preparePreviewDatabase, readCatalog, readRetainedStorage, readRuntimeTables, readHistoryActivityIndexes, readStorageNames, RetainedEntity, RetainedStorage, } from "./migrate/index.js";
107
- export { deploymentFromEnv, DeploymentAdmissionError, requireDeploymentCapability, } from "./deployment.js";
108
+ export { deploymentFromEnv, DeploymentAdmissionError, previewRunsAgent, requireDeploymentCapability, } from "./deployment.js";
108
109
  export type { DeploymentObservation, DeploymentCapabilities, DeploymentAdmissionCode, } from "./deployment.js";
109
110
  export type { ApplyMigrationError, ApplyMigrationOptions, CatalogInput, MigrateInput, MigrationOptions, MigrationRefusalCode, MigrationResult, MigrationStepClassification, MigrationStepKind, PlanMigrationInput, StorageNames, } from "./migrate/index.js";
110
111
  export type { BlobStorageBinding } from "./storage/provider.js";
package/dist/index.js CHANGED
@@ -63,18 +63,19 @@ export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-co
63
63
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
64
64
  // The app's own agent: pairing channel accounts with members, and acting as them, or as a
65
65
  // workflow's user in the tasks workflows hand it.
66
- export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, GUEST_EMAIL_CODE_PATH, GUEST_SIGN_UP_PATH, GUEST_USAGE_PATH, GUEST_LINK_PATH, } from "./service/agent/server.js";
66
+ export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_EVAL_TOKENS_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, GUEST_EMAIL_CODE_PATH, GUEST_SIGN_UP_PATH, GUEST_USAGE_PATH, GUEST_LINK_PATH, } from "./service/agent/server.js";
67
67
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
68
68
  export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
69
69
  // Agent tokens: access tokens of a member's grant to the agent, which a browser shows the agent.
70
- export { AGENT_WEB_CLIENT_ID, agentResource } from "./service/agent/web-tokens.js";
71
- export { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, } from "./service/runtime-identity.js";
70
+ export { AGENT_EVAL_CLIENT_ID, AGENT_WEB_CLIENT_ID, agentResource, } from "./service/agent/web-tokens.js";
71
+ export { EVAL_TOKEN_DEFAULT_SECONDS, EVAL_TOKEN_MAX_SECONDS } from "./service/agent/eval-tokens.js";
72
+ export { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, ONTOLOGY_DEPLOYMENT_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, } from "./service/runtime-identity.js";
72
73
  // The MCP server the service serves beside the HTTP API.
73
74
  export { MCP_PATH, MCP_PROTOCOL_VERSIONS } from "./service/mcp/server.js";
74
75
  export { MCP_TOOL_NAME_MAX_LENGTH, mcpToolName } from "./names.js";
75
76
  // Migrations: the planner, the applier and the physical mapping they share with the runtime.
76
77
  export { applyMigration, CatalogInvalid, CatalogMismatch, isNoopMigration, migrate, MIGRATION_REFUSAL_CODES, MIGRATION_STEP_CLASSIFICATIONS, MIGRATION_STEP_KINDS, MigrationFailed, MigrationPlan, MigrationRefusal, MigrationRefused, MigrationStep, OntologyStorage, planMigration, preparePreviewDatabase, readCatalog, readRetainedStorage, readRuntimeTables, readHistoryActivityIndexes, readStorageNames, RetainedEntity, RetainedStorage, } from "./migrate/index.js";
77
- export { deploymentFromEnv, DeploymentAdmissionError, requireDeploymentCapability, } from "./deployment.js";
78
+ export { deploymentFromEnv, DeploymentAdmissionError, previewRunsAgent, requireDeploymentCapability, } from "./deployment.js";
78
79
  export { runBlobStorageMaintenance } from "./storage/operator.js";
79
80
  export { runNewUserHook } from "./runtime/new-user-hook.js";
80
81
  export { sqlAgentStore, resolveChannelIdentity, resolveChannelSignIn } from "./runtime/agents.js";
package/dist/manifest.js CHANGED
@@ -1098,6 +1098,7 @@ export function buildManifest(input) {
1098
1098
  "workspace-app-previews-v1",
1099
1099
  "workspace-app-preview-workflows-v1",
1100
1100
  "workspace-app-local-previews-v1",
1101
+ "workspace-app-preview-agent-v1",
1101
1102
  ],
1102
1103
  entities: input.entities.map((candidate) => entityManifest({ resolved: candidate, warehouseBacked })),
1103
1104
  roles: input.roles.map((candidate) => ({
@@ -3,7 +3,7 @@ import { Effect } from "effect";
3
3
  import { SqlClient } from "effect/unstable/sql";
4
4
  import { signUpRolesOf } from "../manifest.js";
5
5
  import { AGENT_GUEST_LINKS_TABLE, CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
6
- import { AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
6
+ import { AGENT_EVAL_CLIENT_ID, AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
7
7
  import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, FULL_SCOPE, REFRESH_TOKEN_PREFIX, REFRESH_TOKEN_TTL_MS, newSecret, secretHash, } from "../service/oauth/protocol.js";
8
8
  import { addGuestSpend, completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, guestSpendLimited, } from "./agent-counters.js";
9
9
  import { channelUsersAvailable } from "./member-tables.js";
@@ -157,13 +157,52 @@ export function sqlAgentWebStore(ontology, sql, admission) {
157
157
  return token;
158
158
  }))
159
159
  .pipe(Effect.orDie),
160
- grantMember: ({ grantId, userId }) => Effect.gen(function* () {
160
+ issueEval: ({ email, resource, expiresAt }) => sql
161
+ .withTransaction(Effect.gen(function* () {
162
+ // Exclusive, so that two sessions issued at once for one member serialize: the second
163
+ // revokes the first's grant.
164
+ const [member] = yield* sql.unsafe(`SELECT "id"::text AS "id", "active" FROM "${USER_TABLE}"
165
+ WHERE "kind" = 'member' AND "email" = $1 LIMIT 1 FOR UPDATE`, [email.trim().toLowerCase()]);
166
+ if (member === undefined) {
167
+ return { status: "not_member" };
168
+ }
169
+ if (!member.active || (yield* isMemberBlocked(sql, member.id))) {
170
+ return { status: "inactive" };
171
+ }
172
+ yield* sql.unsafe(`INSERT INTO "${OAUTH_CLIENTS_TABLE}" ("id", "name", "redirect_uris", "auth_method")
173
+ VALUES ($1, $1, '[]'::jsonb, 'none') ON CONFLICT ("id") DO NOTHING`, [AGENT_EVAL_CLIENT_ID]);
174
+ // One eval session per member at a time: issuing again ends the earlier one.
175
+ yield* sql.unsafe(`UPDATE ${GRANTS} SET "revoked_at" = now()
176
+ WHERE "user_id" = $1::uuid AND "client_id" = $2 AND "revoked_at" IS NULL`, [member.id, AGENT_EVAL_CLIENT_ID]);
177
+ const grantId = randomUUID();
178
+ yield* oauth.saveGrant({
179
+ id: grantId,
180
+ clientId: AGENT_EVAL_CLIENT_ID,
181
+ userId: member.id,
182
+ scope: FULL_SCOPE,
183
+ resource,
184
+ });
185
+ const token = newSecret(ACCESS_TOKEN_PREFIX);
186
+ // No refresh token: a session ends with its access token.
187
+ yield* oauth.saveTokens([
188
+ { hash: secretHash(token), grantId, kind: "access", expiresAt },
189
+ ]);
190
+ return { status: "issued", token, grantId, memberId: member.id };
191
+ }))
192
+ .pipe(Effect.orDie),
193
+ grantMember: ({ grantId, userId, evalGrants }) => Effect.gen(function* () {
161
194
  if (!isRecordId(grantId) || !isRecordId(userId)) {
162
195
  return undefined;
163
196
  }
164
197
  const [standing] = yield* sql
165
198
  .unsafe(`SELECT 1 FROM ${GRANTS} WHERE "id" = $1::uuid AND "user_id" = $2::uuid
166
- AND "client_id" = $3 AND "revoked_at" IS NULL`, [grantId, userId, AGENT_WEB_CLIENT_ID])
199
+ AND "client_id" = ANY($3::text[]) AND "revoked_at" IS NULL`, [
200
+ grantId,
201
+ userId,
202
+ evalGrants === true
203
+ ? [AGENT_WEB_CLIENT_ID, AGENT_EVAL_CLIENT_ID]
204
+ : [AGENT_WEB_CLIENT_ID],
205
+ ])
167
206
  .pipe(Effect.orDie);
168
207
  return standing === undefined ? undefined : yield* oauth.memberPrincipal(userId);
169
208
  }),
@@ -1,8 +1,10 @@
1
- import { Effect, Redacted } from "effect";
1
+ import { Effect, Option, Redacted } from "effect";
2
2
  import { HttpServerRequest } from "effect/unstable/http";
3
3
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { RequestId, forbidden, notFound, toServerResponse, unauthorized, unavailable, } from "../errors.js";
5
5
  import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
+ import { previewRunsAgent } from "../../deployment.js";
7
+ import { RuntimeDeployment } from "../../runtime/deployment.js";
6
8
  import { GUEST_ACT_AS_PREFIX, actingGuestId } from "../../runtime/guests.js";
7
9
  import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, CHAT, CHAT_HEADER, EARLIER_CHAT_HEADER, SESSION, SESSION_HEADER, WEB_PROVIDER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
8
10
  export { CHAT_HEADER, SESSION_HEADER } from "../runtime-identity.js";
@@ -69,7 +71,12 @@ export function webMember(agents, userId, grantId) {
69
71
  ? Effect.succeed(undefined)
70
72
  : web.grantGuest(grantId);
71
73
  }
72
- return Effect.map(web.grantMember({ grantId, userId }), (member) => member === undefined ? undefined : { ...member, authenticatedVia: WEB_PROVIDER });
74
+ return Effect.gen(function* () {
75
+ // An eval's grant stands for its test member only in a preview that runs the agent.
76
+ const evalGrants = previewRunsAgent(Option.getOrUndefined(yield* Effect.serviceOption(RuntimeDeployment)));
77
+ const member = yield* web.grantMember({ grantId, userId, evalGrants });
78
+ return member === undefined ? undefined : { ...member, authenticatedVia: WEB_PROVIDER };
79
+ });
73
80
  }
74
81
  /**
75
82
  * The member the runtime acts for: a web member by the grant their agent token stands for, anyone
@@ -0,0 +1,25 @@
1
+ import { Effect } from "effect";
2
+ import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
3
+ import type { DeploymentObservation } from "../../deployment.js";
4
+ import { type TokenVerifier } from "../authentication.js";
5
+ import { RequestId } from "../errors.js";
6
+ import type { AgentWebStore } from "../runtime-contract.js";
7
+ /** How long an eval session's token works unless the platform asks for less: thirty minutes. */
8
+ export declare const EVAL_TOKEN_DEFAULT_SECONDS: number;
9
+ /** The longest an eval session's token works: an hour, and never past the preview's expiry. */
10
+ export declare const EVAL_TOKEN_MAX_SECONDS: number;
11
+ /**
12
+ * `POST /api/ontology/agent/eval-tokens`, mounted only in a preview that runs the agent, for the
13
+ * platform alone: its workload token bound to this preview, on this deployment's own origin. Body
14
+ * `{ email, origin, expires_in_seconds? }`; answers `{ token, expires_at, member_id, grant_id, chat
15
+ * }`, an agent token of a new `agent-eval` grant for the member with that address, for the agent's
16
+ * resource at `origin`. It works thirty minutes unless asked for less or more, an hour at most and
17
+ * never past the preview's expiry, has no refresh token, and ends the member's earlier eval session.
18
+ * The member must already exist and be active: `eval_member_not_found` (404) and
19
+ * `eval_member_inactive` (409) otherwise. Answers carry no words, only codes.
20
+ */
21
+ export declare function issueEvalToken(options: {
22
+ readonly deployment: DeploymentObservation;
23
+ readonly verifyToken: TokenVerifier;
24
+ readonly web: AgentWebStore;
25
+ }): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId | HttpServerRequest.ParsedSearchParams>;
@@ -0,0 +1,130 @@
1
+ import { Effect, Redacted, Result, Schema } from "effect";
2
+ import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
3
+ import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
+ import { decodeProtectedHeader } from "jose";
5
+ import { schemaIssues } from "../../runtime/validation.js";
6
+ import { WORKLOAD_TOKEN_TYPE, workloadKind } from "../authentication.js";
7
+ import { RequestId, errorBodyForWire, forbidden, toServerResponse, unauthorized, unavailable, } from "../errors.js";
8
+ import { agentResource, personalChat } from "./web-tokens.js";
9
+ /** How long an eval session's token works unless the platform asks for less: thirty minutes. */
10
+ export const EVAL_TOKEN_DEFAULT_SECONDS = 30 * 60;
11
+ /** The longest an eval session's token works: an hour, and never past the preview's expiry. */
12
+ export const EVAL_TOKEN_MAX_SECONDS = 60 * 60;
13
+ const EvalTokenRequest = Schema.Struct({
14
+ /** The test member's address, which the platform made a member of the preview's branch. */
15
+ email: Schema.String.check(Schema.isMinLength(3), Schema.isMaxLength(320)),
16
+ /** The preview's origin, on which the evals reach the agent: the token's resource is there. */
17
+ origin: Schema.String.check(Schema.isMaxLength(2048)),
18
+ expires_in_seconds: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(60), Schema.isLessThanOrEqualTo(EVAL_TOKEN_MAX_SECONDS))),
19
+ });
20
+ const NO_STORE = { "cache-control": "no-store" };
21
+ function isWorkloadToken(token) {
22
+ try {
23
+ return decodeProtectedHeader(token).typ === WORKLOAD_TOKEN_TYPE;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ function requestOrigin(request) {
30
+ return new URL(request.source instanceof Request ? request.source.url : request.url, `https://${request.headers.host ?? "ontology.invalid"}`).origin;
31
+ }
32
+ function refused(status, error, requestId) {
33
+ return HttpServerResponse.jsonUnsafe(errorBodyForWire({ error, detail: error, requestId }), {
34
+ status,
35
+ headers: NO_STORE,
36
+ });
37
+ }
38
+ /**
39
+ * `POST /api/ontology/agent/eval-tokens`, mounted only in a preview that runs the agent, for the
40
+ * platform alone: its workload token bound to this preview, on this deployment's own origin. Body
41
+ * `{ email, origin, expires_in_seconds? }`; answers `{ token, expires_at, member_id, grant_id, chat
42
+ * }`, an agent token of a new `agent-eval` grant for the member with that address, for the agent's
43
+ * resource at `origin`. It works thirty minutes unless asked for less or more, an hour at most and
44
+ * never past the preview's expiry, has no refresh token, and ends the member's earlier eval session.
45
+ * The member must already exist and be active: `eval_member_not_found` (404) and
46
+ * `eval_member_inactive` (409) otherwise. Answers carry no words, only codes.
47
+ */
48
+ export function issueEvalToken(options) {
49
+ const issue = options.web.issueEval;
50
+ return (request) => Effect.gen(function* () {
51
+ const requestId = yield* RequestId;
52
+ const bearer = yield* HttpApiBuilder.securityDecode(HttpApiSecurity.bearer).pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request));
53
+ const token = Redacted.value(bearer);
54
+ if (token === "" || !isWorkloadToken(token)) {
55
+ return toServerResponse(unauthorized(requestId, "The token is not valid."));
56
+ }
57
+ const verification = yield* Effect.promise(() => options.verifyToken(token));
58
+ if (verification.status === "unavailable") {
59
+ return toServerResponse(unavailable(requestId));
60
+ }
61
+ if (verification.status !== "workload") {
62
+ return toServerResponse(unauthorized(requestId, "The token is not valid."));
63
+ }
64
+ const { execution } = verification;
65
+ // The verifier already bound the token to this preview's deployment and expiry; only the
66
+ // platform's own subject, on this deployment's own origin, issues eval sessions.
67
+ if (options.deployment.target !== "preview" ||
68
+ workloadKind({ sub: execution.subject }, execution.workspaceId) !== "platform" ||
69
+ execution.ontologyOrigin !== requestOrigin(request)) {
70
+ return toServerResponse(forbidden(requestId, "This workload may not issue eval tokens."));
71
+ }
72
+ if (issue === undefined) {
73
+ return toServerResponse(unavailable(requestId));
74
+ }
75
+ const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
76
+ try {
77
+ return JSON.parse(text);
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ });
83
+ const decoded = Schema.decodeUnknownResult(EvalTokenRequest)(body, {
84
+ errors: "all",
85
+ onExcessProperty: "error",
86
+ });
87
+ const origin = Result.isSuccess(decoded) && URL.canParse(decoded.success.origin)
88
+ ? new URL(decoded.success.origin)
89
+ : undefined;
90
+ if (Result.isFailure(decoded) ||
91
+ origin === undefined ||
92
+ origin.protocol !== "https:" ||
93
+ origin.origin !== decoded.success.origin.replace(/\/+$/u, "")) {
94
+ return HttpServerResponse.jsonUnsafe(errorBodyForWire({
95
+ error: "invalid_request",
96
+ detail: "The request body is invalid.",
97
+ requestId,
98
+ ...(Result.isFailure(decoded) ? { issues: schemaIssues(decoded.failure) } : {}),
99
+ }), { status: 400, headers: NO_STORE });
100
+ }
101
+ const now = Date.now();
102
+ const deadline = Date.parse(options.deployment.expiresAt);
103
+ // An expired preview issues nothing, even to a warm process.
104
+ if (!(now < deadline)) {
105
+ return refused(410, "preview_expired", requestId);
106
+ }
107
+ const seconds = decoded.success.expires_in_seconds ?? EVAL_TOKEN_DEFAULT_SECONDS;
108
+ const expiresAt = new Date(Math.min(now + seconds * 1000, deadline));
109
+ const issued = yield* issue({
110
+ email: decoded.success.email,
111
+ resource: agentResource(origin.origin),
112
+ expiresAt,
113
+ });
114
+ switch (issued.status) {
115
+ case "not_member":
116
+ return refused(404, "eval_member_not_found", requestId);
117
+ case "inactive":
118
+ return refused(409, "eval_member_inactive", requestId);
119
+ case "issued":
120
+ yield* Effect.logInfo("ontology.agent.eval_token_issued").pipe(Effect.annotateLogs({ requestId, grantId: issued.grantId }));
121
+ return HttpServerResponse.jsonUnsafe({
122
+ token: issued.token,
123
+ expires_at: expiresAt.toISOString(),
124
+ member_id: issued.memberId,
125
+ grant_id: issued.grantId,
126
+ chat: personalChat(issued.memberId),
127
+ }, { status: 200, headers: NO_STORE });
128
+ }
129
+ });
130
+ }
@@ -8,6 +8,7 @@ import { type RuntimeTokenVerifier } from "../runtime-identity.js";
8
8
  import { type AgentToolsOf } from "./protocol.js";
9
9
  import { type VisitorWebsites } from "./web-tokens.js";
10
10
  import type { BotCheckVerifier } from "./bot-check.js";
11
+ import type { DeploymentObservation } from "../../deployment.js";
11
12
  import { type OntologyManifest } from "../../manifest.js";
12
13
  import { GUEST_LINK_PATH, type EmailCodes } from "./guest-sign-up.js";
13
14
  import type { ResolvedGuest } from "../../sign-in.js";
@@ -16,6 +17,8 @@ export declare const AGENT_PATH = "/api/ontology/agent";
16
17
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
17
18
  export declare const AGENT_TOKENS_PATH = "/api/ontology/agent/tokens";
18
19
  export declare const AGENT_TOKEN_INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
20
+ /** Where the platform issues an eval session's agent token, in a preview that runs the agent. */
21
+ export declare const AGENT_EVAL_TOKENS_PATH = "/api/ontology/agent/eval-tokens";
19
22
  /** Where a browser on a declared website signs its visitor up on `web`. */
20
23
  export declare const AGENT_VISITORS_PATH = "/api/ontology/agent/visitors";
21
24
  /** A website's guests' own routes: becoming a user, and the runtime's report of their spend. */
@@ -53,6 +56,11 @@ export interface AgentServerOptions {
53
56
  readonly cronSecret?: Redacted.Redacted<string> | undefined;
54
57
  /** How many days the chats' messages are kept, as the ontology declares it. */
55
58
  readonly chatRetentionDays?: number;
59
+ /**
60
+ * The preview deployment, in a preview that runs the agent: the platform issues eval sessions
61
+ * there, and introspection answers for their `agent-eval` tokens. Never set in production.
62
+ */
63
+ readonly evalTokens?: DeploymentObservation;
56
64
  /** The ontology, whose record files a held reply carries and whose channels send them. */
57
65
  readonly manifest?: OntologyManifest;
58
66
  }
@@ -15,6 +15,7 @@ import { OntologyBackend } from "../runtime-contract.js";
15
15
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
16
16
  import { ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
17
17
  import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
18
+ import { issueEvalToken } from "./eval-tokens.js";
18
19
  import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
19
20
  import { CHAT_RETENTION_DAYS } from "../../manifest.js";
20
21
  import { snapshotDraftFiles } from "../chat/draft-files.js";
@@ -33,6 +34,8 @@ const REVIEWS_PATH = `${AGENT_PATH}/reviews`;
33
34
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
34
35
  export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
35
36
  export const AGENT_TOKEN_INTROSPECTION_PATH = `${AGENT_TOKENS_PATH}/introspect`;
37
+ /** Where the platform issues an eval session's agent token, in a preview that runs the agent. */
38
+ export const AGENT_EVAL_TOKENS_PATH = `${AGENT_PATH}/eval-tokens`;
36
39
  /** Where a browser on a declared website signs its visitor up on `web`. */
37
40
  export const AGENT_VISITORS_PATH = `${AGENT_PATH}/visitors`;
38
41
  /** A website's guests' own routes: becoming a user, and the runtime's report of their spend. */
@@ -730,7 +733,14 @@ export function agentLayer(options) {
730
733
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
731
734
  if (store.web !== undefined && backend.oauth !== undefined) {
732
735
  yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
733
- yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth, options.agentTools, options.guest)));
736
+ yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth, options.agentTools, options.guest, options.evalTokens !== undefined)));
737
+ if (options.evalTokens !== undefined) {
738
+ yield* router.add("POST", AGENT_EVAL_TOKENS_PATH, issueEvalToken({
739
+ deployment: options.evalTokens,
740
+ verifyToken: options.verifyToken,
741
+ web: store.web,
742
+ }));
743
+ }
734
744
  const websites = options.visitorWebsites ?? { guests: [], signUp: [] };
735
745
  const botCheck = options.guest?.botCheck === undefined || options.botCheckVerifier === undefined
736
746
  ? undefined
@@ -15,6 +15,14 @@ import { type AgentToolsOf } from "./protocol.js";
15
15
  * stands for, and names the token's grant whenever it then acts for the member.
16
16
  */
17
17
  export declare const AGENT_WEB_CLIENT_ID = "agent-web";
18
+ /**
19
+ * The first-party client of the grants with which a builder's evals reach the agent of an app
20
+ * preview, as a test member that exists only in the preview's branch: `POST
21
+ * /api/ontology/agent/eval-tokens` issues them, for the platform only. Its tokens are agent tokens
22
+ * like `agent-web`'s, which introspection marks `eval: true`. Outside a preview that runs the agent
23
+ * the client is refused outright, and a production ontology holds none of its grants.
24
+ */
25
+ export declare const AGENT_EVAL_CLIENT_ID = "agent-eval";
18
26
  /** The resource agent tokens are issued for: the agent's routes on the origin the member used. */
19
27
  export declare function agentResource(origin: string): string;
20
28
  /** Tokens one member may request per minute; the browser keeps one until it is about to expire. */
@@ -34,9 +42,12 @@ export declare function issueAgentToken(store: AgentStore, web: AgentWebStore, l
34
42
  * member is starting a turn: someone `signUp` created has it counted against the agent's limits,
35
43
  * and the answer names the limit it exceeds as `limited`. A guest's token is answered
36
44
  * `{ active, guest_id, roles, grant_id, chat, agent_tools }`, without a member, and each of their
37
- * turns counts against the agent's guest limits.
45
+ * turns counts against the agent's guest limits. In a preview that runs the agent, an `agent-eval`
46
+ * token is answered as a member's, with `eval: true`, and its turns count against no limit.
38
47
  */
39
- export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore, agentTools: AgentToolsOf, guests?: Pick<ResolvedGuest, "confirmations">): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
48
+ export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore, agentTools: AgentToolsOf, guests?: Pick<ResolvedGuest, "confirmations">,
49
+ /** Whether `agent-eval` tokens count: only in a preview that runs the agent. */
50
+ evalGrants?: boolean): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
40
51
  /** The headers that let a website on `origin` read an answer to its visitor's browser. */
41
52
  export declare function websiteHeaders(origin: string): Record<string, string>;
42
53
  /** The declared website a browser's request comes from, when it comes from one. */
@@ -18,6 +18,14 @@ import { AgentLimitsRequest } from "./protocol.js";
18
18
  * stands for, and names the token's grant whenever it then acts for the member.
19
19
  */
20
20
  export const AGENT_WEB_CLIENT_ID = "agent-web";
21
+ /**
22
+ * The first-party client of the grants with which a builder's evals reach the agent of an app
23
+ * preview, as a test member that exists only in the preview's branch: `POST
24
+ * /api/ontology/agent/eval-tokens` issues them, for the platform only. Its tokens are agent tokens
25
+ * like `agent-web`'s, which introspection marks `eval: true`. Outside a preview that runs the agent
26
+ * the client is refused outright, and a production ontology holds none of its grants.
27
+ */
28
+ export const AGENT_EVAL_CLIENT_ID = "agent-eval";
21
29
  /** The resource agent tokens are issued for: the agent's routes on the origin the member used. */
22
30
  export function agentResource(origin) {
23
31
  return new URL(`${BASE_PATH}/agent`, origin).href;
@@ -90,9 +98,12 @@ function originOf(value, request) {
90
98
  * member is starting a turn: someone `signUp` created has it counted against the agent's limits,
91
99
  * and the answer names the limit it exceeds as `limited`. A guest's token is answered
92
100
  * `{ active, guest_id, roles, grant_id, chat, agent_tools }`, without a member, and each of their
93
- * turns counts against the agent's guest limits.
101
+ * turns counts against the agent's guest limits. In a preview that runs the agent, an `agent-eval`
102
+ * token is answered as a member's, with `eval: true`, and its turns count against no limit.
94
103
  */
95
- export function introspectAgentToken(store, web, oauth, agentTools, guests) {
104
+ export function introspectAgentToken(store, web, oauth, agentTools, guests,
105
+ /** Whether `agent-eval` tokens count: only in a preview that runs the agent. */
106
+ evalGrants = false) {
96
107
  return (request) => Effect.gen(function* () {
97
108
  const requestId = yield* RequestId;
98
109
  const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
@@ -150,14 +161,17 @@ export function introspectAgentToken(store, web, oauth, agentTools, guests) {
150
161
  ...limitedAs(limited),
151
162
  });
152
163
  }
153
- const member = authenticated?.caller.kind === "oauth" &&
154
- authenticated.caller.client.id === AGENT_WEB_CLIENT_ID
164
+ const client = authenticated?.caller.kind === "oauth" ? authenticated.caller.client.id : undefined;
165
+ const evaluating = evalGrants && client === AGENT_EVAL_CLIENT_ID;
166
+ const member = authenticated !== undefined && (client === AGENT_WEB_CLIENT_ID || evaluating)
155
167
  ? yield* store.member(authenticated.principal.id)
156
168
  : undefined;
157
169
  if (authenticated === undefined || member === undefined) {
158
170
  return json({ active: false });
159
171
  }
160
- const limited = decoded.success.turn === true
172
+ // An eval's turns spend the workspace's budget as any turn does, but count against no
173
+ // member's limits: the test member exists only in the preview.
174
+ const limited = decoded.success.turn === true && !evaluating
161
175
  ? yield* web.countTurn(member.principal.id, limits)
162
176
  : undefined;
163
177
  return json({
@@ -168,6 +182,7 @@ export function introspectAgentToken(store, web, oauth, agentTools, guests) {
168
182
  agent_tools: agentTools(member.principal),
169
183
  grant_id: authenticated.grantId,
170
184
  chat: personalChat(member.principal.id),
185
+ ...(evaluating ? { eval: true } : {}),
171
186
  ...limitedAs(limited),
172
187
  });
173
188
  });
@@ -4,7 +4,7 @@ import { HttpApiMiddleware, HttpApiSecurity, OpenApi } from "effect/unstable/htt
4
4
  import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, errors, jwtVerify, } from "jose";
5
5
  import { channelIdentityProvider, WORKSPACE_CHANNEL_KIND, workspaceChannelOf, } from "../chat-channel.js";
6
6
  import { CHANNEL_COOKIE_PATTERN } from "../channel-session.js";
7
- import { requireDeploymentCapability } from "../deployment.js";
7
+ import { previewRunsAgent, requireDeploymentCapability, } from "../deployment.js";
8
8
  import { API_KEY_PREFIX } from "../runtime/principals.js";
9
9
  import { FEDERATION_TOKEN_PREFIX, federationDigest } from "../runtime/federation.js";
10
10
  import { browserRevisionAdmitted, browserRevisionObservation, browserSessionAdmission, federationStatus, } from "./federation-status.js";
@@ -620,7 +620,8 @@ export function authenticate(credential, verifyToken, options = {}) {
620
620
  ((token.startsWith(FEDERATION_TOKEN_PREFIX) && !verifyToken.browserMethods) ||
621
621
  token.startsWith(ACCESS_TOKEN_PREFIX) ||
622
622
  token.startsWith(API_KEY_PREFIX) ||
623
- options.runtime !== undefined)) {
623
+ // Only a preview that runs the agent admits its runtime.
624
+ (options.runtime !== undefined && !previewRunsAgent(verifyToken.deployment)))) {
624
625
  return { status: "rejected" };
625
626
  }
626
627
  if (token === "") {
@@ -1,7 +1,7 @@
1
1
  import { telegramPreviewEnvironment } from "../telegram.js";
2
2
  import { Redacted, Schema } from "effect";
3
3
  import { BlobStorageBinding } from "../storage/provider.js";
4
- import { deploymentFromEnv } from "../deployment.js";
4
+ import { deploymentFromEnv, previewRunsAgent } from "../deployment.js";
5
5
  import { LocalConnectionContextError, readLocalConnectionContext, RUNTIME_CONTEXT_FD, } from "./connections.js";
6
6
  /** The environment of the workspace deployment's ontology service. */
7
7
  export const ENVIRONMENT_VARIABLES = {
@@ -170,7 +170,13 @@ export function configFromEnv(environment = process.env) {
170
170
  message: "OIDC requires both a public client ID and an HTTPS issuer.",
171
171
  });
172
172
  }
173
- const runtimeIdentity = deployment.target === "preview" ? undefined : runtimeIdentityFromEnv(read);
173
+ // A hosted preview trusts its own functions' tokens, which name `preview`, only when the platform
174
+ // runs the agent there; a local session has no functions.
175
+ const runtimeIdentity = deployment.target === "preview"
176
+ ? previewRunsAgent(deployment)
177
+ ? { ...runtimeIdentityFromEnv(read), environment: "preview" }
178
+ : undefined
179
+ : runtimeIdentityFromEnv(read);
174
180
  const localConnections = deployment.target === "preview" ? undefined : localConnectionsFromEnv(environment);
175
181
  let blobStorage;
176
182
  if (read("SEGMENTSTREAM_ONTOLOGY_STORAGE")) {
@@ -265,7 +265,22 @@ export interface AgentWebStore {
265
265
  readonly grantMember: (input: {
266
266
  readonly grantId: string;
267
267
  readonly userId: string;
268
+ /**
269
+ * Whether an `agent-eval` grant counts too: only in a preview that runs the agent, where evals
270
+ * act as a test member. Never in production.
271
+ */
272
+ readonly evalGrants?: boolean;
268
273
  }) => Effect.Effect<Principal | undefined>;
274
+ /**
275
+ * In a preview that runs the agent: an access token of a new `agent-eval` grant to the agent at
276
+ * `resource`, for the active member with `email`, revoking the member's earlier `agent-eval`
277
+ * grants. No refresh token. Absent where the store cannot issue them.
278
+ */
279
+ readonly issueEval?: (input: {
280
+ readonly email: string;
281
+ readonly resource: string;
282
+ readonly expiresAt: Date;
283
+ }) => Effect.Effect<EvalIssue>;
269
284
  /**
270
285
  * Counts one turn a member starts on the web against the agent's limits when `signUp` created
271
286
  * them, as their turns on a messenger are counted, on the same counters; invited and paired
@@ -385,6 +400,21 @@ export type VisitorSignUp = {
385
400
  } | {
386
401
  readonly status: "refused";
387
402
  };
403
+ /** An eval session's credential, as {@link AgentWebStore.issueEval} answers it. */
404
+ export type EvalIssue = {
405
+ readonly status: "issued";
406
+ readonly token: string;
407
+ readonly grantId: string;
408
+ readonly memberId: string;
409
+ }
410
+ /** No member has the address. */
411
+ | {
412
+ readonly status: "not_member";
413
+ }
414
+ /** The member is deactivated or blocked. */
415
+ | {
416
+ readonly status: "inactive";
417
+ };
388
418
  /** A guest's credential, as {@link AgentWebStore.guest} answers it. */
389
419
  export type GuestIssue = {
390
420
  readonly status: "issued";
@@ -30,6 +30,14 @@ export declare const CHAT: RegExp;
30
30
  export declare const SESSION: RegExp;
31
31
  /** The chat and session a request names, or `undefined` without a well-formed chat. */
32
32
  export declare function requestChat(request: HttpServerRequest.HttpServerRequest): ChatProvenance | undefined;
33
+ /**
34
+ * The header the agent of a preview names its own deployment in, as the ontology's own calls to
35
+ * the platform do. Vercel's function tokens name a project and its environment, never a
36
+ * deployment, and every preview of a workspace shares one hosting project, so a preview's ontology
37
+ * checks the header against its own deployment before it trusts a runtime token: an agent of
38
+ * another preview of the same workspace is refused rather than served another branch's data.
39
+ */
40
+ export declare const ONTOLOGY_DEPLOYMENT_HEADER = "x-segmentstream-ontology-deployment-id";
33
41
  /**
34
42
  * Whom the service trusts as its runtime caller: Vercel OIDC tokens of the functions of this
35
43
  * deployment's own project. The app's agent is a service of the same Vercel project as the ontology
@@ -42,6 +50,11 @@ export interface RuntimeIdentityConfig {
42
50
  readonly audience: string;
43
51
  /** The project the token must name, from `VERCEL_PROJECT_ID`. */
44
52
  readonly projectId: string;
53
+ /**
54
+ * The environment the token must name: `production`, unless the platform runs the agent in a
55
+ * hosted preview, whose functions' tokens name `preview`.
56
+ */
57
+ readonly environment?: "production" | "preview";
45
58
  }
46
59
  export type RuntimeVerification = {
47
60
  readonly status: "valid";
@@ -61,10 +74,13 @@ export type RuntimeVerification = {
61
74
  export type RuntimeTokenVerifier = (token: string) => Promise<RuntimeVerification>;
62
75
  /** The issuer's key set, at `<issuer>/.well-known/jwks` as Vercel publishes it. */
63
76
  export declare function runtimeKeySet(issuer: string): JWTVerifyGetKey;
77
+ /** Whether a bearer token claims the runtime issuer, read without verifying it. */
78
+ export declare function claimsRuntimeIssuer(config: RuntimeIdentityConfig, token: string): boolean;
64
79
  /**
65
80
  * Verifies the Vercel OIDC token of a function of this deployment's project, as backend-next
66
81
  * verifies the ontology service's own: RS256 from the team's issuer, for the team's audience,
67
- * unexpired, with `project_id` equal to the configured project and `environment` `production`.
82
+ * unexpired, with `project_id` equal to the configured project and `environment` the configured
83
+ * one, `production` unless set.
68
84
  * The issuer and the audience name the team, so no further owner check is needed. A token that
69
85
  * claims another issuer is `other`, without a key-set fetch.
70
86
  */
@@ -44,6 +44,14 @@ const CLOCK_TOLERANCE_SECONDS = 5;
44
44
  const JWKS_TIMEOUT_MS = 5_000;
45
45
  /** The environment that a Vercel function token must name: channels run only in production. */
46
46
  const PRODUCTION = "production";
47
+ /**
48
+ * The header the agent of a preview names its own deployment in, as the ontology's own calls to
49
+ * the platform do. Vercel's function tokens name a project and its environment, never a
50
+ * deployment, and every preview of a workspace shares one hosting project, so a preview's ontology
51
+ * checks the header against its own deployment before it trusts a runtime token: an agent of
52
+ * another preview of the same workspace is refused rather than served another branch's data.
53
+ */
54
+ export const ONTOLOGY_DEPLOYMENT_HEADER = "x-segmentstream-ontology-deployment-id";
47
55
  /** The issuer without a trailing slash, as Vercel writes it in `iss` and as its JWKS URL starts. */
48
56
  function normalizedIssuer(issuer) {
49
57
  let end = issuer.length;
@@ -83,10 +91,15 @@ function claimedIssuer(token) {
83
91
  return undefined;
84
92
  }
85
93
  }
94
+ /** Whether a bearer token claims the runtime issuer, read without verifying it. */
95
+ export function claimsRuntimeIssuer(config, token) {
96
+ return claimedIssuer(token) === normalizedIssuer(config.issuer);
97
+ }
86
98
  /**
87
99
  * Verifies the Vercel OIDC token of a function of this deployment's project, as backend-next
88
100
  * verifies the ontology service's own: RS256 from the team's issuer, for the team's audience,
89
- * unexpired, with `project_id` equal to the configured project and `environment` `production`.
101
+ * unexpired, with `project_id` equal to the configured project and `environment` the configured
102
+ * one, `production` unless set.
90
103
  * The issuer and the audience name the team, so no further owner check is needed. A token that
91
104
  * claims another issuer is `other`, without a key-set fetch.
92
105
  */
@@ -107,7 +120,7 @@ export function makeRuntimeTokenVerifier(config, keySet) {
107
120
  if (payload.project_id !== config.projectId) {
108
121
  return { status: "invalid", reason: "claim:project_id" };
109
122
  }
110
- if (payload.environment !== PRODUCTION) {
123
+ if (payload.environment !== (config.environment ?? PRODUCTION)) {
111
124
  return { status: "invalid", reason: "claim:environment" };
112
125
  }
113
126
  return { status: "valid" };
@@ -6,6 +6,7 @@ import { validateDeploymentStorage } from "../storage/provider.js";
6
6
  import { captureRuntimeFailure } from "../internal/diagnostics.js";
7
7
  import { deploymentFromEnv, DeploymentAdmissionError, requireDeploymentCapability, } from "../deployment.js";
8
8
  import { RuntimeDeployment } from "../runtime/deployment.js";
9
+ import { previewRunsAgent } from "../deployment.js";
9
10
  import { nameToWire } from "../authoring-names.js";
10
11
  import { bundledNavigationCatalog } from "../navigation-artifact.js";
11
12
  import { parsePageCatalog } from "../navigation-catalog.js";
@@ -56,7 +57,7 @@ import { vercelWorkflowEngine, workflowStarter, workflowsLayer } from "./workflo
56
57
  import { deploymentWorkflowEngine } from "./workflow-deployment.js";
57
58
  import { OntologyBackend } from "./runtime-contract.js";
58
59
  import { currentEntityPath } from "../earlier-entity-names.js";
59
- import { runtimeCredential, runtimeTokenVerifier, } from "./runtime-identity.js";
60
+ import { ONTOLOGY_DEPLOYMENT_HEADER, claimsRuntimeIssuer, runtimeCredential, runtimeTokenVerifier, } from "./runtime-identity.js";
60
61
  /** The header every response carries: the hash of the manifest the service serves. */
61
62
  export const ONTOLOGY_HASH_HEADER = "x-ontology-hash";
62
63
  /** The header every response carries: the correlation id quoted in error bodies and logs. */
@@ -158,6 +159,23 @@ function decorate(response, requestId, hash, durationMs) {
158
159
  headers,
159
160
  });
160
161
  }
162
+ /**
163
+ * The agent routes a preview that runs the agent serves: agent tokens for the preview app's web chat,
164
+ * their introspection, eval sessions, the chat store, held replies, and members' attachments and
165
+ * files.
166
+ */
167
+ const PREVIEW_AGENT_ROUTE = /^\/api\/ontology\/agent\/(?:tokens|eval-tokens|chats|drafts|reviews|attachments|files|conversations)(?:\/|$)/;
168
+ /**
169
+ * Whether a request is not the runtime's, or is the runtime's and names this deployment in
170
+ * `x-segmentstream-ontology-deployment-id`. Every preview of a workspace shares one hosting project,
171
+ * whose function tokens name no deployment, so the header keeps another preview's agent out.
172
+ */
173
+ function sameDeployment(request, identity, deploymentId) {
174
+ const match = /^Bearer\s+(.+)$/iu.exec(request.headers.get("authorization")?.trim() ?? "");
175
+ return (match === null ||
176
+ !claimsRuntimeIssuer(identity, match[1]) ||
177
+ request.headers.get(ONTOLOGY_DEPLOYMENT_HEADER)?.trim() === deploymentId);
178
+ }
161
179
  /**
162
180
  * The ontology service: the derived HttpApi, the MCP server at `/mcp` and the agent's pairing routes,
163
181
  * wired to the runtime, behind Neon Auth, app-token, API-key and runtime-token authentication.
@@ -167,27 +185,45 @@ function decorate(response, requestId, hash, durationMs) {
167
185
  export function createOntologyService(ontology, config) {
168
186
  const ambient = deploymentFromEnv();
169
187
  const requested = ambient.target === "preview" ? ambient : (config.deployment ?? ambient);
188
+ // The agent runs in a hosted preview only where the platform said so and gave the service the
189
+ // preview's runtime identity; production never trusts a preview's tokens.
190
+ const runtimeIdentity = requested.target === "preview"
191
+ ? requested.agent === true && config.runtimeIdentity?.environment === "preview"
192
+ ? config.runtimeIdentity
193
+ : undefined
194
+ : config.runtimeIdentity === undefined
195
+ ? undefined
196
+ : { ...config.runtimeIdentity, environment: "production" };
170
197
  const deployment = deploymentFromEnv({
171
198
  SEGMENTSTREAM_DEPLOYMENT_TARGET: requested.target,
172
199
  SEGMENTSTREAM_ONTOLOGY_DEPLOYMENT_ID: requested.deploymentId,
173
200
  SEGMENTSTREAM_PREVIEW_EXPIRES_AT: requested.target === "preview" ? requested.expiresAt : undefined,
174
201
  SEGMENTSTREAM_PREVIEW_HOST: requested.target === "preview" ? requested.host : undefined,
202
+ ...(requested.target === "preview" && runtimeIdentity !== undefined
203
+ ? {
204
+ SEGMENTSTREAM_RUNTIME_OIDC_ISSUER: runtimeIdentity.issuer,
205
+ SEGMENTSTREAM_RUNTIME_OIDC_AUDIENCE: runtimeIdentity.audience,
206
+ }
207
+ : {}),
175
208
  });
176
209
  const preview = deployment.target === "preview";
210
+ const previewAgent = previewRunsAgent(deployment);
177
211
  config = {
178
212
  ...config,
179
213
  deployment,
180
214
  ...(preview
181
215
  ? {
182
216
  oidc: ontology.signIn.browser ? config.oidc : undefined,
183
- runtimeIdentity: undefined,
217
+ runtimeIdentity,
184
218
  localConnections: undefined,
185
219
  cronSecret: undefined,
186
220
  agentOrigin: undefined,
187
221
  channels: undefined,
188
222
  channelAppProviders: undefined,
189
223
  }
190
- : {}),
224
+ : runtimeIdentity === undefined
225
+ ? {}
226
+ : { runtimeIdentity }),
191
227
  };
192
228
  if (preview && !config.neonAuth && !ontology.signIn.browser?.methods.includes("segmentstream")) {
193
229
  throw new DeploymentAdmissionError("preview_configuration_invalid");
@@ -345,7 +381,8 @@ export function createOntologyService(ontology, config) {
345
381
  ? deployedConnections(config)
346
382
  : localConnections(config.localConnections)));
347
383
  const replicate = deployedReplication(config);
348
- const chatHistory = config.runtimeIdentity === undefined ? undefined : platformChatArchive(config);
384
+ // The platform keeps chat history for production agents only.
385
+ const chatHistory = config.runtimeIdentity === undefined || preview ? undefined : platformChatArchive(config);
349
386
  const chatDelivery = makeChatDelivery(ontology, connections,
350
387
  // @legacy agent.cloud-chat-archive Deliveries reserve here while the store holds no message.
351
388
  config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
@@ -410,15 +447,18 @@ export function createOntologyService(ontology, config) {
410
447
  verifyToken,
411
448
  })
412
449
  : undefined);
413
- const agent = preview
450
+ // A preview runs the agent for the preview app's web chat and evals only: no visitors, sign-ups,
451
+ // channels or tasks.
452
+ const withoutAgent = preview && !previewAgent;
453
+ const agent = withoutAgent
414
454
  ? Layer.empty
415
455
  : agentLayer({
416
456
  verifyToken,
417
457
  verifyRuntime,
418
458
  exchangeSession,
419
- visitorWebsites,
459
+ visitorWebsites: preview ? { guests: [], signUp: [] } : visitorWebsites,
420
460
  agentTools,
421
- guest,
461
+ guest: preview ? undefined : guest,
422
462
  botCheckVerifier: config.botCheckVerifier ??
423
463
  deployedBotCheckVerifier({
424
464
  segmentstreamUrl: config.segmentstreamUrl,
@@ -431,6 +471,7 @@ export function createOntologyService(ontology, config) {
431
471
  emailCodes,
432
472
  cronSecret: config.cronSecret,
433
473
  chatRetentionDays: chatRetentionDaysOf(ontology.manifest),
474
+ ...(previewAgent ? { evalTokens: deployment } : {}),
434
475
  });
435
476
  const agentTasks = preview
436
477
  ? Layer.empty
@@ -442,7 +483,7 @@ export function createOntologyService(ontology, config) {
442
483
  agentTools,
443
484
  implicitMember: implicitMemberOf(ontology.roles) !== undefined,
444
485
  });
445
- const attachments = preview
486
+ const attachments = withoutAgent
446
487
  ? Layer.empty
447
488
  : attachmentsLayer({
448
489
  plan: built.plan,
@@ -454,7 +495,7 @@ export function createOntologyService(ontology, config) {
454
495
  });
455
496
  const application = Layer.mergeAll(channelApps.length > 0
456
497
  ? Layer.merge(channelSessionLayer(config), channelSignInLayer(channelApps, config, connections))
457
- : Layer.empty, federationLayer(federationConfig, verifyToken, { ontology, browserRevision }), routes, preview
498
+ : Layer.empty, federationLayer(federationConfig, verifyToken, { ontology, browserRevision }), routes, withoutAgent
458
499
  ? Layer.empty
459
500
  : chatRoutes({
460
501
  built,
@@ -474,7 +515,7 @@ export function createOntologyService(ontology, config) {
474
515
  chatDelivery,
475
516
  verifyToken,
476
517
  exchangeSession,
477
- }), preview ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
518
+ }), withoutAgent ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
478
519
  ? Layer.empty
479
520
  : archiveRoutes({
480
521
  transport: chatHistory,
@@ -547,12 +588,23 @@ export function createOntologyService(ontology, config) {
547
588
  requireDeploymentCapability(deployment);
548
589
  if (preview) {
549
590
  const path = new URL(request.url).pathname;
550
- const blocked = /^\/api\/ontology\/(?:agent|agents|chat|attachments|channels)(?:\/|$)/.test(path)
591
+ // A preview that runs the agent serves the routes its web chat and evals use, and still
592
+ // none of channels, pairings, accounts, visitors or tasks.
593
+ const agentRoute = previewAgent &&
594
+ (PREVIEW_AGENT_ROUTE.test(path) ||
595
+ /^\/api\/ontology\/(?:chat|attachments)(?:\/|$)/.test(path));
596
+ const blocked = !agentRoute &&
597
+ /^\/api\/ontology\/(?:agent|agents|chat|attachments|channels)(?:\/|$)/.test(path)
551
598
  ? "agents"
552
599
  : undefined;
553
600
  if (blocked) {
554
601
  throw new DeploymentAdmissionError("preview_capability_unavailable", blocked);
555
602
  }
603
+ if (previewAgent &&
604
+ runtimeIdentity !== undefined &&
605
+ !sameDeployment(request, runtimeIdentity, deployment.deploymentId)) {
606
+ throw new DeploymentAdmissionError("preview_deployment_mismatch");
607
+ }
556
608
  if (/^\/api\/ontology\/(?:oauth|oidc)(?:\/|$)/.test(path) ||
557
609
  (!browser && /^\/api\/ontology\/federation(?:\/|$)/.test(path)) ||
558
610
  path.startsWith("/.well-known/oauth")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.162.0",
3
+ "version": "0.163.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",