@segmentstream/ontology 0.109.0 → 0.110.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 (57) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +21 -0
  3. package/dist/analyze.js +55 -3
  4. package/dist/index.d.ts +5 -5
  5. package/dist/index.js +2 -2
  6. package/dist/manifest.d.ts +94 -5
  7. package/dist/manifest.js +41 -6
  8. package/dist/migrate/apply.d.ts +4 -3
  9. package/dist/migrate/apply.js +8 -3
  10. package/dist/migrate/model.d.ts +46 -2
  11. package/dist/migrate/plan.js +1 -1
  12. package/dist/migrate/preview.js +2 -1
  13. package/dist/migrate/storage.d.ts +13 -1
  14. package/dist/migrate/storage.js +33 -1
  15. package/dist/runtime/agent-counters.d.ts +36 -0
  16. package/dist/runtime/agent-counters.js +84 -0
  17. package/dist/runtime/agent-web.d.ts +1 -1
  18. package/dist/runtime/agent-web.js +175 -3
  19. package/dist/runtime/batch.js +4 -6
  20. package/dist/runtime/history.d.ts +24 -0
  21. package/dist/runtime/history.js +35 -1
  22. package/dist/runtime/pipeline.js +3 -0
  23. package/dist/runtime/principals.d.ts +6 -0
  24. package/dist/runtime/principals.js +25 -6
  25. package/dist/runtime/reads.js +9 -2
  26. package/dist/runtime/sign-in-links.d.ts +10 -0
  27. package/dist/runtime/sign-in-links.js +26 -25
  28. package/dist/runtime/sql-runtime.d.ts +1 -1
  29. package/dist/runtime/sql-runtime.js +3 -2
  30. package/dist/runtime/writes.js +4 -6
  31. package/dist/runtime.d.ts +18 -0
  32. package/dist/service/agent/authentication.d.ts +3 -2
  33. package/dist/service/agent/authentication.js +2 -11
  34. package/dist/service/agent/bot-check.d.ts +42 -0
  35. package/dist/service/agent/bot-check.js +32 -0
  36. package/dist/service/agent/guest-sign-up.d.ts +140 -0
  37. package/dist/service/agent/guest-sign-up.js +545 -0
  38. package/dist/service/agent/protocol.d.ts +33 -1
  39. package/dist/service/agent/protocol.js +41 -1
  40. package/dist/service/agent/server.d.ts +17 -0
  41. package/dist/service/agent/server.js +42 -3
  42. package/dist/service/agent/web-tokens.d.ts +21 -3
  43. package/dist/service/agent/web-tokens.js +79 -6
  44. package/dist/service/authentication.d.ts +8 -1
  45. package/dist/service/authentication.js +26 -5
  46. package/dist/service/config.d.ts +10 -0
  47. package/dist/service/operations.d.ts +5 -0
  48. package/dist/service/runtime-contract.d.ts +124 -1
  49. package/dist/service/runtime-identity.d.ts +23 -0
  50. package/dist/service/runtime-identity.js +31 -0
  51. package/dist/service/schemas.d.ts +46 -2
  52. package/dist/service/service.js +27 -1
  53. package/dist/service/webhooks.d.ts +15 -0
  54. package/dist/service/webhooks.js +15 -4
  55. package/dist/sign-in.d.ts +29 -0
  56. package/dist/sign-in.js +8 -0
  57. package/package.json +1 -1
@@ -30,6 +30,15 @@ export declare const Edit: Schema.Struct<{
30
30
  }>>;
31
31
  }>;
32
32
  export type Edit = typeof Edit.Type;
33
+ /**
34
+ * The chat the app's agent acted in when it ran the action, and its session there, as the chat
35
+ * archive names them: a guest's chat is `web` and `guest:<id>`.
36
+ */
37
+ export declare const ChatProvenance: Schema.Struct<{
38
+ readonly provider: Schema.String;
39
+ readonly chatId: Schema.String;
40
+ readonly sessionId: Schema.optionalKey<Schema.String>;
41
+ }>;
33
42
  /** A row of `<entity>_history`. */
34
43
  export declare const HistoryEntry: Schema.Struct<{
35
44
  readonly execution: Schema.optionalKey<Schema.Struct<{
@@ -52,6 +61,12 @@ export declare const HistoryEntry: Schema.Struct<{
52
61
  readonly issuedAt: Schema.Number;
53
62
  readonly expiresAt: Schema.Number;
54
63
  }>>;
64
+ /** The chat the app's agent ran the action from, for anyone it acted for, a guest included. */
65
+ readonly chat: Schema.optionalKey<Schema.Struct<{
66
+ readonly provider: Schema.String;
67
+ readonly chatId: Schema.String;
68
+ readonly sessionId: Schema.optionalKey<Schema.String>;
69
+ }>>;
55
70
  readonly id: Schema.String;
56
71
  readonly recordId: Schema.String;
57
72
  /** The qualified action, for example `lead.changeStatus`. */
@@ -76,6 +91,7 @@ export interface HistoryWrite {
76
91
  }
77
92
  export interface HistoryScope {
78
93
  readonly execution?: WorkloadExecution;
94
+ readonly chat?: typeof ChatProvenance.Type;
79
95
  readonly workflow?: {
80
96
  readonly name: string;
81
97
  readonly subject: string;
@@ -87,5 +103,13 @@ export interface HistoryScope {
87
103
  readonly blobActionKey?: string;
88
104
  readonly createIntent?: string;
89
105
  }
106
+ /** Whether one run of an action keeps verified attribution beside its history rows. */
107
+ export declare function attributed(scope: HistoryScope): boolean;
108
+ /**
109
+ * `INSERT` of the action's attribution, once per run: the verified pipeline execution, or the chat
110
+ * the app's agent acted in. Only the columns that hold a value are named, so a database migrated
111
+ * before `chat` keeps taking a pipeline's attribution.
112
+ */
113
+ export declare function insertAttribution(scope: HistoryScope, params: Params): string;
90
114
  /** `INSERT` of one history row; `at` is the transaction's time, shared by the whole action. */
91
115
  export declare function insertHistory(scope: HistoryScope, write: HistoryWrite, params: Params): string;
@@ -1,7 +1,7 @@
1
1
  import { Schema } from "effect";
2
2
  import { canonicalJson } from "../manifest.js";
3
3
  import { WorkloadExecution } from "./workload.js";
4
- import { quoteIdentifier } from "../migrate/storage.js";
4
+ import { ACTION_ATTRIBUTION_TABLE, quoteIdentifier } from "../migrate/storage.js";
5
5
  import { uuidv7 } from "./ids.js";
6
6
  export const EditKind = Schema.Literals(["create", "update", "delete", "link", "unlink"]);
7
7
  /** One property's change. A relationship's change carries record ids. */
@@ -20,9 +20,20 @@ export const Edit = Schema.Struct({
20
20
  kind: EditKind,
21
21
  changes: Changes,
22
22
  });
23
+ /**
24
+ * The chat the app's agent acted in when it ran the action, and its session there, as the chat
25
+ * archive names them: a guest's chat is `web` and `guest:<id>`.
26
+ */
27
+ export const ChatProvenance = Schema.Struct({
28
+ provider: Schema.String,
29
+ chatId: Schema.String,
30
+ sessionId: Schema.optionalKey(Schema.String),
31
+ });
23
32
  /** A row of `<entity>_history`. */
24
33
  export const HistoryEntry = Schema.Struct({
25
34
  execution: Schema.optionalKey(WorkloadExecution),
35
+ /** The chat the app's agent ran the action from, for anyone it acted for, a guest included. */
36
+ chat: Schema.optionalKey(ChatProvenance),
26
37
  id: Schema.String,
27
38
  recordId: Schema.String,
28
39
  /** The qualified action, for example `lead.changeStatus`. */
@@ -58,6 +69,29 @@ export function diffRecords(entity, before, after) {
58
69
  }
59
70
  return changes;
60
71
  }
72
+ /** Whether one run of an action keeps verified attribution beside its history rows. */
73
+ export function attributed(scope) {
74
+ return scope.execution !== undefined || scope.chat !== undefined;
75
+ }
76
+ /**
77
+ * `INSERT` of the action's attribution, once per run: the verified pipeline execution, or the chat
78
+ * the app's agent acted in. Only the columns that hold a value are named, so a database migrated
79
+ * before `chat` keeps taking a pipeline's attribution.
80
+ */
81
+ export function insertAttribution(scope, params) {
82
+ const columns = ['"action_id"'];
83
+ const values = [params.add(scope.actionId, "uuid")];
84
+ if (scope.execution !== undefined) {
85
+ columns.push('"execution"');
86
+ values.push(params.add(JSON.stringify(scope.execution), "jsonb"));
87
+ }
88
+ if (scope.chat !== undefined) {
89
+ columns.push('"chat"');
90
+ values.push(params.add(JSON.stringify(scope.chat), "jsonb"));
91
+ }
92
+ return (`INSERT INTO "${ACTION_ATTRIBUTION_TABLE}" (${columns.join(", ")}) ` +
93
+ `VALUES (${values.join(", ")}) ON CONFLICT DO NOTHING`);
94
+ }
61
95
  /** `INSERT` of one history row; `at` is the transaction's time, shared by the whole action. */
62
96
  export function insertHistory(scope, write, params) {
63
97
  const table = quoteIdentifier(write.entity.historyTable);
@@ -352,6 +352,9 @@ export function runAction(ontology, request) {
352
352
  // A guest is no user: what they create or change was created and updated by nobody.
353
353
  principalId: request.principal.kind === "guest" ? null : request.principal.id,
354
354
  ...(request.principal.execution ? { execution: request.principal.execution } : {}),
355
+ // The chat the app's agent acted in: history keeps it, so a record, a guest's too,
356
+ // leads back to the chat it came from.
357
+ ...(request.principal.chat ? { chat: request.principal.chat } : {}),
355
358
  ...(request.principal.workflow ? { workflow: request.principal.workflow } : {}),
356
359
  ...(key ? { blobActionKey: key } : {}),
357
360
  ...(request.branchId ? { branchId: request.branchId } : {}),
@@ -270,6 +270,12 @@ export type MemberKey = {
270
270
  };
271
271
  /** Every member, signed in or not, by email. */
272
272
  export declare function listMembers(): Effect.Effect<ReadonlyArray<MemberSummary>, never, SqlClient.SqlClient>;
273
+ /**
274
+ * Whether an address can receive the app's sign-in code: a user holds it who has signed in with
275
+ * Neon Auth before, as `checkSignIn` answers `code`. Neon Auth sends codes only to its existing
276
+ * accounts; anyone else signs in with a link.
277
+ */
278
+ export declare function signsInWithCode(sql: SqlClient.SqlClient, email: string): Effect.Effect<boolean>;
273
279
  /**
274
280
  * Whether a person may sign in with this address, and how; it reads and changes nothing else.
275
281
  * Under `invited`, an active member who signed in with Neon Auth before gets `code`, an active
@@ -1143,6 +1143,30 @@ const SignInRow = Schema.Struct({
1143
1143
  neon_auth: Schema.Boolean,
1144
1144
  });
1145
1145
  const decodeSignInRow = Schema.decodeUnknownSync(SignInRow);
1146
+ /**
1147
+ * Whether the user `"u"` has a Neon Auth account, which receives sign-in codes: their live email
1148
+ * sign-in identity. `$2` is the Neon Auth provider.
1149
+ */
1150
+ function neonAuthAccountSql(sql) {
1151
+ return Effect.map(userIdentitiesAvailable(sql), (available) => available
1152
+ ? `EXISTS (SELECT 1 FROM "${USER_IDENTITY_TABLE}" AS "i" WHERE "i"."user_id" = "u"."id" ` +
1153
+ `AND "i"."provider" = $2 AND "i"."origin"::text IN ${SIGN_IN_ORIGIN_SQL} ` +
1154
+ `AND "i"."revoked_at" IS NULL)`
1155
+ : `("u"."identity_provider" = $2 AND "u"."identity_subject" IS NOT NULL)`);
1156
+ }
1157
+ /**
1158
+ * Whether an address can receive the app's sign-in code: a user holds it who has signed in with
1159
+ * Neon Auth before, as `checkSignIn` answers `code`. Neon Auth sends codes only to its existing
1160
+ * accounts; anyone else signs in with a link.
1161
+ */
1162
+ export function signsInWithCode(sql, email) {
1163
+ return Effect.gen(function* () {
1164
+ const neonAuth = yield* neonAuthAccountSql(sql);
1165
+ const [row] = yield* sql.unsafe(`SELECT ${neonAuth} AS "code" FROM "${USER_TABLE}" AS "u" ` +
1166
+ `WHERE "u"."kind" = 'member' AND "u"."email" = $1 LIMIT 1`, [normalizeEmail(email), NEON_AUTH_PROVIDER]);
1167
+ return row?.code === true;
1168
+ }).pipe(Effect.orDie);
1169
+ }
1146
1170
  /**
1147
1171
  * Whether a person may sign in with this address, and how; it reads and changes nothing else.
1148
1172
  * Under `invited`, an active member who signed in with Neon Auth before gets `code`, an active
@@ -1156,12 +1180,7 @@ export function checkSignIn(ontology, email) {
1156
1180
  return { allowed: false };
1157
1181
  }
1158
1182
  const sql = yield* SqlClient.SqlClient;
1159
- // Neon Auth accounts receive sign-in codes: the member's live email sign-in identity.
1160
- const neonAuth = (yield* userIdentitiesAvailable(sql))
1161
- ? `EXISTS (SELECT 1 FROM "${USER_IDENTITY_TABLE}" AS "i" WHERE "i"."user_id" = "u"."id" ` +
1162
- `AND "i"."provider" = $2 AND "i"."origin"::text IN ${SIGN_IN_ORIGIN_SQL} ` +
1163
- `AND "i"."revoked_at" IS NULL)`
1164
- : `("u"."identity_provider" = $2 AND "u"."identity_subject" IS NOT NULL)`;
1183
+ const neonAuth = yield* neonAuthAccountSql(sql);
1165
1184
  const [row] = yield* sql.unsafe(`SELECT "u"."id"::text AS "id", "u"."active" AS "active", ${neonAuth} AS "neon_auth" ` +
1166
1185
  `FROM "${USER_TABLE}" AS "u" WHERE "u"."kind" = 'member' AND "u"."email" = $1 LIMIT 1`, [address, NEON_AUTH_PROVIDER]);
1167
1186
  // Anyone may sign in where email is open to sign-up, so the answer reveals nothing.
@@ -283,14 +283,20 @@ export function readHistory(context, entity, input) {
283
283
  conditions.push(`("h"."at" < ${at} OR ("h"."at" = ${at} AND "h"."id" < ${params.add(cursor[1], "uuid")}))`);
284
284
  }
285
285
  const presenceParams = new Params();
286
- const [presence] = yield* context.run("SELECT to_regclass('_ontology_action_attribution') IS NOT NULL AS present", presenceParams);
286
+ // @legacy ontology.pre-upgrade-database-tolerance
287
+ // A database migrated before an attribution table, or before its `chat`, reads without them.
288
+ const [presence] = yield* context.run("SELECT to_regclass('_ontology_action_attribution') IS NOT NULL AS present, " +
289
+ "EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() " +
290
+ "AND table_name = '_ontology_action_attribution' AND column_name = 'chat') AS chat", presenceParams);
287
291
  const attribution = presence?.present === true;
292
+ const chat = attribution && presence?.chat === true;
288
293
  const rows = yield* context.run(`SELECT "h"."id"::text AS "id", "h"."record_id"::text AS "recordId", "h"."action" AS "action", ` +
289
294
  `"h"."action_id"::text AS "actionId", "h"."kind" AS "kind", ` +
290
295
  `"h"."principal_id"::text AS "principalId", ` +
291
296
  `to_char("h"."at" AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "at", ` +
292
297
  `"h"."changes"::text AS "changes" ` +
293
298
  (attribution ? `, "a"."execution" AS "execution" ` : "") +
299
+ (chat ? `, "a"."chat" AS "chat" ` : "") +
294
300
  `FROM ${quoteIdentifier(entity.historyTable)} AS "h" ` +
295
301
  (attribution
296
302
  ? `LEFT JOIN "_ontology_action_attribution" AS "a" ON "a"."action_id" = "h"."action_id" `
@@ -299,8 +305,9 @@ export function readHistory(context, entity, input) {
299
305
  `ORDER BY "h"."at" DESC, "h"."id" DESC ` +
300
306
  `LIMIT ${params.add(limit + 1, "bigint")}`, params);
301
307
  const items = rows.slice(0, limit).map((row) => Schema.decodeUnknownSync(HistoryEntry)({
302
- ...Object.fromEntries(Object.entries(row).filter(([key, value]) => key !== "execution" || value != null)),
308
+ ...Object.fromEntries(Object.entries(row).filter(([key, value]) => (key !== "execution" && key !== "chat") || value != null)),
303
309
  ...(row.execution == null ? {} : { execution: row.execution }),
310
+ ...(row.chat == null ? {} : { chat: row.chat }),
304
311
  at: canonicalInstant(String(row.at)),
305
312
  changes: JSON.parse(String(row.changes)),
306
313
  }));
@@ -31,6 +31,16 @@ export declare function neonSignInLinks(config: {
31
31
  readonly origin: string;
32
32
  readonly fetch?: typeof fetch;
33
33
  }): SignInLinks["Service"];
34
+ /**
35
+ * Asks the app's Neon Auth for a sign-in link to `callbackUrl`, on the app's production origin,
36
+ * for `email`; the platform's email webhook sends it, as for every sign-in link. A link creates
37
+ * the Neon Auth account of an address that has none. Undefined once Neon Auth issued it.
38
+ */
39
+ export declare function requestNeonSignInLink(config: {
40
+ readonly baseUrl: string;
41
+ readonly origin: string;
42
+ readonly fetch?: typeof fetch;
43
+ }, email: string, callbackUrl: string): Promise<SignInLinkFailure | undefined>;
34
44
  /**
35
45
  * Requests the links of the emails an action queued, after its commit, in the same request, and
36
46
  * records each outcome on its row; rows older than {@link SIGN_IN_EMAIL_RETENTION_DAYS} days go.
@@ -29,34 +29,35 @@ export function signInEmailCallback(origin, email) {
29
29
  * no magic links yet; it is reconciled for them.
30
30
  */
31
31
  export function neonSignInLinks(config) {
32
- const fetcher = config.fetch ?? fetch;
33
- const endpoint = `${config.baseUrl.replace(/\/+$/, "")}/sign-in/magic-link`;
34
32
  return {
35
- request: (email) => Effect.promise(async () => {
36
- let response;
37
- try {
38
- response = await fetcher(endpoint, {
39
- method: "POST",
40
- redirect: "error",
41
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
42
- headers: { "content-type": "application/json", origin: config.origin },
43
- body: JSON.stringify({
44
- email: email.email,
45
- callbackURL: signInEmailCallback(config.origin, email),
46
- }),
47
- });
48
- }
49
- catch {
50
- return "unreachable";
51
- }
52
- void response.body?.cancel().catch(() => undefined);
53
- if (response.ok) {
54
- return undefined;
55
- }
56
- return response.status === 404 ? "disabled" : "refused";
57
- }),
33
+ request: (email) => Effect.promise(() => requestNeonSignInLink(config, email.email, signInEmailCallback(config.origin, email))),
58
34
  };
59
35
  }
36
+ /**
37
+ * Asks the app's Neon Auth for a sign-in link to `callbackUrl`, on the app's production origin,
38
+ * for `email`; the platform's email webhook sends it, as for every sign-in link. A link creates
39
+ * the Neon Auth account of an address that has none. Undefined once Neon Auth issued it.
40
+ */
41
+ export async function requestNeonSignInLink(config, email, callbackUrl) {
42
+ let response;
43
+ try {
44
+ response = await (config.fetch ?? fetch)(`${config.baseUrl.replace(/\/+$/, "")}/sign-in/magic-link`, {
45
+ method: "POST",
46
+ redirect: "error",
47
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
48
+ headers: { "content-type": "application/json", origin: config.origin },
49
+ body: JSON.stringify({ email, callbackURL: callbackUrl }),
50
+ });
51
+ }
52
+ catch {
53
+ return "unreachable";
54
+ }
55
+ void response.body?.cancel().catch(() => undefined);
56
+ if (response.ok) {
57
+ return undefined;
58
+ }
59
+ return response.status === 404 ? "disabled" : "refused";
60
+ }
60
61
  /**
61
62
  * Requests the links of the emails an action queued, after its commit, in the same request, and
62
63
  * records each outcome on its row; rows older than {@link SIGN_IN_EMAIL_RETENTION_DAYS} days go.
@@ -8,7 +8,7 @@ import type { OntologyRuntimeService, StoredRecord, StoredValues } from "../runt
8
8
  import { type AttachIdentityInput } from "./channel-identity-admin.js";
9
9
  import { type BatchOperation } from "./batch.js";
10
10
  import { InvalidQuery, UnknownRole } from "./errors.js";
11
- import type { Edit, HistoryEntry, HistoryScope } from "./history.js";
11
+ import { type Edit, type HistoryEntry, type HistoryScope } from "./history.js";
12
12
  import { type QueuedSignInEmail } from "./member-writes.js";
13
13
  import { type EntityModel } from "./model.js";
14
14
  import { type RecordSnapshot, type WriteGuard } from "./writes.js";
@@ -10,6 +10,7 @@ import { ACTION_MAX_BATCH_ROWS, BATCH_MAX_BYTES, BATCH_MAX_ROWS, batchInputBytes
10
10
  import { logBatchConflict } from "./batch-diagnostics.js";
11
11
  import { runMetricQuery } from "./metric-query.js";
12
12
  import { InvalidQuery, UndeclaredWrite, UnknownRole, WriteOutsideAction } from "./errors.js";
13
+ import { attributed } from "./history.js";
13
14
  import { grantMemberRoles, inviteMember, queueSignInEmail, revokeMemberRoles, setMemberActive, } from "./member-writes.js";
14
15
  import { entityModel, ontologyModel } from "./model.js";
15
16
  import { loadRecord, notFound, readHistory, relatedCondition, runQuery, validateQuery, } from "./reads.js";
@@ -167,7 +168,7 @@ export function makeOntologyRuntime(ontology, sql, scope) {
167
168
  for (const snapshot of snapshots ?? []) {
168
169
  scope.onSnapshot?.(snapshot);
169
170
  }
170
- if (edits.length > 0 && scope.execution !== undefined) {
171
+ if (edits.length > 0 && attributed(scope)) {
171
172
  attributionInitialized = true;
172
173
  }
173
174
  return result;
@@ -252,7 +253,7 @@ export function makeOntologyRuntime(ontology, sql, scope) {
252
253
  for (const snapshot of snapshots ?? []) {
253
254
  scope.onSnapshot?.(snapshot);
254
255
  }
255
- if (edits.length > 0 && scope.execution !== undefined) {
256
+ if (edits.length > 0 && attributed(scope)) {
256
257
  attributionInitialized = true;
257
258
  }
258
259
  return result;
@@ -1,12 +1,12 @@
1
1
  import { Effect } from "effect";
2
2
  import { resolveBlobWrites } from "../storage/writes.js";
3
3
  import { Conflict, ScopeViolated } from "../errors.js";
4
- import { ACTION_ATTRIBUTION_TABLE, USER_ROLES_TABLE, quoteIdentifier } from "../migrate/storage.js";
4
+ import { USER_ROLES_TABLE, quoteIdentifier } from "../migrate/storage.js";
5
5
  import { canonicalJson } from "../manifest.js";
6
6
  import { User } from "../user.js";
7
7
  import { InvalidValues } from "./errors.js";
8
8
  import { uuidv7 } from "./ids.js";
9
- import { diffRecords, insertHistory, } from "./history.js";
9
+ import { diffRecords, attributed, insertAttribution, insertHistory, } from "./history.js";
10
10
  import { entityModel } from "./model.js";
11
11
  import { loadRecord, normalizeId, notFound, requireRecords } from "./reads.js";
12
12
  import { bindValue, decodeRecord, prepareWrite, selectList, } from "./records.js";
@@ -51,11 +51,9 @@ export function scopeViolated(entity, check, id, batch) {
51
51
  function recordEdit(context, entity, edit, snapshot) {
52
52
  return Effect.gen(function* () {
53
53
  const params = new Params();
54
- if (context.scope.execution !== undefined) {
54
+ if (attributed(context.scope)) {
55
55
  const attribution = new Params();
56
- yield* context.run(`INSERT INTO "${ACTION_ATTRIBUTION_TABLE}" (action_id, execution) VALUES (` +
57
- `${attribution.add(context.scope.actionId, "uuid")}, ` +
58
- `${attribution.add(JSON.stringify(context.scope.execution), "jsonb")}) ON CONFLICT DO NOTHING`, attribution);
56
+ yield* context.run(insertAttribution(context.scope, attribution), attribution);
59
57
  }
60
58
  yield* context.run(insertHistory(context.scope, { entity, edit }, params), params);
61
59
  context.edits.push(edit);
package/dist/runtime.d.ts CHANGED
@@ -5,9 +5,27 @@ import type { ScopedPermission } from "./permissions.js";
5
5
  import type { Where } from "./query.js";
6
6
  import type { WorkloadExecution } from "./runtime/workload.js";
7
7
  /** Who runs an action: an app member or a service principal, both `user` records. */
8
+ /**
9
+ * The chat the app's agent acted in, as the chat archive names it, and the agent's session there.
10
+ * Only the deployment's own agent runtime reports it; a web chat is checked against the member or
11
+ * guest it acts for.
12
+ */
13
+ export interface ChatProvenance {
14
+ /** The chat's provider: `web`, `telegram`, `slack`, `whatsapp` or `email`. */
15
+ readonly provider: string;
16
+ /** The chat's id there, such as `guest:<id>` or `member:<id>` on the web, or `-100123`. */
17
+ readonly chatId: string;
18
+ /** The agent's session in the chat. */
19
+ readonly sessionId?: string;
20
+ }
8
21
  export interface Principal {
9
22
  /** Present only for a verified managed pipeline worker. */
10
23
  readonly execution?: WorkloadExecution;
24
+ /**
25
+ * Present only when the app's own agent acts for the principal in a chat, a guest's included:
26
+ * the chat and session the request came from. History keeps it with every change it makes.
27
+ */
28
+ readonly chat?: ChatProvenance;
11
29
  /**
12
30
  * Present only for a workflow's user: the workflow's wire name, whose runs it acts in, and its
13
31
  * identity subject, `workflows:<workspace id>:<workflow name>`.
@@ -5,8 +5,7 @@ import { RequestId } from "../errors.js";
5
5
  import type { Principal } from "../../runtime.js";
6
6
  import type { AgentStore, OntologyBackend } from "../runtime-contract.js";
7
7
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
8
- export declare const CHAT_HEADER = "x-segmentstream-agent-chat";
9
- export declare const SESSION_HEADER = "x-segmentstream-agent-session";
8
+ export { CHAT_HEADER, SESSION_HEADER } from "../runtime-identity.js";
10
9
  /** Authenticate the runtime and resolve its member; attachment storage also checks chat access. */
11
10
  export declare function authenticateAgentCaller(input: {
12
11
  readonly request: HttpServerRequest.HttpServerRequest;
@@ -77,6 +76,7 @@ export declare function delegatedAgentMember(request: HttpServerRequest.HttpServ
77
76
  readonly member: {
78
77
  authenticatedVia: string;
79
78
  execution?: import("../../index.js").WorkloadExecution;
79
+ chat?: import("../../runtime.js").ChatProvenance;
80
80
  workflow?: {
81
81
  readonly name: string;
82
82
  readonly subject: string;
@@ -105,6 +105,7 @@ export declare function delegatedAccount(agents: AgentStore, actAs: string, prov
105
105
  member: {
106
106
  authenticatedVia: string;
107
107
  execution?: import("../../index.js").WorkloadExecution;
108
+ chat?: import("../../runtime.js").ChatProvenance;
108
109
  workflow?: {
109
110
  readonly name: string;
110
111
  readonly subject: string;
@@ -4,17 +4,8 @@ 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
6
  import { GUEST_ACT_AS_PREFIX, actingGuestId } from "../../runtime/guests.js";
7
- import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
8
- export const CHAT_HEADER = "x-segmentstream-agent-chat";
9
- export const SESSION_HEADER = "x-segmentstream-agent-session";
10
- /** @legacy agent.conversation-header The chat's header from agents built before it took the name. */
11
- const EARLIER_CHAT_HEADER = "x-segmentstream-agent-conversation";
12
- /**
13
- * `provider:chat id`. An email chat is a Gmail thread and the person's address
14
- * (`email:<thread>:<address>`), so an id may hold an address's `@`, `.` and `+`.
15
- */
16
- const CHAT = /^[a-z][a-z0-9_-]{0,31}:[A-Za-z0-9:_.@+-]{1,320}$/;
17
- const SESSION = /^[A-Za-z0-9:_.-]{1,200}$/;
7
+ 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
+ export { CHAT_HEADER, SESSION_HEADER } from "../runtime-identity.js";
18
9
  /** Authenticate the runtime and resolve its member; attachment storage also checks chat access. */
19
10
  export function authenticateAgentCaller(input) {
20
11
  return Effect.gen(function* () {
@@ -0,0 +1,42 @@
1
+ import type { Redacted } from "effect";
2
+ import type { GuestBotCheck } from "../../sign-in.js";
3
+ import { type WebhookVerification } from "../webhooks.js";
4
+ /**
5
+ * A website's bot check before a guest exists: the website shows the challenge `guest.botCheck`
6
+ * names, and the visitor's browser sends the challenge's token with its request for a guest's agent
7
+ * token. The ontology never holds the challenge's secret key: it is a workspace secret, and
8
+ * SegmentStream's backend checks the token with the provider, as it checks webhook signatures.
9
+ */
10
+ /** The longest challenge token the ontology passes on; providers issue shorter ones. */
11
+ export declare const MAX_BOT_CHECK_TOKEN_LENGTH = 2048;
12
+ /**
13
+ * What the check answered: `valid`, with the hostname of the page the challenge was solved on,
14
+ * `invalid`, `secret_missing` or `unavailable`.
15
+ */
16
+ export type BotCheckVerification = WebhookVerification;
17
+ export interface BotCheckRequest {
18
+ readonly check: GuestBotCheck;
19
+ /** The token the website's challenge gave the visitor. */
20
+ readonly token: string;
21
+ /** The visitor's network address, which the provider compares with the challenge's. */
22
+ readonly remoteIp?: string | undefined;
23
+ /** The deployment's Vercel OIDC token, which proves the workspace application. */
24
+ readonly identityToken: string | undefined;
25
+ readonly requestId: string;
26
+ }
27
+ /** Checks a visitor's challenge token. The service asks SegmentStream's backend by default. */
28
+ export type BotCheckVerifier = (request: BotCheckRequest) => Promise<BotCheckVerification>;
29
+ /**
30
+ * The verifier of a deployed ontology service: `POST
31
+ * /api/internal/v1/workspaces/{id}/secrets/{name}/verify-challenge` on SegmentStream with the
32
+ * request's Vercel OIDC token, admitted only for the secret the deployed ontology's `guest.botCheck`
33
+ * names. Each check carries a new idempotency key, which the provider takes to tell a retried
34
+ * check from a token used twice.
35
+ */
36
+ export declare function deployedBotCheckVerifier(environment: {
37
+ readonly segmentstreamUrl: string;
38
+ readonly workspaceId: string;
39
+ readonly organizationId: string;
40
+ readonly deploymentId?: string | undefined;
41
+ readonly previewCredential?: Redacted.Redacted<string> | undefined;
42
+ }, fetchImpl?: typeof fetch): BotCheckVerifier;
@@ -0,0 +1,32 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { deployedSecretVerifier } from "../webhooks.js";
3
+ /**
4
+ * A website's bot check before a guest exists: the website shows the challenge `guest.botCheck`
5
+ * names, and the visitor's browser sends the challenge's token with its request for a guest's agent
6
+ * token. The ontology never holds the challenge's secret key: it is a workspace secret, and
7
+ * SegmentStream's backend checks the token with the provider, as it checks webhook signatures.
8
+ */
9
+ /** The longest challenge token the ontology passes on; providers issue shorter ones. */
10
+ export const MAX_BOT_CHECK_TOKEN_LENGTH = 2048;
11
+ /**
12
+ * The verifier of a deployed ontology service: `POST
13
+ * /api/internal/v1/workspaces/{id}/secrets/{name}/verify-challenge` on SegmentStream with the
14
+ * request's Vercel OIDC token, admitted only for the secret the deployed ontology's `guest.botCheck`
15
+ * names. Each check carries a new idempotency key, which the provider takes to tell a retried
16
+ * check from a token used twice.
17
+ */
18
+ export function deployedBotCheckVerifier(environment, fetchImpl = fetch) {
19
+ const verify = deployedSecretVerifier(environment, "verify-challenge", fetchImpl);
20
+ return (request) => verify({
21
+ secret: request.check.secret,
22
+ identityToken: request.identityToken,
23
+ requestId: request.requestId,
24
+ }, {
25
+ scheme: request.check.scheme,
26
+ token: request.token,
27
+ idempotencyKey: randomUUID(),
28
+ ...(request.remoteIp === undefined || request.remoteIp === ""
29
+ ? {}
30
+ : { remoteIp: request.remoteIp }),
31
+ });
32
+ }