@segmentstream/ontology 0.162.0 → 0.164.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/deployment.d.ts +13 -1
  3. package/dist/deployment.js +8 -0
  4. package/dist/email.d.ts +1 -1
  5. package/dist/email.js +1 -1
  6. package/dist/gmail-send.d.ts +10 -0
  7. package/dist/gmail-send.js +31 -9
  8. package/dist/index.d.ts +5 -4
  9. package/dist/index.js +5 -4
  10. package/dist/manifest.js +1 -0
  11. package/dist/runtime/agent-web.js +42 -3
  12. package/dist/service/agent/authentication.js +9 -2
  13. package/dist/service/agent/eval-tokens.d.ts +25 -0
  14. package/dist/service/agent/eval-tokens.js +130 -0
  15. package/dist/service/agent/server.d.ts +8 -0
  16. package/dist/service/agent/server.js +11 -1
  17. package/dist/service/agent/web-tokens.d.ts +13 -2
  18. package/dist/service/agent/web-tokens.js +20 -5
  19. package/dist/service/authentication.js +3 -2
  20. package/dist/service/chat/draft-files.d.ts +5 -0
  21. package/dist/service/chat/draft-files.js +28 -1
  22. package/dist/service/chat/providers/custom.js +2 -2
  23. package/dist/service/chat/providers/email.js +13 -11
  24. package/dist/service/chat/providers/files-send.d.ts +36 -0
  25. package/dist/service/chat/providers/files-send.js +182 -0
  26. package/dist/service/chat/providers/provider.d.ts +22 -3
  27. package/dist/service/chat/providers/provider.js +43 -0
  28. package/dist/service/chat/providers/slack.js +4 -1
  29. package/dist/service/chat/providers/telegram.js +23 -3
  30. package/dist/service/chat/providers/whatsapp.js +4 -1
  31. package/dist/service/chat/review-delivery.js +1 -0
  32. package/dist/service/config.js +8 -2
  33. package/dist/service/runtime-contract.d.ts +30 -0
  34. package/dist/service/runtime-identity.d.ts +17 -1
  35. package/dist/service/runtime-identity.js +15 -2
  36. package/dist/service/service.js +63 -11
  37. package/dist/slack-files.d.ts +2 -0
  38. package/dist/slack-files.js +1 -1
  39. package/dist/telegram-files.d.ts +4 -0
  40. package/dist/telegram-files.js +6 -2
  41. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.164.0
4
+
5
+ Approving a draft with files now sends them on Telegram, Slack and WhatsApp too, with the shared
6
+ senders of `@segmentstream/ontology/<channel>`. Telegram sends one message when the text fits a
7
+ caption and the files go as one file or one album of one type, otherwise the text and then the
8
+ files; Slack uploads every file and shares them with the text as one message; WhatsApp sends each
9
+ file by a link granted just before its message, the text as the first's caption. Each channel
10
+ declares its file limits and refuses what it cannot send before anything is reserved. A reply that
11
+ reached the person only in part is `uncertain` and never sent again, and its delivery keeps what
12
+ became of each file (`ProviderOutcome.files`). A Telegram caption may now be written in MarkdownV2
13
+ (`parseMode`), with `plainCaption` sent when Telegram refuses its formatting, and `sendSlackFiles`
14
+ takes `requireAll` to share nothing unless every file uploaded.
15
+
16
+ `sendGmailMessage` throws `GmailMaybeSent` when an upload fails after its last chunk went to
17
+ Gmail, which may have sent the message, and an approved email reply that fails so is `uncertain`,
18
+ never `failed`.
19
+
20
+ ## 0.163.0
21
+
22
+ The ontology of an app preview can serve the workspace's agent, built from the preview's commit,
23
+ for the preview app's web chat and for evals. The platform turns it on by giving the preview the
24
+ runtime identity of its hosting project (`SEGMENTSTREAM_RUNTIME_OIDC_ISSUER` and
25
+ `SEGMENTSTREAM_RUNTIME_OIDC_AUDIENCE`); the deployment observation then says `agent: true`, and
26
+ `previewRunsAgent()` reads it. The preview trusts only its hosting project's function tokens that
27
+ name `preview`, and only with `X-SegmentStream-Ontology-Deployment-Id` naming its own deployment
28
+ (`ONTOLOGY_DEPLOYMENT_HEADER`), because every preview of a workspace shares one hosting project.
29
+ It serves agent tokens, their introspection, the chat store, held replies, and members' attachments
30
+ and files, and still none of channels, pairings, accounts, visitors or tasks. Production never
31
+ trusts a preview's tokens. Manifests advertise `workspace-app-preview-agent-v1`.
32
+
33
+ Evals reach that agent as a test member with an agent token of the new first-party client
34
+ `agent-eval` (`AGENT_EVAL_CLIENT_ID`), on the existing grant and token tables. Only the platform
35
+ issues one, with its workload token bound to the preview, at `POST /api/ontology/agent/eval-tokens`
36
+ (`AGENT_EVAL_TOKENS_PATH`), which only a preview that runs the agent mounts. A token works 30
37
+ minutes by default and an hour at most (`EVAL_TOKEN_DEFAULT_SECONDS`, `EVAL_TOKEN_MAX_SECONDS`),
38
+ never past the preview's expiry, has no refresh token, and issuing another ends the member's earlier
39
+ eval session. Introspection answers it as the member's, with `eval: true`, and counts its turns
40
+ against no limit. Outside such a preview the client is refused: introspection answers its tokens
41
+ `active: false` and the agent cannot act with its grants.
42
+
3
43
  ## 0.162.0
4
44
 
5
45
  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/email.d.ts CHANGED
@@ -78,4 +78,4 @@ export declare function emailReplyMessage(reply: EmailReply): string;
78
78
  /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
79
79
  export declare function base64Url(text: string): string;
80
80
  export type { ChannelCall, ChannelReply, ChannelRequest } from "./channel-files.js";
81
- export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, gmailJson, sendGmailMessage, } from "./gmail-send.js";
81
+ export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, sendGmailMessage, } from "./gmail-send.js";
package/dist/email.js CHANGED
@@ -210,4 +210,4 @@ export function emailReplyMessage(reply) {
210
210
  export function base64Url(text) {
211
211
  return Buffer.from(text, "utf8").toString("base64url");
212
212
  }
213
- export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, gmailJson, sendGmailMessage, } from "./gmail-send.js";
213
+ export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, GmailMaybeSent, gmailJson, sendGmailMessage, } from "./gmail-send.js";
@@ -21,6 +21,16 @@ export declare class GmailError extends Error {
21
21
  readonly name = "GmailError";
22
22
  constructor(operation: string, status: number, detail?: string | undefined);
23
23
  }
24
+ /**
25
+ * A failure after the message's last byte went to Gmail: the upload may have completed and the
26
+ * message been sent, whatever the failure says, so it is never retried as unsent. `cause` is what
27
+ * failed, such as the probe of what Gmail held.
28
+ */
29
+ export declare class GmailMaybeSent extends Error {
30
+ readonly cause: unknown;
31
+ readonly name = "GmailMaybeSent";
32
+ constructor(cause: unknown);
33
+ }
24
34
  /** A reply's body as a JSON object, or an empty one. */
25
35
  export declare function gmailJson(reply: Pick<ChannelReply, "body">): Record<string, unknown>;
26
36
  /** Google's explanation of a refused call: its error message and reasons. */
@@ -29,6 +29,19 @@ export class GmailError extends Error {
29
29
  this.detail = detail;
30
30
  }
31
31
  }
32
+ /**
33
+ * A failure after the message's last byte went to Gmail: the upload may have completed and the
34
+ * message been sent, whatever the failure says, so it is never retried as unsent. `cause` is what
35
+ * failed, such as the probe of what Gmail held.
36
+ */
37
+ export class GmailMaybeSent extends Error {
38
+ cause;
39
+ name = "GmailMaybeSent";
40
+ constructor(cause) {
41
+ super("Gmail may have sent the message: its upload's last answer was lost.", { cause });
42
+ this.cause = cause;
43
+ }
44
+ }
32
45
  /** A reply's body as a JSON object, or an empty one. */
33
46
  export function gmailJson(reply) {
34
47
  try {
@@ -134,9 +147,13 @@ export async function sendGmailMessage(options) {
134
147
  const total = message.byteLength;
135
148
  let offset = 0;
136
149
  let recoveries = 0;
150
+ // Once the last byte was offered, Gmail may hold the whole message and have sent it.
151
+ let whole = false;
152
+ const maybeSent = (error) => (whole ? new GmailMaybeSent(error) : error);
137
153
  for (;;) {
138
154
  const end = Math.min(offset + UPLOAD_CHUNK_BYTES, total);
139
155
  let reply;
156
+ whole ||= end === total;
140
157
  try {
141
158
  reply = await request({
142
159
  api: session.api,
@@ -156,21 +173,26 @@ export async function sendGmailMessage(options) {
156
173
  // The chunk may or may not have arrived: Gmail says how much it holds.
157
174
  recoveries += 1;
158
175
  if (recoveries > UPLOAD_RECOVERIES) {
159
- throw error;
176
+ throw maybeSent(error);
177
+ }
178
+ try {
179
+ reply = await request({
180
+ api: session.api,
181
+ method: "PUT",
182
+ path: session.path,
183
+ headers: [["content-range", `bytes */${total}`]],
184
+ body: new Uint8Array(),
185
+ });
186
+ }
187
+ catch (probe) {
188
+ throw maybeSent(probe);
160
189
  }
161
- reply = await request({
162
- api: session.api,
163
- method: "PUT",
164
- path: session.path,
165
- headers: [["content-range", `bytes */${total}`]],
166
- body: new Uint8Array(),
167
- });
168
190
  }
169
191
  if (reply.status === 200 || reply.status === 201) {
170
192
  return gmailJson(reply);
171
193
  }
172
194
  if (reply.status !== 308) {
173
- throw new GmailError("messages.send", reply.status, gmailExplanation(reply));
195
+ throw maybeSent(new GmailError("messages.send", reply.status, gmailExplanation(reply)));
174
196
  }
175
197
  // `Range: bytes=0-N` is what Gmail holds; without it, nothing yet.
176
198
  const held = /^bytes=0-(\d+)$/u.exec(replyHeader(reply, "range") ?? "")?.[1];
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. */