@segmentstream/ontology 0.94.1 → 0.96.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 (58) hide show
  1. package/README.md +52 -7
  2. package/dist/analyze.d.ts +15 -3
  3. package/dist/analyze.js +217 -5
  4. package/dist/authoring.js +3 -0
  5. package/dist/index.d.ts +8 -8
  6. package/dist/index.js +5 -5
  7. package/dist/manifest-compatibility.d.ts +7 -0
  8. package/dist/manifest-compatibility.js +12 -0
  9. package/dist/manifest.d.ts +102 -18
  10. package/dist/manifest.js +41 -2
  11. package/dist/migrate/apply.d.ts +3 -2
  12. package/dist/migrate/apply.js +11 -3
  13. package/dist/migrate/model.d.ts +60 -12
  14. package/dist/migrate/plan.js +9 -1
  15. package/dist/migrate/storage.d.ts +7 -0
  16. package/dist/migrate/storage.js +24 -12
  17. package/dist/ontology.d.ts +2 -2
  18. package/dist/permissions.d.ts +9 -0
  19. package/dist/permissions.js +8 -0
  20. package/dist/runtime/channel-identity-admin.d.ts +41 -0
  21. package/dist/runtime/channel-identity-admin.js +223 -0
  22. package/dist/runtime/generated-actions.d.ts +2 -1
  23. package/dist/runtime/generated-actions.js +71 -3
  24. package/dist/runtime/member-tables.d.ts +7 -2
  25. package/dist/runtime/member-tables.js +18 -3
  26. package/dist/runtime/new-user-hook.d.ts +11 -1
  27. package/dist/runtime/new-user-hook.js +69 -29
  28. package/dist/runtime/pipeline.d.ts +2 -0
  29. package/dist/runtime/pipeline.js +11 -3
  30. package/dist/runtime/principals.d.ts +37 -3
  31. package/dist/runtime/principals.js +140 -36
  32. package/dist/runtime/resolve-agent-identity.js +43 -12
  33. package/dist/runtime/service-binding.js +11 -4
  34. package/dist/runtime/sql-runtime.d.ts +14 -1
  35. package/dist/runtime/sql-runtime.js +9 -0
  36. package/dist/runtime/user-identities.d.ts +5 -3
  37. package/dist/runtime/user-identities.js +9 -4
  38. package/dist/runtime/user-identity-sql.d.ts +4 -1
  39. package/dist/runtime/user-identity-sql.js +5 -2
  40. package/dist/runtime-source.d.ts +6 -0
  41. package/dist/runtime-source.js +11 -0
  42. package/dist/service/agent/attachments.js +4 -0
  43. package/dist/service/agent/authentication.d.ts +74 -2
  44. package/dist/service/agent/authentication.js +93 -11
  45. package/dist/service/agent/files.js +8 -1
  46. package/dist/service/agent/server.js +13 -2
  47. package/dist/service/authentication.js +58 -2
  48. package/dist/service/caller-context.d.ts +16 -0
  49. package/dist/service/chat/envelope.d.ts +20 -2
  50. package/dist/service/chat/envelope.js +10 -0
  51. package/dist/service/runtime-contract.d.ts +9 -0
  52. package/dist/service/schemas.d.ts +12 -0
  53. package/dist/sign-in.d.ts +32 -1
  54. package/dist/sign-in.js +12 -1
  55. package/dist/storage/attachments.d.ts +11 -0
  56. package/dist/user-identity.d.ts +14 -5
  57. package/dist/user-identity.js +25 -5
  58. package/package.json +1 -1
@@ -2,11 +2,11 @@ import { randomUUID } from "node:crypto";
2
2
  import { Effect, Option, Schema } from "effect";
3
3
  import { isSqlError } from "effect/unstable/sql/SqlError";
4
4
  import { Conflict } from "../errors.js";
5
- import { channelPolicyOf } from "../manifest.js";
5
+ import { channelPolicyOf, signUpRolesOf } from "../manifest.js";
6
6
  import { AGENT_IDENTITIES_TABLE, CHANNEL_USERS_TABLE } from "../migrate/storage.js";
7
7
  import { countAgentAttempt, effectiveChannelLimits } from "./agent-counters.js";
8
8
  import { runNewUserHook } from "./new-user-hook.js";
9
- import { makePrincipalUserWriter } from "./sql-runtime.js";
9
+ import { makeOntologyRuntime, makePrincipalUserWriter } from "./sql-runtime.js";
10
10
  import { makeIdentityWriter, USER_IDENTITY_TABLE } from "./user-identities.js";
11
11
  class RegistrationCapped extends Schema.TaggedError()("RegistrationCapped", {
12
12
  limit: Schema.Int,
@@ -23,6 +23,8 @@ function uniqueFailure(error) {
23
23
  /** Account admission shares pairing's lock and creates User plus identity in one transaction. */
24
24
  export function resolveAgentIdentity(ontology, sql, store, input, context = "agent") {
25
25
  const contact = input.turn || context === "channel_app";
26
+ // A channel `signUp` opens grants these roles; one an open `signIn.channels` opens grants member.
27
+ const signUpRoles = signUpRolesOf(ontology.manifest, input.provider);
26
28
  const policy = effectiveChannelLimits(sql, input.limits);
27
29
  const account = `${input.provider}:${input.externalId}`;
28
30
  const attempt = sql.withTransaction(Effect.gen(function* () {
@@ -36,7 +38,9 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
36
38
  if (identity === undefined) {
37
39
  if (!contact ||
38
40
  input.chat !== "private" ||
39
- channelPolicyOf(ontology.manifest, input.provider) !== "open") {
41
+ // @legacy ontology.legacy-channel-admission
42
+ (signUpRoles === undefined &&
43
+ channelPolicyOf(ontology.manifest, input.provider) !== "open")) {
40
44
  return { status: "pairing_required" };
41
45
  }
42
46
  const limited = yield* countAgentAttempt(sql, {
@@ -82,7 +86,23 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
82
86
  yield* sql.unsafe(`INSERT INTO "${AGENT_IDENTITIES_TABLE}"
83
87
  ("id", "provider", "external_id", "user_id", "display", "origin")
84
88
  VALUES ($1::uuid, $2, $3, $4::uuid, $5, 'provisioned')`, [identityId, input.provider, input.externalId, String(user.id), display]);
85
- yield* sql.unsafe(`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via") VALUES ($1::uuid, $2)`, [String(user.id), input.provider]);
89
+ if (signUpRoles === undefined) {
90
+ // @legacy ontology.legacy-channel-admission
91
+ yield* sql.unsafe(`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via") VALUES ($1::uuid, $2)`, [String(user.id), input.provider]);
92
+ }
93
+ else {
94
+ yield* sql.unsafe(`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via", "signed_up")
95
+ VALUES ($1::uuid, $2, true)`, [String(user.id), input.provider]);
96
+ }
97
+ if (signUpRoles !== undefined && signUpRoles.length > 0) {
98
+ yield* makeOntologyRuntime(ontology, sql, {
99
+ action: "user.grant_roles",
100
+ actionId,
101
+ principalId: null,
102
+ })
103
+ .members.grantRoles({ id: String(user.id), roles: signUpRoles })
104
+ .pipe(Effect.orDie);
105
+ }
86
106
  created = true;
87
107
  identity = yield* store.findIdentity(input);
88
108
  }
@@ -90,8 +110,9 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
90
110
  return yield* Effect.die(new Error("Provisioning did not create an identity."));
91
111
  }
92
112
  const [lifecycle] = yield* sql.unsafe(`SELECT "created_via", "blocked_at" IS NOT NULL AS "blocked",
93
- "on_new_user_completed_at" IS NOT NULL AS "completed"
94
- FROM "${CHANNEL_USERS_TABLE}" WHERE "user_id" = $1::uuid`, [identity.userId]);
113
+ "on_new_user_completed_at" IS NOT NULL AS "completed",
114
+ COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up"
115
+ FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid`, [identity.userId]);
95
116
  if (lifecycle?.blocked) {
96
117
  return { status: "refused", reason: "blocked" };
97
118
  }
@@ -123,11 +144,18 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
123
144
  if (username !== undefined) {
124
145
  yield* sql.unsafe(`UPDATE "${AGENT_IDENTITIES_TABLE}" SET "username" = $2 WHERE "id" = $1::uuid`, [identity.id, username]);
125
146
  }
126
- const provisioned = lifecycle !== undefined && !["invite", "email"].includes(lifecycle.created_via);
127
- if (contact &&
128
- provisioned &&
129
- member.principal.roles.length === 1 &&
130
- member.principal.roles[0] === "member") {
147
+ const signedUp = lifecycle?.signed_up === true;
148
+ // Admitted by themselves rather than invited or paired: a channel account, or anyone sign-up
149
+ // created, including by email. The agent resolves such a user's deferred turns again.
150
+ const provisioned = signedUp ||
151
+ (lifecycle !== undefined && !["invite", "email"].includes(lifecycle.created_via));
152
+ // Everyone sign-up created is counted, whatever roles they hold later.
153
+ const counted = signedUp ||
154
+ // @legacy ontology.legacy-channel-admission
155
+ (provisioned &&
156
+ member.principal.roles.length === 1 &&
157
+ member.principal.roles[0] === "member");
158
+ if (contact && counted) {
131
159
  for (const [scope, subject, window] of [
132
160
  ["turnsPerMinute", identity.userId, "minute"],
133
161
  ["turnsPerDay", identity.userId, "day"],
@@ -154,7 +182,10 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
154
182
  (identity.noticedAt === null ||
155
183
  (input.noticeVersion !== undefined && identity.noticeVersion !== input.noticeVersion) ||
156
184
  (input.noticeSha256 !== undefined && identity.noticeSha256 !== input.noticeSha256)),
157
- onNewUserPending: provisioned && !lifecycle?.completed && ontology.signIn.onNewUser !== undefined,
185
+ onNewUserPending: provisioned &&
186
+ !lifecycle?.completed &&
187
+ // @legacy ontology.legacy-channel-admission
188
+ (signedUp ? ontology.signIn.onSignUp : ontology.signIn.onNewUser) !== undefined,
158
189
  };
159
190
  }));
160
191
  const admission = policy.pipe(Effect.andThen(attempt)).pipe(Effect.catchIf(uniqueFailure, () => attempt), Effect.catchTag("RegistrationCapped", ({ limit }) =>
@@ -19,8 +19,9 @@ import { generatedActions } from "./generated-actions.js";
19
19
  import { sqlChannelSessionStore } from "./channel-sessions.js";
20
20
  import { sqlOAuthStore } from "./oauth.js";
21
21
  import { sqlFederationStore } from "./federation.js";
22
+ import { runNewUserHook, withSignUpOnboarding } from "./new-user-hook.js";
22
23
  import { runAction } from "./pipeline.js";
23
- import { checkSignIn, resolvePrincipalByApiKey, resolvePrincipalByIdentity, resolvePipelineWorker, resolveHookService, resolveWorkflowUser, } from "./principals.js";
24
+ import { checkSignIn, resolveApiKeyCredential, resolvePrincipalByApiKey, resolveSignInState, resolvePipelineWorker, resolveHookService, resolveWorkflowUser, } from "./principals.js";
24
25
  import { postgresTls } from "./postgres-tls.js";
25
26
  import { makeOntologyRuntime } from "./sql-runtime.js";
26
27
  import { NEON_AUTH_PROVIDER, SIGN_IN_ORIGIN_SQL, USER_IDENTITY_TABLE, } from "./user-identity-sql.js";
@@ -206,12 +207,17 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
206
207
  AND i.origin::text IN ${SIGN_IN_ORIGIN_SQL} AND i.revoked_at IS NULL)`, [identity.email, NEON_AUTH_PROVIDER]);
207
208
  return neon ? yield* store.principal(neon.id) : undefined;
208
209
  }).pipe(Effect.orDie)
209
- : withSql(resolvePrincipalByIdentity(ontology, {
210
+ : withSql(resolveSignInState(ontology, {
210
211
  identityProvider: identity.provider,
211
212
  identitySubject: identity.subject,
212
213
  ...(identity.email === undefined ? {} : { email: identity.email }),
213
214
  ...(identity.name === undefined ? {} : { name: identity.name }),
214
- })).pipe(Effect.catchTag("PrincipalRejected", (rejection) => rejection.reason === "not_invited"
215
+ }).pipe(
216
+ // A user email sign-up created runs `onSignUp` once its creation committed,
217
+ // before they use the app; a failure leaves it pending for their next request.
218
+ Effect.tap((state) => state.signUpPending && ontology.signIn.onSignUp !== undefined
219
+ ? runNewUserHook(ontology, sql, state.principal)
220
+ : Effect.void), Effect.map((state) => state.principal))).pipe(Effect.catchTag("PrincipalRejected", (rejection) => rejection.reason === "not_invited"
215
221
  ? rejectedAs("sign_in")(rejection).pipe(Effect.andThen(Effect.fail(new NotInvited({ message: rejection.message }))))
216
222
  : rejectedAs("sign_in")(rejection))),
217
223
  resolveHookService: (heldRole) => withSql(resolveHookService(ontology, heldRole)).pipe(Effect.catchTag("PrincipalRejected", rejectedAs("hook_service"))),
@@ -221,6 +227,7 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
221
227
  ? Effect.succeed({ allowed: false })
222
228
  : withSql(checkSignIn(ontology, email)),
223
229
  resolveApiKey: (key) => withSql(resolvePrincipalByApiKey(ontology, Redacted.value(key))).pipe(Effect.catchTag("PrincipalRejected", rejectedAs("api_key"))),
230
+ resolveApiKeyCredential: (key) => withSql(resolveApiKeyCredential(ontology, Redacted.value(key))).pipe(Effect.catchTag("PrincipalRejected", rejectedAs("api_key"))),
224
231
  appliedHash: readCatalog({ sql }).pipe(Effect.map((manifest) => manifest?.hash), Effect.orDie),
225
232
  replicationEnabled: Effect.gen(function* () {
226
233
  const [presence] = yield* sql.unsafe("SELECT to_regclass('_ontology_replication') IS NOT NULL AS present");
@@ -236,7 +243,7 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
236
243
  .create(input)
237
244
  .pipe(withStarter, Effect.provideService(ActionTransactions, actionTransactions)),
238
245
  },
239
- federation: sqlFederationStore(ontology, sql),
246
+ federation: withSignUpOnboarding(ontology, sql, sqlFederationStore(ontology, sql)),
240
247
  agents: {
241
248
  ...agents,
242
249
  resolveIdentity: (input) => agents
@@ -1,10 +1,11 @@
1
1
  import { Effect } from "effect";
2
2
  import type { SqlClient } from "effect/unstable/sql";
3
3
  import { type SqlError } from "effect/unstable/sql/SqlError";
4
- import { Conflict, type NotFound } from "../errors.js";
4
+ import { ActionRejected, Conflict, type NotFound } from "../errors.js";
5
5
  import type { Ontology } from "../ontology.js";
6
6
  import type { Query, QueryResult } from "../query.js";
7
7
  import type { OntologyRuntimeService, StoredRecord, StoredValues } from "../runtime.js";
8
+ import { type AttachIdentityInput } from "./channel-identity-admin.js";
8
9
  import { type BatchOperation } from "./batch.js";
9
10
  import { InvalidQuery, UnknownRole } from "./errors.js";
10
11
  import type { Edit, HistoryEntry, HistoryScope } from "./history.js";
@@ -103,6 +104,18 @@ export interface SqlOntologyRuntime extends OntologyRuntimeService {
103
104
  readonly active: boolean;
104
105
  }) => Effect.Effect<StoredRecord, NotFound>;
105
106
  };
107
+ /**
108
+ * The writes behind the built-in `user_identity.attach` and `user_identity.revoke`: an
109
+ * administrator attaching a member's chat account and revoking one. Only those two actions run
110
+ * them; anything else that reaches them is a defect, so that no other action, handler or
111
+ * workflow binds an account to a member.
112
+ */
113
+ readonly identities: {
114
+ readonly attach: (input: AttachIdentityInput) => Effect.Effect<StoredRecord, ActionRejected | Conflict | NotFound>;
115
+ readonly revoke: (input: {
116
+ readonly id: string;
117
+ }) => Effect.Effect<StoredRecord, NotFound>;
118
+ };
106
119
  }
107
120
  /** A unique violation becomes Conflict, naming the property when the index covers one column. */
108
121
  export declare function uniqueConflict(entity: EntityModel, error: SqlError, batch?: {
@@ -5,6 +5,7 @@ import { ActionRejected, Conflict } from "../errors.js";
5
5
  import { toSnakeCase } from "../names.js";
6
6
  import { User } from "../user.js";
7
7
  import { UserIdentity } from "../user-identity.js";
8
+ import { ATTACH_IDENTITY_ACTION, attachChannelIdentity, REVOKE_IDENTITY_ACTION, revokeChannelIdentity, } from "./channel-identity-admin.js";
8
9
  import { ACTION_MAX_BATCH_ROWS, BATCH_MAX_BYTES, BATCH_MAX_ROWS, batchInputBytes, executeBatch, planBatch, } from "./batch.js";
9
10
  import { logBatchConflict } from "./batch-diagnostics.js";
10
11
  import { runMetricQuery } from "./metric-query.js";
@@ -269,6 +270,10 @@ export function makeOntologyRuntime(ontology, sql, scope) {
269
270
  outcome: Exit.isSuccess(exit) ? "success" : "failure",
270
271
  }))));
271
272
  });
273
+ // Sign-in identities change only through the platform; these two are its actions' writes.
274
+ const identityAction = (action, operation) => scope?.action === action && scope.principalId !== null
275
+ ? operation(scope)
276
+ : Effect.die(new Error(`Sign-in identities change only through ${action}, never in another action.`));
272
277
  const declaredRoles = ontology.roles.map((candidate) => candidate.name);
273
278
  const memberWrite = (operation) => write(User.name, (writeContext, entity) => operation({ ...writeContext, sql, roles: declaredRoles }, entity));
274
279
  const members = {
@@ -358,5 +363,9 @@ export function makeOntologyRuntime(ontology, sql, scope) {
358
363
  setUserActive: members.setActive,
359
364
  sendUserSignInLink: (input) => memberWrite((context, entity) => queueSignInEmail(context, entity, ontology.manifest.emails ?? {}, input)).pipe(Effect.catchTag("Conflict", (error) => Effect.die(error)), Effect.flatMap((queued) => Effect.sync(() => scope?.onSignInEmail?.(queued)))),
360
365
  members,
366
+ identities: {
367
+ attach: (input) => identityAction(ATTACH_IDENTITY_ACTION, (actionScope) => attachChannelIdentity(ontology, sql, actionScope, input)),
368
+ revoke: (input) => identityAction(REVOKE_IDENTITY_ACTION, (actionScope) => revokeChannelIdentity(ontology, sql, actionScope, input)),
369
+ },
361
370
  };
362
371
  }
@@ -23,13 +23,15 @@ export interface IdentityCreate extends IdentityAccount {
23
23
  }
24
24
  /**
25
25
  * The platform's writes of `user_identity`: each runs in its own savepoint of the caller's
26
- * transaction and records history under `scope`, without a principal. Only these writes change the
27
- * entity; the general runtime refuses to. They change `user_identity` alone: callers write the
28
- * legacy stores beside them.
26
+ * transaction and records history under `scope`, without a principal unless `scope` names the
27
+ * administrator whose `user_identity` action it runs. Only these writes change the entity; the
28
+ * general runtime refuses to. They change `user_identity` alone: callers write the legacy stores
29
+ * beside them.
29
30
  */
30
31
  export declare function makeIdentityWriter(ontology: Ontology, sql: SqlClient.SqlClient, scope: {
31
32
  readonly action: string;
32
33
  readonly actionId: string;
34
+ readonly principalId?: string | null;
33
35
  }): {
34
36
  /** Creates a live identity; Conflict when its account or member key is held. */
35
37
  create: (input: IdentityCreate) => Effect.Effect<StoredRecord, Conflict | NotFound>;
@@ -24,9 +24,10 @@ export function userIdentitiesAvailable(sql) {
24
24
  }
25
25
  /**
26
26
  * The platform's writes of `user_identity`: each runs in its own savepoint of the caller's
27
- * transaction and records history under `scope`, without a principal. Only these writes change the
28
- * entity; the general runtime refuses to. They change `user_identity` alone: callers write the
29
- * legacy stores beside them.
27
+ * transaction and records history under `scope`, without a principal unless `scope` names the
28
+ * administrator whose `user_identity` action it runs. Only these writes change the entity; the
29
+ * general runtime refuses to. They change `user_identity` alone: callers write the legacy stores
30
+ * beside them.
30
31
  */
31
32
  export function makeIdentityWriter(ontology, sql, scope) {
32
33
  const model = ontologyModel(ontology);
@@ -34,7 +35,11 @@ export function makeIdentityWriter(ontology, sql, scope) {
34
35
  const client = sql.withoutTransforms();
35
36
  const context = () => ({
36
37
  model,
37
- scope: { action: scope.action, actionId: scope.actionId, principalId: null },
38
+ scope: {
39
+ action: scope.action,
40
+ actionId: scope.actionId,
41
+ principalId: scope.principalId ?? null,
42
+ },
38
43
  edits: [],
39
44
  run: (text, params) => client.unsafe(text, params.values),
40
45
  });
@@ -17,7 +17,10 @@ export declare const OIDC_PROVIDER = "oidc";
17
17
  export declare const LEGACY_OIDC_PREFIX = "oidc:";
18
18
  /** Origins of the identities a member signs in with, which the member's user columns mirror. */
19
19
  export declare const SIGN_IN_ORIGINS: ReadonlyArray<UserIdentityOrigin>;
20
- /** Origins of channel accounts, which `_agent_identities` mirrors with the same ids. */
20
+ /**
21
+ * Origins of channel accounts, which `_agent_identities` mirrors with the same ids: paired by the
22
+ * member, created by an open channel, or attached by an administrator.
23
+ */
21
24
  export declare const CHANNEL_ORIGINS: ReadonlyArray<UserIdentityOrigin>;
22
25
  /** `origin IN (…)` of sign-in identities, for SQL on the alias `i`. */
23
26
  export declare const SIGN_IN_ORIGIN_SQL: string;
@@ -17,8 +17,11 @@ export const OIDC_PROVIDER = "oidc";
17
17
  export const LEGACY_OIDC_PREFIX = "oidc:";
18
18
  /** Origins of the identities a member signs in with, which the member's user columns mirror. */
19
19
  export const SIGN_IN_ORIGINS = ["invite", "sign_in", "link"];
20
- /** Origins of channel accounts, which `_agent_identities` mirrors with the same ids. */
21
- export const CHANNEL_ORIGINS = ["pairing", "channel"];
20
+ /**
21
+ * Origins of channel accounts, which `_agent_identities` mirrors with the same ids: paired by the
22
+ * member, created by an open channel, or attached by an administrator.
23
+ */
24
+ export const CHANNEL_ORIGINS = ["pairing", "channel", "attach"];
22
25
  const originList = (origins) => `(${origins.map((origin) => `'${origin}'`).join(", ")})`;
23
26
  /** `origin IN (…)` of sign-in identities, for SQL on the alias `i`. */
24
27
  export const SIGN_IN_ORIGIN_SQL = originList(SIGN_IN_ORIGINS);
@@ -8,6 +8,12 @@ export declare const RuntimeSource: Schema.Union<readonly [Schema.Struct<{
8
8
  readonly reply_to_message_id: Schema.optionalKey<Schema.String>;
9
9
  readonly callback_query_id: Schema.optionalKey<Schema.String>;
10
10
  readonly sender: Schema.optionalKey<Schema.String>;
11
+ readonly location: Schema.optionalKey<Schema.Struct<{
12
+ readonly latitude: Schema.Number;
13
+ readonly longitude: Schema.Number;
14
+ readonly horizontal_accuracy: Schema.optionalKey<Schema.Number>;
15
+ readonly live_period: Schema.optionalKey<Schema.Int>;
16
+ }>>;
11
17
  readonly attachments: Schema.optionalKey<Schema.$Array<Schema.Struct<{
12
18
  readonly file_id: Schema.String;
13
19
  readonly file_unique_id: Schema.optionalKey<Schema.String>;
@@ -1,5 +1,15 @@
1
1
  import { Schema } from "effect";
2
2
  const Id = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512));
3
+ /**
4
+ * The location a Telegram message shared, as the Bot API sends it: a live location's latest update
5
+ * or a pinned point. Only the runtime that received the message reports it, never a model.
6
+ */
7
+ const TelegramLocation = Schema.Struct({
8
+ latitude: Schema.Number.check(Schema.isBetween({ minimum: -90, maximum: 90 })),
9
+ longitude: Schema.Number.check(Schema.isBetween({ minimum: -180, maximum: 180 })),
10
+ horizontal_accuracy: Schema.optionalKey(Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1500 }))),
11
+ live_period: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
12
+ });
3
13
  /** A Telegram chat, with the references Telegram's own actions and attachments use. */
4
14
  const TelegramRuntimeSource = Schema.Struct({
5
15
  provider: Schema.Literal("telegram"),
@@ -9,6 +19,7 @@ const TelegramRuntimeSource = Schema.Struct({
9
19
  reply_to_message_id: Schema.optionalKey(Id),
10
20
  callback_query_id: Schema.optionalKey(Id),
11
21
  sender: Schema.optionalKey(Id),
22
+ location: Schema.optionalKey(TelegramLocation),
12
23
  attachments: Schema.optionalKey(Schema.Array(Schema.Struct({
13
24
  file_id: Id,
14
25
  file_unique_id: Schema.optionalKey(Id),
@@ -117,6 +117,9 @@ export function attachmentsLayer(options) {
117
117
  agents,
118
118
  verify: verifyRuntime,
119
119
  allowUnpairedMember: true,
120
+ ...(backend.resolveApiKeyCredential === undefined
121
+ ? {}
122
+ : { resolveApiKey: backend.resolveApiKeyCredential }),
120
123
  });
121
124
  return authenticated.ok
122
125
  ? yield* answer(request, authenticated.caller, attachments)
@@ -171,6 +174,7 @@ export function attachmentsLayer(options) {
171
174
  const metadata = yield* consumeChatEnvelope(promotion._meta ?? {}, {
172
175
  kind: "runtime",
173
176
  subjectId: caller.principal.id,
177
+ ...(caller.delegatedBy === undefined ? {} : { delegatedBy: caller.delegatedBy }),
174
178
  });
175
179
  const attachmentId = yield* idOf;
176
180
  const envelopeSource = metadata.envelope?.source;
@@ -1,8 +1,8 @@
1
- import { Effect } from "effect";
1
+ import { Effect, Redacted } from "effect";
2
2
  import { HttpServerRequest } from "effect/unstable/http";
3
3
  import type { AttachmentCaller } from "../../storage/attachments.js";
4
4
  import { RequestId } from "../errors.js";
5
- import type { AgentStore } from "../runtime-contract.js";
5
+ import type { AgentStore, OntologyBackend } from "../runtime-contract.js";
6
6
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
7
7
  export declare const CONVERSATION_HEADER = "x-segmentstream-agent-conversation";
8
8
  export declare const SESSION_HEADER = "x-segmentstream-agent-session";
@@ -13,10 +13,82 @@ export declare function authenticateAgentCaller(input: {
13
13
  readonly verify: RuntimeTokenVerifier;
14
14
  /** Temporary attachments authorize active members against the chat registry, without a pairing. */
15
15
  readonly allowUnpairedMember?: boolean;
16
+ /**
17
+ * Resolves `ssk_` keys, so that an external runtime holding an API key with delegation reaches
18
+ * these routes for a member with a live account of the provider it names.
19
+ */
20
+ readonly resolveApiKey?: ApiKeyCredentialResolver;
16
21
  }): Effect.Effect<{
17
22
  readonly ok: false;
18
23
  readonly response: import("effect/unstable/http/HttpServerResponse").HttpServerResponse;
19
24
  } | {
20
25
  readonly ok: true;
21
26
  readonly caller: AttachmentCaller;
27
+ readonly response?: undefined;
22
28
  }, never, RequestId | HttpServerRequest.ParsedSearchParams>;
29
+ /** Resolves an `ssk_` key to its user and whether it acts with delegation. */
30
+ export type ApiKeyCredentialResolver = NonNullable<OntologyBackend["Service"]["resolveApiKeyCredential"]>;
31
+ /**
32
+ * The member an external runtime with an API key with delegation acts for on an agent route: the
33
+ * member `X-SegmentStream-Act-As` names, who must be active and hold a live account of the provider
34
+ * `X-SegmentStream-Identity-Provider` names, even where the app's own agent needs no pairing. An
35
+ * ordinary API key, and a task's secret, are refused.
36
+ */
37
+ export declare function delegatedAgentMember(request: HttpServerRequest.HttpServerRequest, agents: AgentStore, resolveApiKey: ApiKeyCredentialResolver, bearer: Redacted.Redacted<string>): Effect.Effect<{
38
+ readonly status: "rejected";
39
+ readonly detail?: undefined;
40
+ readonly member?: undefined;
41
+ client?: undefined;
42
+ } | {
43
+ readonly status: "refused";
44
+ readonly detail: string;
45
+ readonly member?: undefined;
46
+ client?: undefined;
47
+ } | {
48
+ readonly status: "member";
49
+ readonly member: {
50
+ authenticatedVia: string;
51
+ execution?: import("../../index.js").WorkloadExecution;
52
+ workflow?: {
53
+ readonly name: string;
54
+ readonly subject: string;
55
+ };
56
+ id: string;
57
+ kind: "member" | "service";
58
+ roles: ReadonlyArray<string>;
59
+ permissions: ReadonlyArray<string>;
60
+ scopes?: ReadonlyArray<import("../../permissions.js").ScopedPermission>;
61
+ };
62
+ readonly client: {
63
+ readonly id: string;
64
+ readonly account: {
65
+ provider: string;
66
+ subject: string;
67
+ };
68
+ };
69
+ readonly detail?: undefined;
70
+ }, never, never>;
71
+ /**
72
+ * The active, unblocked member an API key with delegation acts for, with their roles now and
73
+ * `authenticatedVia` the provider, and the live chat account of that provider it acts through;
74
+ * `undefined` for anyone else.
75
+ */
76
+ export declare function delegatedAccount(agents: AgentStore, actAs: string, provider: string): Effect.Effect<{
77
+ member: {
78
+ authenticatedVia: string;
79
+ execution?: import("../../index.js").WorkloadExecution;
80
+ workflow?: {
81
+ readonly name: string;
82
+ readonly subject: string;
83
+ };
84
+ id: string;
85
+ kind: "member" | "service";
86
+ roles: ReadonlyArray<string>;
87
+ permissions: ReadonlyArray<string>;
88
+ scopes?: ReadonlyArray<import("../../permissions.js").ScopedPermission>;
89
+ };
90
+ account: {
91
+ provider: string;
92
+ subject: string;
93
+ };
94
+ } | undefined, never, never>;
@@ -2,7 +2,8 @@ import { Effect, 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
- import { ACT_AS_HEADER, AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
5
+ import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
+ import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
6
7
  export const CONVERSATION_HEADER = "x-segmentstream-agent-conversation";
7
8
  export const SESSION_HEADER = "x-segmentstream-agent-session";
8
9
  const CONVERSATION = /^[a-z][a-z0-9_-]{0,31}:[A-Za-z0-9:_-]{1,200}$/;
@@ -15,8 +16,18 @@ export function authenticateAgentCaller(input) {
15
16
  const credential = HttpApiBuilder.securityDecode(HttpApiSecurity.bearer);
16
17
  const bearer = yield* Effect.provideService(credential, HttpServerRequest.HttpServerRequest, request);
17
18
  const token = Redacted.value(bearer);
18
- const verified = token === "" ? undefined : yield* Effect.promise(() => verify(token));
19
19
  const denied = (response) => ({ ok: false, response: toServerResponse(response) });
20
+ if (input.resolveApiKey !== undefined && token.startsWith(API_KEY_PREFIX)) {
21
+ const delegated = yield* delegatedAgentMember(request, agents, input.resolveApiKey, bearer);
22
+ if (delegated.status === "rejected") {
23
+ return denied(unauthorized(requestId, "The bearer token is invalid, expired or revoked."));
24
+ }
25
+ if (delegated.status === "refused") {
26
+ return denied(forbidden(requestId, delegated.detail));
27
+ }
28
+ return agentCaller(request, requestId, delegated.member, delegated.client);
29
+ }
30
+ const verified = token === "" ? undefined : yield* Effect.promise(() => verify(token));
20
31
  switch (verified?.status) {
21
32
  case "valid":
22
33
  break;
@@ -33,8 +44,6 @@ export function authenticateAgentCaller(input) {
33
44
  return denied(forbidden(requestId, `This route does not accept ${AGENT_TASK_HEADER}.`));
34
45
  }
35
46
  const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
36
- const conversation = request.headers[CONVERSATION_HEADER]?.trim() ?? "";
37
- const session = request.headers[SESSION_HEADER]?.trim() ?? "";
38
47
  const member = actAs === ""
39
48
  ? undefined
40
49
  : input.allowUnpairedMember
@@ -45,14 +54,87 @@ export function authenticateAgentCaller(input) {
45
54
  ? notFound(requestId, "Attachment not found.")
46
55
  : forbidden(requestId, "The member is inactive or has not paired with the agent."));
47
56
  }
48
- if (!CONVERSATION.test(conversation) || (session !== "" && !SESSION.test(session))) {
49
- return denied(forbidden(requestId, "The agent names the chat and session of every request."));
57
+ return agentCaller(request, requestId, member);
58
+ });
59
+ }
60
+ /** The chat and session every agent request names, with the member it acts for. */
61
+ function agentCaller(request, requestId, member, delegatedBy) {
62
+ const conversation = request.headers[CONVERSATION_HEADER]?.trim() ?? "";
63
+ const session = request.headers[SESSION_HEADER]?.trim() ?? "";
64
+ if (!CONVERSATION.test(conversation) || (session !== "" && !SESSION.test(session))) {
65
+ return {
66
+ ok: false,
67
+ response: toServerResponse(forbidden(requestId, "The agent names the chat and session of every request.")),
68
+ };
69
+ }
70
+ const caller = {
71
+ principal: member,
72
+ conversation,
73
+ ...(session === "" ? {} : { sessionId: session }),
74
+ ...(delegatedBy === undefined ? {} : { delegatedBy }),
75
+ };
76
+ return { ok: true, caller };
77
+ }
78
+ /**
79
+ * The member an external runtime with an API key with delegation acts for on an agent route: the
80
+ * member `X-SegmentStream-Act-As` names, who must be active and hold a live account of the provider
81
+ * `X-SegmentStream-Identity-Provider` names, even where the app's own agent needs no pairing. An
82
+ * ordinary API key, and a task's secret, are refused.
83
+ */
84
+ export function delegatedAgentMember(request, agents, resolveApiKey, bearer) {
85
+ return Effect.gen(function* () {
86
+ const resolved = yield* resolveApiKey(bearer);
87
+ if (resolved === undefined) {
88
+ return { status: "rejected" };
89
+ }
90
+ if (!resolved.delegation) {
91
+ return { status: "refused", detail: "Only the app's agent calls this route." };
50
92
  }
51
- const caller = {
52
- principal: member,
53
- conversation,
54
- ...(session === "" ? {} : { sessionId: session }),
93
+ if (agentTaskSecret(request) !== undefined) {
94
+ return {
95
+ status: "refused",
96
+ detail: `An API key with delegation never presents ${AGENT_TASK_HEADER}.`,
97
+ };
98
+ }
99
+ const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
100
+ const provider = request.headers[ACT_AS_PROVIDER_HEADER]?.trim() ?? "";
101
+ if (actAs === "" || provider === "") {
102
+ return {
103
+ status: "refused",
104
+ detail: `An API key with delegation names the member in ${ACT_AS_HEADER} and the provider of ` +
105
+ `their account in ${ACT_AS_PROVIDER_HEADER}.`,
106
+ };
107
+ }
108
+ const delegated = yield* delegatedAccount(agents, actAs, provider);
109
+ if (delegated === undefined) {
110
+ return {
111
+ status: "refused",
112
+ detail: `The member is inactive or has no live ${provider} account.`,
113
+ };
114
+ }
115
+ return {
116
+ status: "member",
117
+ member: delegated.member,
118
+ client: { id: resolved.principal.id, account: delegated.account },
55
119
  };
56
- return { ok: true, caller };
120
+ });
121
+ }
122
+ /**
123
+ * The active, unblocked member an API key with delegation acts for, with their roles now and
124
+ * `authenticatedVia` the provider, and the live chat account of that provider it acts through;
125
+ * `undefined` for anyone else.
126
+ */
127
+ export function delegatedAccount(agents, actAs, provider) {
128
+ return Effect.gen(function* () {
129
+ const member = yield* agents.actingMember(actAs, provider);
130
+ const account = member === undefined
131
+ ? undefined
132
+ : (yield* agents.listIdentities(member.id)).find((identity) => identity.provider === provider && identity.revokedAt === null);
133
+ return member === undefined || member.kind !== "member" || account === undefined
134
+ ? undefined
135
+ : {
136
+ member: { ...member, authenticatedVia: provider },
137
+ account: { provider: account.provider, subject: account.externalId },
138
+ };
57
139
  });
58
140
  }
@@ -19,7 +19,14 @@ export function filesLayer(options) {
19
19
  }
20
20
  const read = (request) => Effect.gen(function* () {
21
21
  const requestId = yield* RequestId;
22
- const authenticated = yield* authenticateAgentCaller({ request, agents, verify });
22
+ const authenticated = yield* authenticateAgentCaller({
23
+ request,
24
+ agents,
25
+ verify,
26
+ ...(backend.resolveApiKeyCredential === undefined
27
+ ? {}
28
+ : { resolveApiKey: backend.resolveApiKeyCredential }),
29
+ });
23
30
  if (!authenticated.ok) {
24
31
  return authenticated.response;
25
32
  }
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { Effect, Layer, Redacted, Result, Schema } from "effect";
4
4
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
5
5
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
6
+ import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
7
  import { schemaIssues } from "../../runtime/validation.js";
7
8
  import { BASE_PATH } from "../api.js";
8
9
  import { CurrentPrincipal, withPrincipal, } from "../authentication.js";
@@ -307,10 +308,20 @@ export function agentLayer(options) {
307
308
  const limiter = fixedWindowLimiter(PAIRING_LIMIT);
308
309
  const credential = HttpApiBuilder.securityDecode(HttpApiSecurity.bearer);
309
310
  const bearerOf = (request) => Effect.provideService(credential, HttpServerRequest.HttpServerRequest, request);
310
- const asRuntime = (answer) => (request) => Effect.gen(function* () {
311
+ const asRuntime = (answer, route = {}) => (request) => Effect.gen(function* () {
311
312
  const requestId = yield* RequestId;
312
313
  const bearer = yield* bearerOf(request);
313
314
  const token = Redacted.value(bearer);
315
+ if (route.delegated === true &&
316
+ token.startsWith(API_KEY_PREFIX) &&
317
+ backend.resolveApiKeyCredential !== undefined) {
318
+ const resolved = yield* backend.resolveApiKeyCredential(bearer);
319
+ if (resolved?.delegation === true) {
320
+ return agentTaskSecret(request) === undefined
321
+ ? yield* answer(request)
322
+ : toServerResponse(forbidden(requestId, `This route does not accept ${AGENT_TASK_HEADER}.`));
323
+ }
324
+ }
314
325
  const verified = options.verifyRuntime === undefined || token === ""
315
326
  ? undefined
316
327
  : yield* Effect.promise(() => options.verifyRuntime(token));
@@ -353,7 +364,7 @@ export function agentLayer(options) {
353
364
  yield* router.add("GET", `${PAIRINGS_PATH}/:code`, asMember(() => describePairing(store)));
354
365
  yield* router.add("POST", `${PAIRINGS_PATH}/:code/approve`, asMember((_, member) => approvePairing(store, member)));
355
366
  yield* router.add("GET", IDENTITIES_PATH, asMember((_, member) => listIdentities(store, member)));
356
- yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store)));
367
+ yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store), { delegated: true }));
357
368
  yield* router.add("POST", `${IDENTITIES_PATH}/resolve`, asRuntime(resolveChannelIdentity(store)));
358
369
  yield* router.add("POST", `${IDENTITIES_PATH}/notice`, asRuntime(recordNotice(store)));
359
370
  yield* router.add("POST", `${IDENTITIES_PATH}/limit-notice`, asRuntime(completeLimitNotice(store)));