@segmentstream/ontology 0.197.1 → 0.199.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 (68) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/dist/analyze.d.ts +2 -0
  3. package/dist/analyze.js +17 -0
  4. package/dist/bin/check.js +12 -0
  5. package/dist/bin/migrate.js +1 -1
  6. package/dist/connection.d.ts +109 -6
  7. package/dist/connection.js +132 -17
  8. package/dist/diagnostics.d.ts +3 -3
  9. package/dist/diagnostics.js +2 -0
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +1 -1
  12. package/dist/manifest.d.ts +28 -0
  13. package/dist/manifest.js +6 -0
  14. package/dist/migrate/apply.d.ts +7 -1
  15. package/dist/migrate/apply.js +12 -3
  16. package/dist/migrate/model.d.ts +8 -0
  17. package/dist/migrate/plan.js +14 -1
  18. package/dist/owned-workflows.d.ts +10 -0
  19. package/dist/owned-workflows.js +16 -0
  20. package/dist/runtime/agents.js +2 -0
  21. package/dist/runtime/owner-departures.d.ts +35 -0
  22. package/dist/runtime/owner-departures.js +64 -0
  23. package/dist/runtime/pipeline.d.ts +15 -1
  24. package/dist/runtime/pipeline.js +67 -1
  25. package/dist/runtime/principals.d.ts +17 -2
  26. package/dist/runtime/principals.js +33 -2
  27. package/dist/runtime/service-binding.js +17 -3
  28. package/dist/runtime/workflow-starts.d.ts +108 -8
  29. package/dist/runtime/workflow-starts.js +276 -49
  30. package/dist/service/agent/attachments.js +27 -6
  31. package/dist/service/agent/authentication.d.ts +5 -0
  32. package/dist/service/agent/authentication.js +1 -1
  33. package/dist/service/agent/protocol.d.ts +4 -0
  34. package/dist/service/agent/protocol.js +4 -0
  35. package/dist/service/agent/server.js +7 -4
  36. package/dist/service/agent/task-caller.d.ts +4 -2
  37. package/dist/service/agent/task-caller.js +4 -2
  38. package/dist/service/authentication.d.ts +7 -0
  39. package/dist/service/authentication.js +12 -0
  40. package/dist/service/channel/telegram-pairing.d.ts +9 -0
  41. package/dist/service/channel/telegram-pairing.js +114 -0
  42. package/dist/service/chat/envelope.d.ts +7 -0
  43. package/dist/service/chat/envelope.js +15 -0
  44. package/dist/service/chat/providers/telegram.d.ts +2 -0
  45. package/dist/service/chat/providers/telegram.js +1 -1
  46. package/dist/service/config.d.ts +6 -0
  47. package/dist/service/connections.d.ts +17 -2
  48. package/dist/service/connections.js +21 -1
  49. package/dist/service/errors.js +27 -1
  50. package/dist/service/member-files.js +6 -0
  51. package/dist/service/operations.d.ts +8 -0
  52. package/dist/service/operations.js +11 -4
  53. package/dist/service/owned-connections.d.ts +80 -0
  54. package/dist/service/owned-connections.js +488 -0
  55. package/dist/service/runtime-contract.d.ts +34 -0
  56. package/dist/service/schemas.d.ts +2 -0
  57. package/dist/service/service.js +26 -2
  58. package/dist/service/workflow-errors.d.ts +12 -1
  59. package/dist/service/workflow-errors.js +15 -2
  60. package/dist/service/workflows.d.ts +22 -0
  61. package/dist/service/workflows.js +358 -48
  62. package/dist/start-recovery-contract.d.ts +17 -1
  63. package/dist/start-recovery-contract.js +11 -1
  64. package/dist/start-recovery.js +4 -1
  65. package/dist/storage/tables.d.ts +15 -0
  66. package/dist/storage/tables.js +21 -0
  67. package/dist/workflow.d.ts +20 -2
  68. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -12,8 +12,8 @@ export { action, isAction } from "./action.js";
12
12
  export { ActionConfirmation, ConfirmationFact } from "./confirmation.js";
13
13
  export type { ConfirmContext } from "./confirmation.js";
14
14
  export type { Action, ActionConfig, ActionConfigWithConnections, ActionContext, ActionIdentity, ActionEncodedInput, ActionHints, ActionInput, ActionResult, ActionWriteTarget, Actions, AnyAction, PrepareContext, PrepareError, } from "./action.js";
15
- export { CONNECTION_ERROR_REASONS, CONNECTION_KEY, CONNECTION_METHODS, connection, ConnectionError, Connections, ConnectionTransport, isConnection, MAXIMUM_CONNECTION_BODY_BYTES, MAXIMUM_CONNECTION_FILE_BYTES, MAXIMUM_CONNECTION_RESPONSE_BYTES, } from "./connection.js";
16
- export type { AnyConnectionHandle, Connection, ConnectionCall, ConnectionClient, ConnectionErrorReason, ConnectionHandle, ConnectionHeaders, ConnectionMethod, ConnectionOptions, ConnectionReply, ConnectionRequest, ConnectionRequestOptions, ConnectionResponse, ConnectionStreamReply, ConnectionStreamResponse, ConnectionsOf, ConnectionStub, StubRequest, StubResponse, } from "./connection.js";
15
+ export { CONNECTION_ERROR_REASONS, CONNECTION_KEY, CONNECTION_METHODS, connection, ConnectionError, Connections, ConnectionTransport, isConnection, MAXIMUM_CONNECTION_BODY_BYTES, MAXIMUM_CONNECTION_FILE_BYTES, MAXIMUM_CONNECTION_RESPONSE_BYTES, OWNED_CONNECTIONS_PAGE, ownedConnectionLink, } from "./connection.js";
16
+ export type { AnyConnectionHandle, Connection, ConnectionCall, ConnectionCallKind, ConnectionClient, ConnectionErrorReason, ConnectionHandle, ConnectionHeaders, ConnectionMethod, ConnectionOptions, ConnectionReply, ConnectionRequest, ConnectionRequestOptions, ConnectionResponse, ConnectionStreamReply, ConnectionStreamResponse, ConnectionsOf, ConnectionStub, StubRequest, StubResponse, StubSelection, TestConnectionsOptions, } from "./connection.js";
17
17
  export type { ChatChannelConfig, ChatConfig, ChatFilesConfig, DiscoveryOptions, EntityPermissions, JsonSchemaObject, MemberOptions, OntologyConfig, ResolvedAction, ResolvedConnection, ResolvedEntity, ResolvedIndex, ResolvedProperty, ResolvedRelationship, } from "./analyze.js";
18
18
  export { Diagnostic, DIAGNOSTIC_CODES, formatDiagnostics, InvalidOntology } from "./diagnostics.js";
19
19
  export type { DiagnosticCode } from "./diagnostics.js";
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ export { METRIC_CONDITION_OPERATORS } from "./metric-filters.js";
7
7
  export * from "./legacy.js";
8
8
  export { action, isAction } from "./action.js";
9
9
  export { ActionConfirmation, ConfirmationFact } from "./confirmation.js";
10
- export { CONNECTION_ERROR_REASONS, CONNECTION_KEY, CONNECTION_METHODS, connection, ConnectionError, Connections, ConnectionTransport, isConnection, MAXIMUM_CONNECTION_BODY_BYTES, MAXIMUM_CONNECTION_FILE_BYTES, MAXIMUM_CONNECTION_RESPONSE_BYTES, } from "./connection.js";
10
+ export { CONNECTION_ERROR_REASONS, CONNECTION_KEY, CONNECTION_METHODS, connection, ConnectionError, Connections, ConnectionTransport, isConnection, MAXIMUM_CONNECTION_BODY_BYTES, MAXIMUM_CONNECTION_FILE_BYTES, MAXIMUM_CONNECTION_RESPONSE_BYTES, OWNED_CONNECTIONS_PAGE, ownedConnectionLink, } from "./connection.js";
11
11
  export { Diagnostic, DIAGNOSTIC_CODES, formatDiagnostics, InvalidOntology } from "./diagnostics.js";
12
12
  export { entity, isEntity } from "./entity.js";
13
13
  export { isToolset, MCP_TOOL_NAME, TOOLSET_LOCK_VERSION, toolset, ToolsetLock, ToolsetLockTool, } from "./toolset.js";
@@ -799,6 +799,11 @@ export declare const ConnectionManifest: Schema.Struct<{
799
799
  readonly description: Schema.String;
800
800
  /** Written only when the ontology sends data out through the connection. */
801
801
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
802
+ /**
803
+ * Written only for an owned connection, whose every user connects their own account. backend-next
804
+ * takes ownership from the connections manifest and checks that this agrees with it.
805
+ */
806
+ readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
802
807
  }>;
803
808
  export type ConnectionManifest = typeof ConnectionManifest.Type;
804
809
  /**
@@ -1336,6 +1341,11 @@ export declare const OntologyManifestWire: Schema.encodeKeys<Schema.Struct<{
1336
1341
  readonly description: Schema.String;
1337
1342
  /** Written only when the ontology sends data out through the connection. */
1338
1343
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
1344
+ /**
1345
+ * Written only for an owned connection, whose every user connects their own account. backend-next
1346
+ * takes ownership from the connections manifest and checks that this agrees with it.
1347
+ */
1348
+ readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
1339
1349
  }>>>;
1340
1350
  /**
1341
1351
  * The agent's channels whose chats the built-in exact chat post delivers to, each through its
@@ -1828,6 +1838,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1828
1838
  readonly connections?: readonly {
1829
1839
  readonly description: string;
1830
1840
  readonly key: string;
1841
+ readonly owner?: "user" | undefined;
1831
1842
  readonly delivers?: true | undefined;
1832
1843
  }[] | undefined;
1833
1844
  readonly metrics?: readonly {
@@ -2212,6 +2223,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2212
2223
  readonly connections?: readonly {
2213
2224
  readonly description: string;
2214
2225
  readonly key: string;
2226
+ readonly owner?: "user" | undefined;
2215
2227
  readonly delivers?: true | undefined;
2216
2228
  }[] | undefined;
2217
2229
  readonly metrics?: readonly {
@@ -2596,6 +2608,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2596
2608
  readonly connections?: readonly {
2597
2609
  readonly description: string;
2598
2610
  readonly key: string;
2611
+ readonly owner?: "user" | undefined;
2599
2612
  readonly delivers?: true | undefined;
2600
2613
  }[] | undefined;
2601
2614
  readonly metrics?: readonly {
@@ -2980,6 +2993,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2980
2993
  readonly connections?: readonly {
2981
2994
  readonly description: string;
2982
2995
  readonly key: string;
2996
+ readonly owner?: "user" | undefined;
2983
2997
  readonly delivers?: true | undefined;
2984
2998
  }[] | undefined;
2985
2999
  readonly metrics?: readonly {
@@ -3416,6 +3430,11 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3416
3430
  readonly description: Schema.String;
3417
3431
  /** Written only when the ontology sends data out through the connection. */
3418
3432
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
3433
+ /**
3434
+ * Written only for an owned connection, whose every user connects their own account. backend-next
3435
+ * takes ownership from the connections manifest and checks that this agrees with it.
3436
+ */
3437
+ readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
3419
3438
  }>>>;
3420
3439
  /**
3421
3440
  * The agent's channels whose chats the built-in exact chat post delivers to, each through its
@@ -3945,6 +3964,11 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3945
3964
  readonly description: Schema.String;
3946
3965
  /** Written only when the ontology sends data out through the connection. */
3947
3966
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
3967
+ /**
3968
+ * Written only for an owned connection, whose every user connects their own account. backend-next
3969
+ * takes ownership from the connections manifest and checks that this agrees with it.
3970
+ */
3971
+ readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
3948
3972
  }>>>;
3949
3973
  /**
3950
3974
  * The agent's channels whose chats the built-in exact chat post delivers to, each through its
@@ -4429,6 +4453,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
4429
4453
  readonly connections?: readonly {
4430
4454
  readonly description: string;
4431
4455
  readonly key: string;
4456
+ readonly owner?: "user" | undefined;
4432
4457
  readonly delivers?: true | undefined;
4433
4458
  }[] | undefined;
4434
4459
  readonly metrics?: readonly {
@@ -4813,6 +4838,7 @@ export declare const OntologyManifest: Schema.declareConstructor<{
4813
4838
  readonly connections?: readonly {
4814
4839
  readonly description: string;
4815
4840
  readonly key: string;
4841
+ readonly owner?: "user" | undefined;
4816
4842
  readonly delivers?: true | undefined;
4817
4843
  }[] | undefined;
4818
4844
  readonly metrics?: readonly {
@@ -5203,6 +5229,7 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
5203
5229
  readonly connections?: readonly {
5204
5230
  readonly description: string;
5205
5231
  readonly key: string;
5232
+ readonly owner?: "user" | undefined;
5206
5233
  readonly delivers?: true | undefined;
5207
5234
  }[] | undefined;
5208
5235
  readonly metrics?: readonly {
@@ -5587,6 +5614,7 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
5587
5614
  readonly connections?: readonly {
5588
5615
  readonly description: string;
5589
5616
  readonly key: string;
5617
+ readonly owner?: "user" | undefined;
5590
5618
  readonly delivers?: true | undefined;
5591
5619
  }[] | undefined;
5592
5620
  readonly metrics?: readonly {
package/dist/manifest.js CHANGED
@@ -491,6 +491,11 @@ export const ConnectionManifest = Schema.Struct({
491
491
  description: Schema.String,
492
492
  /** Written only when the ontology sends data out through the connection. */
493
493
  delivers: Schema.optionalKey(Schema.Literal(true)),
494
+ /**
495
+ * Written only for an owned connection, whose every user connects their own account. backend-next
496
+ * takes ownership from the connections manifest and checks that this agrees with it.
497
+ */
498
+ owner: Schema.optionalKey(Schema.Literal("user")),
494
499
  });
495
500
  /**
496
501
  * Who may become a member by signing in: `invited` or `open` as this SDK writes it. The policy is
@@ -1257,6 +1262,7 @@ export function buildManifest(input) {
1257
1262
  key: candidate.key,
1258
1263
  description: candidate.description,
1259
1264
  ...(candidate.delivers ? { delivers: true } : {}),
1265
+ ...(candidate.owner === "user" ? { owner: "user" } : {}),
1260
1266
  })),
1261
1267
  }
1262
1268
  : {}),
@@ -93,8 +93,14 @@ export declare const RUNTIME_TABLES: ReadonlyArray<string>;
93
93
  * {@link ATTACHMENT_SOURCES} or that lacks the view of its earlier name, which the idempotent
94
94
  * attribution, API key and attachment DDL add and widen. A table still named
95
95
  * {@link LEGACY_ATTACHMENTS_TABLE} is reported under that name, so that the plan renames it.
96
+ * {@link WORKFLOW_START_OWNERS}, which names no table, is reported when `_workflow_starts` has the
97
+ * run owner columns, which the plan adds for an ontology that declares an owned workflow. Only for
98
+ * a `target` that declares one does the query look for them; every other ontology's is unchanged.
96
99
  */
97
- export declare const readRuntimeTables: (input: CatalogInput) => Effect.Effect<ReadonlySet<string>, SqlError>;
100
+ export declare const readRuntimeTables: (input: CatalogInput & {
101
+ /** The ontology being migrated to, whose owned workflows need the run owner columns. */
102
+ readonly target?: Pick<OntologyManifest, "connections" | "workflows"> | undefined;
103
+ }) => Effect.Effect<ReadonlySet<string>, SqlError>;
98
104
  /** Only valid, complete covering indexes satisfy the upgrade; failed builds are retried. */
99
105
  export declare const readHistoryActivityIndexes: (input: CatalogInput) => Effect.Effect<ReadonlySet<string>, SqlError>;
100
106
  export declare const migrate: (input: MigrateInput) => Effect.Effect<{
@@ -7,6 +7,7 @@ import { canonicalJson, decodeManifestDocument, encodeManifest, manifestHash, }
7
7
  import { CatalogInvalid, CatalogMismatch, MigrationFailed, MigrationRefused } from "./errors.js";
8
8
  import { isNoopMigration, NO_RETAINED_STORAGE, RetainedStorage, retainedStorageJson, } from "./model.js";
9
9
  import { planMigration } from "./plan.js";
10
+ import { declaresOwnedWorkflow } from "../owned-workflows.js";
10
11
  import { REPLICATION_DDL, REPLICATION_SCHEMA_VERSION, replicationEntityDdl, } from "../replication/schema.js";
11
12
  import { lockReplicationLifecycle, lockReplicationSchema } from "../replication/transaction.js";
12
13
  import { replicatesRecords } from "../replicated-entities.js";
@@ -15,7 +16,7 @@ import { randomUUID } from "node:crypto";
15
16
  import { recordWorkflowCatalog } from "../runtime/workflow-admission.js";
16
17
  import { prepareReplicationEvolution, dropsServingReplicationStorage, refreshReplicationProjection, retainReplicationHistory, renameReplicationHistory, } from "../replication/evolution.js";
17
18
  import { migratedReplicationFills } from "../replication/migrate.js";
18
- import { AGENT_TASKS_TABLE, ATTACHMENT_SOURCE_CHECK, ATTACHMENT_SOURCES, ATTACHMENTS_TABLE, LEGACY_ATTACHMENTS_TABLE, SIGN_IN_EMAILS_TABLE, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
19
+ import { AGENT_TASKS_TABLE, ATTACHMENT_SOURCE_CHECK, ATTACHMENT_SOURCES, ATTACHMENTS_TABLE, LEGACY_ATTACHMENTS_TABLE, SIGN_IN_EMAILS_TABLE, WORKFLOW_START_OWNERS, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
19
20
  import { principalsOntology, reconcileWorkflowUsers } from "../runtime/principals.js";
20
21
  import { FEDERATION_TABLES } from "../runtime/federation-tables.js";
21
22
  import { syncUserIdentities, USER_IDENTITY_ENTITY_ID } from "../runtime/user-identities.js";
@@ -495,6 +496,9 @@ export const RUNTIME_TABLES = [
495
496
  * {@link ATTACHMENT_SOURCES} or that lacks the view of its earlier name, which the idempotent
496
497
  * attribution, API key and attachment DDL add and widen. A table still named
497
498
  * {@link LEGACY_ATTACHMENTS_TABLE} is reported under that name, so that the plan renames it.
499
+ * {@link WORKFLOW_START_OWNERS}, which names no table, is reported when `_workflow_starts` has the
500
+ * run owner columns, which the plan adds for an ontology that declares an owned workflow. Only for
501
+ * a `target` that declares one does the query look for them; every other ontology's is unchanged.
498
502
  */
499
503
  export const readRuntimeTables = (input) => input.sql
500
504
  .unsafe(`SELECT "tablename" AS "name" FROM "pg_catalog"."pg_tables" ` +
@@ -538,7 +542,12 @@ export const readRuntimeTables = (input) => input.sql
538
542
  `WHERE n.nspname = current_schema() AND t.relname = ${quoteLiteral(ATTACHMENTS_TABLE)} ` +
539
543
  `AND c.conname = ${quoteLiteral(ATTACHMENT_SOURCE_CHECK)} ` +
540
544
  ATTACHMENT_SOURCES.map((source) => `AND pg_catalog.pg_get_constraintdef(c.oid) LIKE ${quoteLiteral(`%'${source}'%`)} `).join("") +
541
- `))`)
545
+ `))` +
546
+ (input.target !== undefined && declaresOwnedWorkflow(input.target)
547
+ ? ` UNION ALL SELECT ${quoteLiteral(WORKFLOW_START_OWNERS)} AS "name" WHERE EXISTS (` +
548
+ `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
549
+ `AND table_name = ${quoteLiteral(WORKFLOW_STARTS_TABLE)} AND column_name = 'owner_id')`
550
+ : ""))
542
551
  .pipe(Effect.map((rows) => new Set(rows.map((row) => row.name))));
543
552
  /** Only valid, complete covering indexes satisfy the upgrade; failed builds are retried. */
544
553
  export const readHistoryActivityIndexes = (input) => input.sql
@@ -552,7 +561,7 @@ export const readHistoryActivityIndexes = (input) => input.sql
552
561
  export const migrate = (input) => Effect.gen(function* () {
553
562
  const current = yield* readCatalog({ sql: input.sql });
554
563
  const retained = yield* readRetainedStorage({ sql: input.sql });
555
- const existingTables = yield* readRuntimeTables({ sql: input.sql });
564
+ const existingTables = yield* readRuntimeTables({ sql: input.sql, target: input.target });
556
565
  const existingHistoryActivityIndexes = yield* readHistoryActivityIndexes({ sql: input.sql });
557
566
  const existingStorage = yield* readStorageNames({ sql: input.sql });
558
567
  const plan = planMigration({
@@ -534,6 +534,7 @@ export declare const MigrationPlan: Schema.Struct<{
534
534
  readonly connections?: readonly {
535
535
  readonly description: string;
536
536
  readonly key: string;
537
+ readonly owner?: "user" | undefined;
537
538
  readonly delivers?: true | undefined;
538
539
  }[] | undefined;
539
540
  readonly metrics?: readonly {
@@ -918,6 +919,7 @@ export declare const MigrationPlan: Schema.Struct<{
918
919
  readonly connections?: readonly {
919
920
  readonly description: string;
920
921
  readonly key: string;
922
+ readonly owner?: "user" | undefined;
921
923
  readonly delivers?: true | undefined;
922
924
  }[] | undefined;
923
925
  readonly metrics?: readonly {
@@ -1302,6 +1304,7 @@ export declare const MigrationPlan: Schema.Struct<{
1302
1304
  readonly connections?: readonly {
1303
1305
  readonly description: string;
1304
1306
  readonly key: string;
1307
+ readonly owner?: "user" | undefined;
1305
1308
  readonly delivers?: true | undefined;
1306
1309
  }[] | undefined;
1307
1310
  readonly metrics?: readonly {
@@ -1686,6 +1689,7 @@ export declare const MigrationPlan: Schema.Struct<{
1686
1689
  readonly connections?: readonly {
1687
1690
  readonly description: string;
1688
1691
  readonly key: string;
1692
+ readonly owner?: "user" | undefined;
1689
1693
  readonly delivers?: true | undefined;
1690
1694
  }[] | undefined;
1691
1695
  readonly metrics?: readonly {
@@ -2055,6 +2059,7 @@ export declare const MigrationPlan: Schema.Struct<{
2055
2059
  readonly key: Schema.String;
2056
2060
  readonly description: Schema.String;
2057
2061
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
2062
+ readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
2058
2063
  }>>>;
2059
2064
  readonly chat: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
2060
2065
  readonly telegram: Schema.optionalKey<Schema.Struct<{
@@ -2435,6 +2440,7 @@ export declare const MigrationPlan: Schema.Struct<{
2435
2440
  readonly key: Schema.String;
2436
2441
  readonly description: Schema.String;
2437
2442
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
2443
+ readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
2438
2444
  }>>>;
2439
2445
  readonly chat: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
2440
2446
  readonly telegram: Schema.optionalKey<Schema.Struct<{
@@ -2845,6 +2851,7 @@ export declare const MigrationPlan: Schema.Struct<{
2845
2851
  readonly connections?: readonly {
2846
2852
  readonly description: string;
2847
2853
  readonly key: string;
2854
+ readonly owner?: "user" | undefined;
2848
2855
  readonly delivers?: true | undefined;
2849
2856
  }[] | undefined;
2850
2857
  readonly metrics?: readonly {
@@ -3229,6 +3236,7 @@ export declare const MigrationPlan: Schema.Struct<{
3229
3236
  readonly connections?: readonly {
3230
3237
  readonly description: string;
3231
3238
  readonly key: string;
3239
+ readonly owner?: "user" | undefined;
3232
3240
  readonly delivers?: true | undefined;
3233
3241
  }[] | undefined;
3234
3242
  readonly metrics?: readonly {
@@ -1,7 +1,8 @@
1
1
  import { isValueMatched, } from "../manifest.js";
2
2
  import { FEDERATION_TABLES, FEDERATION_TABLES_DDL } from "../runtime/federation-tables.js";
3
3
  import { EMAIL_LINK_FENCE_SQL, SEGMENTSTREAM_LINK_FENCE_SQL, USER_IDENTITY_ENTITY_ID, USER_IDENTITY_SYNC_SQL, } from "../runtime/user-identity-sql.js";
4
- import { AGENT_TASKS_DDL, AGENT_TASKS_TABLE, SIGN_IN_EMAILS_DDL, SIGN_IN_EMAILS_TABLE, ATTACHMENTS_TABLE, ATTACHMENT_TABLES_DDL, LEGACY_ATTACHMENTS_TABLE, BLOB_TABLES_DDL, WORKFLOW_STARTS_DDL, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
4
+ import { AGENT_TASKS_DDL, AGENT_TASKS_TABLE, SIGN_IN_EMAILS_DDL, SIGN_IN_EMAILS_TABLE, ATTACHMENTS_TABLE, ATTACHMENT_TABLES_DDL, LEGACY_ATTACHMENTS_TABLE, BLOB_TABLES_DDL, WORKFLOW_START_OWNERS, WORKFLOW_START_OWNERS_DDL, WORKFLOW_STARTS_DDL, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
5
+ import { declaresOwnedWorkflow } from "../owned-workflows.js";
5
6
  import { SNAKE_CASE_NAME, isSystemProperty, toSnakeCase } from "../names.js";
6
7
  import { NO_RETAINED_STORAGE, retainedEntityManifest, } from "./model.js";
7
8
  import { ACTION_ATTRIBUTION_TABLE, ACTION_ATTRIBUTION_DDL, AGENT_TABLES, AGENT_TABLES_DDL, API_KEYS_DDL, API_KEYS_TABLE, CATALOG_TABLE_DDL, MAX_IDENTIFIER_LENGTH, OAUTH_TABLES, OAUTH_TABLES_DDL, USER_TABLE, addConstraintStatement, columnName, columnDefinition, constraintDefinition, createEnumStatement, createIndexStatement, createTableStatement, defaultExpression, entityStorage, historyActivityIndex, enumTypeName, isStoredProperty, fieldColumnName, joinTable, propertyCheck, blobForeignKey, propertyColumn, propertyEnum, quoteIdentifier, quoteLiteral, relationshipColumn, relationshipColumnName, RUNTIME_TABLES_DDL, relationshipForeignKey, SYSTEM_COLUMNS, storedEntity, tableName, } from "./storage.js";
@@ -219,6 +220,18 @@ export function planMigration(input) {
219
220
  }
220
221
  planBrowserMethodFences(target, methods, draft);
221
222
  }
223
+ // An owned workflow's starts record their owners. Only such an ontology adds the columns, so
224
+ // that no other workspace's table changes.
225
+ if (declaresOwnedWorkflow(target) &&
226
+ (current === undefined || input.existingTables?.has(WORKFLOW_START_OWNERS) === false)) {
227
+ draft.runtimeTables.push(step({
228
+ kind: "createCatalog",
229
+ classification: "additive",
230
+ description: "Record the owner of each start of a workflow that lists an owned connection, and a " +
231
+ "cron's scheduled minute, on the workflow starts.",
232
+ sql: WORKFLOW_START_OWNERS_DDL,
233
+ }));
234
+ }
222
235
  const storesFiles = storedTargets.some((entity) => entity.properties.some((property) => property.type === "blob"));
223
236
  if (storesFiles &&
224
237
  !current?.entities.some((entity) => entity.properties.some((property) => property.type === "blob"))) {
@@ -0,0 +1,10 @@
1
+ import type { OntologyManifest, WorkflowManifest } from "./manifest.js";
2
+ /**
3
+ * Which workflows are owned (docs/private-connections-spec.md, "Workflows"): a workflow that lists
4
+ * an owned connection, one declared with `owner: "user"`, in its `connections`. Nothing else marks
5
+ * it. Read from the manifest, so `check`, the migration and the service agree.
6
+ */
7
+ /** The owned connections a workflow lists, in its order; empty for a workflow that is not owned. */
8
+ export declare function ownedConnectionKeys(manifest: Pick<OntologyManifest, "connections">, workflow: Pick<WorkflowManifest, "connections">): ReadonlyArray<string>;
9
+ /** Whether the ontology declares an owned workflow, so its starts record their owners. */
10
+ export declare function declaresOwnedWorkflow(manifest: Pick<OntologyManifest, "connections" | "workflows">): boolean;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Which workflows are owned (docs/private-connections-spec.md, "Workflows"): a workflow that lists
3
+ * an owned connection, one declared with `owner: "user"`, in its `connections`. Nothing else marks
4
+ * it. Read from the manifest, so `check`, the migration and the service agree.
5
+ */
6
+ /** The owned connections a workflow lists, in its order; empty for a workflow that is not owned. */
7
+ export function ownedConnectionKeys(manifest, workflow) {
8
+ const owned = new Set((manifest.connections ?? [])
9
+ .filter((connection) => connection.owner === "user")
10
+ .map((connection) => connection.key));
11
+ return owned.size === 0 ? [] : workflow.connections.filter((key) => owned.has(key));
12
+ }
13
+ /** Whether the ontology declares an owned workflow, so its starts record their owners. */
14
+ export function declaresOwnedWorkflow(manifest) {
15
+ return (manifest.workflows ?? []).some((workflow) => ownedConnectionKeys(manifest, workflow).length > 0);
16
+ }
@@ -414,6 +414,8 @@ export function sqlAgentStore(ontology, sql) {
414
414
  return inserted.length > 0;
415
415
  }))
416
416
  .pipe(Effect.orDie),
417
+ telegramLaunchPairing: (id, sender) => rows(`SELECT "code_hash" FROM ${PAIRINGS} WHERE "id" = $1::uuid AND "provider" = 'telegram'
418
+ AND "external_id" = $2 AND "expires_at" > now()`, [id, sender]).pipe(Effect.map(([row]) => (row ? { codeHash: String(row.code_hash) } : undefined))),
417
419
  findPairing: (codeHash) => rows([
418
420
  `SELECT ${PAIRING_COLUMNS}`,
419
421
  `FROM ${PAIRINGS}`,
@@ -0,0 +1,35 @@
1
+ import { Context, Effect } from "effect";
2
+ import type { SqlClient } from "effect/unstable/sql";
3
+ import type { Edit } from "./history.js";
4
+ declare const OwnedConnectionRetirement_base: Context.ServiceClass<OwnedConnectionRetirement, "@segmentstream/ontology/OwnedConnectionRetirement", {
5
+ readonly retire: (ownerId: string) => Effect.Effect<void>;
6
+ }>;
7
+ /**
8
+ * Retires every credential of owned connections (docs/private-connections-spec.md) that a
9
+ * workspace user holds, once they have left: the platform's internal operation, called by the
10
+ * service with the request's deployment identity. It never fails: a failure is logged, the
11
+ * action that made the user leave stands, and the next deployment retires what was missed.
12
+ */
13
+ export declare class OwnedConnectionRetirement extends OwnedConnectionRetirement_base {
14
+ }
15
+ /** What a committed action did, as far as who left: its name, its input and its edits. */
16
+ export interface CommittedChange {
17
+ readonly entity: string;
18
+ readonly action: string;
19
+ readonly input: unknown;
20
+ readonly edits: ReadonlyArray<Edit>;
21
+ }
22
+ /**
23
+ * The users a committed action made leave: deactivated or deleted, as its edits of `user` show,
24
+ * so every way of running an action counts; or left with no live identity by
25
+ * `user_identity.revoke`, whose identity writes are no edits of the action, read from the
26
+ * database after the commit.
27
+ */
28
+ export declare function departedUsers(sql: SqlClient.SqlClient, committed: CommittedChange): Effect.Effect<ReadonlyArray<string>, unknown>;
29
+ /**
30
+ * Retires the owned connection credentials of the users a committed action made leave, through
31
+ * the `OwnedConnectionRetirement` its caller provides; without one, as in a test or a local run,
32
+ * nothing is called. A failure is logged and never fails the action.
33
+ */
34
+ export declare function retireDepartedUsers(sql: SqlClient.SqlClient, committed: CommittedChange, requestId: string): Effect.Effect<void>;
35
+ export {};
@@ -0,0 +1,64 @@
1
+ import { Context, Effect, Option } from "effect";
2
+ import { USER_TABLE } from "../migrate/storage.js";
3
+ import { userIdentitiesAvailable } from "./user-identities.js";
4
+ import { USER_IDENTITY_TABLE } from "./user-identity-sql.js";
5
+ /**
6
+ * Retires every credential of owned connections (docs/private-connections-spec.md) that a
7
+ * workspace user holds, once they have left: the platform's internal operation, called by the
8
+ * service with the request's deployment identity. It never fails: a failure is logged, the
9
+ * action that made the user leave stands, and the next deployment retires what was missed.
10
+ */
11
+ export class OwnedConnectionRetirement extends Context.Service()("@segmentstream/ontology/OwnedConnectionRetirement") {
12
+ }
13
+ /**
14
+ * The users a committed action made leave: deactivated or deleted, as its edits of `user` show,
15
+ * so every way of running an action counts; or left with no live identity by
16
+ * `user_identity.revoke`, whose identity writes are no edits of the action, read from the
17
+ * database after the commit.
18
+ */
19
+ export function departedUsers(sql, committed) {
20
+ return Effect.gen(function* () {
21
+ const departed = new Set();
22
+ for (const edit of committed.edits) {
23
+ const active = edit.changes.active;
24
+ if (edit.entity === USER_TABLE &&
25
+ (edit.kind === "delete" ||
26
+ (active !== undefined && active.before === true && active.after === false))) {
27
+ departed.add(edit.id);
28
+ }
29
+ }
30
+ const revoked = committed.entity === USER_IDENTITY_TABLE &&
31
+ committed.action === "revoke" &&
32
+ typeof committed.input === "object" &&
33
+ committed.input !== null &&
34
+ typeof committed.input.id === "string"
35
+ ? committed.input.id
36
+ : undefined;
37
+ if (revoked !== undefined && (yield* userIdentitiesAvailable(sql))) {
38
+ const users = yield* sql.unsafe(`SELECT "i"."user_id"::text AS "userId" FROM "${USER_IDENTITY_TABLE}" AS "i" ` +
39
+ `WHERE "i"."id"::text = $1 AND "i"."revoked_at" IS NOT NULL AND NOT EXISTS (` +
40
+ `SELECT 1 FROM "${USER_IDENTITY_TABLE}" AS "live" ` +
41
+ `WHERE "live"."user_id" = "i"."user_id" AND "live"."revoked_at" IS NULL)`, [revoked]);
42
+ for (const user of users) {
43
+ departed.add(user.userId);
44
+ }
45
+ }
46
+ return [...departed];
47
+ });
48
+ }
49
+ /**
50
+ * Retires the owned connection credentials of the users a committed action made leave, through
51
+ * the `OwnedConnectionRetirement` its caller provides; without one, as in a test or a local run,
52
+ * nothing is called. A failure is logged and never fails the action.
53
+ */
54
+ export function retireDepartedUsers(sql, committed, requestId) {
55
+ return Effect.gen(function* () {
56
+ const retirement = Option.getOrUndefined(yield* Effect.serviceOption(OwnedConnectionRetirement));
57
+ if (retirement === undefined) {
58
+ return;
59
+ }
60
+ for (const ownerId of yield* departedUsers(sql, committed)) {
61
+ yield* retirement.retire(ownerId);
62
+ }
63
+ }).pipe(Effect.catchCause((cause) => Effect.logWarning("ontology.owned_connections.retire_failed", cause).pipe(Effect.annotateLogs({ requestId }))));
64
+ }
@@ -2,7 +2,8 @@ import type { ActionRuntime } from "../runtime-source.js";
2
2
  import { Duration, Effect, Schema } from "effect";
3
3
  import { SqlClient } from "effect/unstable/sql";
4
4
  import { type AnyAction } from "../action.js";
5
- import { ConnectionError, ConnectionTransport } from "../connection.js";
5
+ import { ConnectionError, ConnectionTransport, type ConnectionOwner } from "../connection.js";
6
+ import { type CallerContext } from "../service/caller-context.js";
6
7
  import { type ActionError } from "../errors.js";
7
8
  import type { Ontology } from "../ontology.js";
8
9
  import { type ActionRequirement } from "../permissions.js";
@@ -155,3 +156,16 @@ export declare function findAction(ontology: Ontology, entityName: string, actio
155
156
  * Database failures are defects.
156
157
  */
157
158
  export declare function runAction<R = never>(ontology: Ontology, request: ActionRequest<R>): Effect.Effect<ActionOutcome, ActionError | ConnectionError | UnknownAction | TriggerInputInvalid | WorkflowRecoveryUnavailable, SqlClient.SqlClient | R>;
159
+ /**
160
+ * Whose credential an owned connection's call in an action uses: the acting user's, when a person
161
+ * called the action, and the call is interactive (docs/private-connections-spec.md, "Using an owned
162
+ * connection"). It fails closed: only a verified credential of that same member selects an owner,
163
+ * their own app session or app token (`member`), their own MCP client (`oauth`), or the app's own
164
+ * agent acting for a verified chat sender (Act-As, a `runtime` caller without `delegatedBy`). Nobody
165
+ * else's call selects one, so an owned call fails there with `owner_required`: an `unverified`
166
+ * caller, an in-process run that provided none, such as a direct `runAction`, a hook or the
167
+ * new-user hook; an API key with delegation, which acts for any member it names; a service, a
168
+ * workflow's user, an agent task, a pipeline worker or a guest. A member principal is active:
169
+ * authentication refuses an inactive user.
170
+ */
171
+ export declare function actingConnectionOwner(principal: Principal, caller: CallerContext): ConnectionOwner | undefined;
@@ -4,7 +4,8 @@ import { SqlClient } from "effect/unstable/sql";
4
4
  import { isSqlError } from "effect/unstable/sql/SqlError";
5
5
  import { ActionIdentity } from "../action.js";
6
6
  import { ActionConfirmation } from "../confirmation.js";
7
- import { ConnectionError, ConnectionTransport, connectionContext } from "../connection.js";
7
+ import { ConnectionError, ConnectionTransport, connectionContext, runTransportOwner, testTransportOwner, } from "../connection.js";
8
+ import { currentCaller } from "../service/caller-context.js";
8
9
  import { Files } from "../files.js";
9
10
  import { FileAccess, unavailableFiles } from "../storage/file-access.js";
10
11
  import { Conflict, PermissionDenied, } from "../errors.js";
@@ -21,6 +22,7 @@ import { OntologyReads, OntologyRuntime } from "../runtime.js";
21
22
  import { UnknownAction, ValidationIssue, WorkflowRecoveryUnavailable, } from "./errors.js";
22
23
  import { generatedActions, writesOnlyThroughActions } from "./generated-actions.js";
23
24
  import { Edit } from "./history.js";
25
+ import { retireDepartedUsers } from "./owner-departures.js";
24
26
  import { canonicalInstant, isRecordId } from "./records.js";
25
27
  import { makeOntologyRuntime } from "./sql-runtime.js";
26
28
  import { AgentFileRecords, resolveFileRecord } from "./files.js";
@@ -341,6 +343,10 @@ export function runAction(ontology, request) {
341
343
  // Triggers are definitions; all mutable runtime and trigger state belongs to one attempt.
342
344
  const triggers = matchingTriggers(ontology, request.entity, request.action, request.principal);
343
345
  const starter = Option.getOrUndefined(yield* Effect.serviceOption(WorkflowStarter));
346
+ const owner = triggers.length === 0
347
+ ? undefined
348
+ : startOwner(request.connections ??
349
+ Option.getOrUndefined(yield* Effect.serviceOption(ConnectionTransport)), request.principal, yield* currentCaller);
344
350
  // Before the transaction: whatever it commits must be swept if this request does not start it.
345
351
  if (triggers.length > 0 && !validateOnly && starter !== undefined) {
346
352
  yield* starter.ensureRecovery({ commitBy: Date.now() + limits.handlerTimeoutMs }).pipe(Effect.mapError((error) => new WorkflowRecoveryUnavailable({
@@ -479,6 +485,7 @@ export function runAction(ontology, request) {
479
485
  actionId,
480
486
  at: canonicalInstant(now.at),
481
487
  principal: request.principal,
488
+ owner,
482
489
  input: decoded.value,
483
490
  result,
484
491
  edits,
@@ -556,6 +563,8 @@ export function runAction(ontology, request) {
556
563
  actionId,
557
564
  }))));
558
565
  }
566
+ // A user the action made leave keeps no credential of an owned connection.
567
+ yield* retireDepartedUsers(sql, committed, requestId);
559
568
  return { result: result ?? null, validation: VALID, edits };
560
569
  });
561
570
  }
@@ -577,6 +586,60 @@ function confirmation(ontology, sql, action, qualified, context) {
577
586
  onExcessProperty: "error",
578
587
  }).pipe(Effect.mapError((issue) => new Error(`${qualified} confirm described an invalid confirmation: ${issue}`)), Effect.orDie)), sqlFailuresAsDefects);
579
588
  }
589
+ /**
590
+ * Whose credential an owned connection's call in an action uses: the acting user's, when a person
591
+ * called the action, and the call is interactive (docs/private-connections-spec.md, "Using an owned
592
+ * connection"). It fails closed: only a verified credential of that same member selects an owner,
593
+ * their own app session or app token (`member`), their own MCP client (`oauth`), or the app's own
594
+ * agent acting for a verified chat sender (Act-As, a `runtime` caller without `delegatedBy`). Nobody
595
+ * else's call selects one, so an owned call fails there with `owner_required`: an `unverified`
596
+ * caller, an in-process run that provided none, such as a direct `runAction`, a hook or the
597
+ * new-user hook; an API key with delegation, which acts for any member it names; a service, a
598
+ * workflow's user, an agent task, a pipeline worker or a guest. A member principal is active:
599
+ * authentication refuses an inactive user.
600
+ */
601
+ export function actingConnectionOwner(principal, caller) {
602
+ const presentMember = caller.kind === "member" ||
603
+ caller.kind === "oauth" ||
604
+ (caller.kind === "runtime" && caller.delegatedBy === undefined);
605
+ return presentMember &&
606
+ caller.subjectId === principal.id &&
607
+ principal.kind === "member" &&
608
+ principal.workflow === undefined &&
609
+ principal.execution === undefined &&
610
+ principal.authenticatedVia !== "workflow" &&
611
+ // `AGENT_TASK_AUTHENTICATION`: a task acts as its workflow's user.
612
+ principal.authenticatedVia !== "agent_task"
613
+ ? { id: principal.id, call: "interactive" }
614
+ : undefined;
615
+ }
616
+ /**
617
+ * Whose credential an action's owned calls use, and for which keys. A `Connections.test` transport
618
+ * names the owner of the calls it answers. In a workflow step the owner is the run's, which the
619
+ * ontology service bound to the transport it made for this action from what the platform recorded
620
+ * when the run started, and only for the owned keys the run's workflow lists; nothing else gives a
621
+ * step's action an owner, the verified caller included, so a key the workflow does not list fails
622
+ * with `owner_required`. Otherwise it is the acting member's ({@link actingConnectionOwner}).
623
+ */
624
+ function connectionSelection(transport, principal, caller) {
625
+ const tested = testTransportOwner(transport);
626
+ if (tested !== undefined) {
627
+ return { owner: tested };
628
+ }
629
+ const run = runTransportOwner(transport);
630
+ return run !== undefined
631
+ ? { owner: run.owner, listed: run.listed }
632
+ : { owner: actingConnectionOwner(principal, caller) };
633
+ }
634
+ /**
635
+ * Who the runs an action's triggers start belong to, when their workflow is owned: the owner of
636
+ * the workflow run the action ran in, with that run's call kind, or the member who called it,
637
+ * interactively. A `Connections.test` owner names only whose credential its stubs see, never who a
638
+ * run acts as.
639
+ */
640
+ function startOwner(transport, principal, caller) {
641
+ return runTransportOwner(transport)?.owner ?? actingConnectionOwner(principal, caller);
642
+ }
580
643
  /**
581
644
  * Runs `prepare` outside any transaction, with reads, declared connections and file access.
582
645
  * Reads take no locks here: `forUpdate` is dropped, since a lock
@@ -587,6 +650,8 @@ function prepare(ontology, sql, action, context, connections, qualified, fileInv
587
650
  const transport = connections ?? Option.getOrUndefined(yield* Effect.serviceOption(ConnectionTransport));
588
651
  const fileAccess = Option.getOrUndefined(yield* Effect.serviceOption(FileAccess));
589
652
  const files = fileAccess?.forInvocation(fileInvocation) ?? unavailableFiles;
653
+ // The request's verified credential: none, or an API key with delegation, selects no owner.
654
+ const caller = yield* currentCaller;
590
655
  const runtime = makeOntologyRuntime(ontology, sql);
591
656
  const reads = {
592
657
  get: ({ entity, id }) => runtime.get({ entity, id }),
@@ -604,6 +669,7 @@ function prepare(ontology, sql, action, context, connections, qualified, fileInv
604
669
  }), Effect.provideContext(connectionContext(action.connections, transport ?? NO_CONNECTIONS, {
605
670
  readOnly: action.hints?.readOnly === true || action.hints?.connectionsReadOnly === true,
606
671
  files,
672
+ ...connectionSelection(transport, context.principal, caller),
607
673
  })), Effect.timeoutOrElse({
608
674
  duration: PREPARE_TIMEOUT,
609
675
  orElse: () => Effect.fail(new ConnectionError({