@segmentstream/ontology 0.197.0 → 0.198.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 (60) hide show
  1. package/CHANGELOG.md +103 -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/owner-departures.d.ts +35 -0
  21. package/dist/runtime/owner-departures.js +64 -0
  22. package/dist/runtime/pipeline.d.ts +15 -1
  23. package/dist/runtime/pipeline.js +67 -1
  24. package/dist/runtime/principals.d.ts +17 -2
  25. package/dist/runtime/principals.js +33 -2
  26. package/dist/runtime/service-binding.js +17 -3
  27. package/dist/runtime/workflow-starts.d.ts +108 -8
  28. package/dist/runtime/workflow-starts.js +276 -49
  29. package/dist/service/agent/attachments.js +27 -6
  30. package/dist/service/agent/authentication.d.ts +5 -0
  31. package/dist/service/agent/authentication.js +1 -1
  32. package/dist/service/agent/task-caller.d.ts +4 -2
  33. package/dist/service/agent/task-caller.js +4 -2
  34. package/dist/service/authentication.d.ts +7 -0
  35. package/dist/service/authentication.js +12 -0
  36. package/dist/service/chat/envelope.d.ts +7 -0
  37. package/dist/service/chat/envelope.js +15 -0
  38. package/dist/service/config.d.ts +6 -0
  39. package/dist/service/connections.d.ts +17 -2
  40. package/dist/service/connections.js +21 -1
  41. package/dist/service/errors.js +27 -1
  42. package/dist/service/member-files.js +6 -0
  43. package/dist/service/operations.d.ts +8 -0
  44. package/dist/service/operations.js +11 -4
  45. package/dist/service/owned-connections.d.ts +80 -0
  46. package/dist/service/owned-connections.js +488 -0
  47. package/dist/service/runtime-contract.d.ts +22 -0
  48. package/dist/service/schemas.d.ts +2 -0
  49. package/dist/service/service.js +23 -2
  50. package/dist/service/workflow-errors.d.ts +18 -1
  51. package/dist/service/workflow-errors.js +51 -2
  52. package/dist/service/workflows.d.ts +24 -0
  53. package/dist/service/workflows.js +360 -50
  54. package/dist/start-recovery-contract.d.ts +17 -1
  55. package/dist/start-recovery-contract.js +11 -1
  56. package/dist/start-recovery.js +4 -1
  57. package/dist/storage/tables.d.ts +15 -0
  58. package/dist/storage/tables.js +21 -0
  59. package/dist/workflow.d.ts +20 -2
  60. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { Context, Effect, Schema } from "effect";
2
2
  import { ActionRejected, PermissionDenied } from "../../errors.js";
3
+ import type { ValidationIssue } from "../../runtime/errors.js";
3
4
  import type { CallerContext } from "../caller-context.js";
4
5
  declare const RuntimeEnvelope: Schema.Struct<{
5
6
  readonly version: Schema.Literal<1>;
@@ -141,4 +142,10 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
141
142
  readonly operation_id?: string | undefined;
142
143
  };
143
144
  }, ActionRejected | PermissionDenied, never>;
145
+ /**
146
+ * The issue of a promotion whose action input carries runtime call metadata, which is refused: a
147
+ * promotion's provenance comes only from where its route takes it, never from the action input a
148
+ * model or client supplies. Empty when the input carries none.
149
+ */
150
+ export declare function nestedEnvelopeIssues(input: Readonly<Record<string, unknown>> | undefined): ReadonlyArray<ValidationIssue>;
144
151
  export {};
@@ -47,3 +47,18 @@ export function consumeChatEnvelope(args, caller) {
47
47
  return { input, envelope: parsed };
48
48
  });
49
49
  }
50
+ /**
51
+ * The issue of a promotion whose action input carries runtime call metadata, which is refused: a
52
+ * promotion's provenance comes only from where its route takes it, never from the action input a
53
+ * model or client supplies. Empty when the input carries none.
54
+ */
55
+ export function nestedEnvelopeIssues(input) {
56
+ return input !== undefined && Object.hasOwn(input, "_segmentstream")
57
+ ? [
58
+ {
59
+ path: ["input", "_segmentstream"],
60
+ message: "A promotion's action input cannot carry runtime call metadata.",
61
+ },
62
+ ]
63
+ : [];
64
+ }
@@ -185,6 +185,12 @@ export interface OntologyServiceConfig extends OntologyEnvironment {
185
185
  * set, else SegmentStream's proxy with the request's Vercel OIDC token.
186
186
  */
187
187
  readonly connections?: ConnectionTransportFactory;
188
+ /**
189
+ * Sends the requests of the caller's own connection routes (`/api/ontology/me/connections`), and
190
+ * a cron's read of the users eligible for an owned workflow's runs, to backend-next; tests
191
+ * replace it. Defaults to `fetch`.
192
+ */
193
+ readonly ownedConnectionsFetch?: typeof fetch;
188
194
  /**
189
195
  * Serve the MCP server at `/mcp`. On by default: its tools reach exactly what the HTTP routes
190
196
  * reach, with the same credentials.
@@ -1,6 +1,14 @@
1
+ import type { OwnedConnectionRetirement } from "../runtime/owner-departures.js";
1
2
  import { type ConnectionTransport } from "../connection.js";
2
3
  /** The header Vercel sets on each function request: the deployment's OIDC token. */
3
4
  export declare const OIDC_TOKEN_HEADER = "x-vercel-oidc-token";
5
+ /**
6
+ * The owner of an owned connection's call: the acting user's id (docs/private-connections-spec.md).
7
+ * Internal: the package does not export it, so no API names an owner.
8
+ */
9
+ export declare const CONNECTION_OWNER_HEADER = "x-segmentstream-connection-owner";
10
+ /** An owned connection's call kind, `interactive` or `background`. Internal, as the owner. */
11
+ export declare const CONNECTION_CALL_HEADER = "x-segmentstream-connection-call";
4
12
  /** Where `segmentstream exec` passes the local runtime context: a pipe's file descriptor. */
5
13
  export declare const RUNTIME_CONTEXT_FD = "SEGMENTSTREAM_RUNTIME_CONTEXT_FD";
6
14
  /** Who a connection call is made for. SegmentStream logs these; it never trusts them. */
@@ -11,11 +19,18 @@ export interface ConnectionAudit {
11
19
  readonly requestId: string;
12
20
  }
13
21
  /** Builds the transport of one action request. */
14
- export type ConnectionTransportFactory = (input: {
22
+ export type ConnectionTransportFactory = ((input: {
15
23
  /** The deployment's OIDC token, from the request or the environment. */
16
24
  readonly identityToken: string | undefined;
17
25
  readonly audit: ConnectionAudit;
18
- }) => ConnectionTransport["Service"];
26
+ }) => ConnectionTransport["Service"]) & {
27
+ /**
28
+ * The platform's retirement of a departed user's owned connection credentials, with the
29
+ * request's deployment identity; absent where there is no platform to call, as in a preview, a
30
+ * local run or a test.
31
+ */
32
+ readonly retirement?: (identityToken: string | undefined) => OwnedConnectionRetirement["Service"];
33
+ };
19
34
  /** A connection the local grant covers, as the CLI describes it. */
20
35
  export interface LocalConnection {
21
36
  readonly key: string;
@@ -1,9 +1,21 @@
1
1
  import { closeSync, readFileSync } from "node:fs";
2
2
  import { Effect, Stream } from "effect";
3
- import { CONNECTION_KEY, ConnectionError, MAXIMUM_CONNECTION_BODY_BYTES, MAXIMUM_CONNECTION_RESPONSE_BYTES, } from "../connection.js";
3
+ import { callOwner, CONNECTION_KEY, ConnectionError, MAXIMUM_CONNECTION_BODY_BYTES, MAXIMUM_CONNECTION_RESPONSE_BYTES, } from "../connection.js";
4
4
  import { CONNECTION_STREAM_MEDIA_TYPE, openConnectionStream } from "./connection-stream.js";
5
5
  /** The header Vercel sets on each function request: the deployment's OIDC token. */
6
6
  export const OIDC_TOKEN_HEADER = "x-vercel-oidc-token";
7
+ /**
8
+ * The owner of an owned connection's call: the acting user's id (docs/private-connections-spec.md).
9
+ * Internal: the package does not export it, so no API names an owner.
10
+ */
11
+ export const CONNECTION_OWNER_HEADER = "x-segmentstream-connection-owner";
12
+ /** An owned connection's call kind, `interactive` or `background`. Internal, as the owner. */
13
+ export const CONNECTION_CALL_HEADER = "x-segmentstream-connection-call";
14
+ function ownerHeaders(owner) {
15
+ return owner === undefined
16
+ ? {}
17
+ : { [CONNECTION_OWNER_HEADER]: owner.id, [CONNECTION_CALL_HEADER]: owner.call };
18
+ }
7
19
  /** Where `segmentstream exec` passes the local runtime context: a pipe's file descriptor. */
8
20
  export const RUNTIME_CONTEXT_FD = "SEGMENTSTREAM_RUNTIME_CONTEXT_FD";
9
21
  const MAXIMUM_CONTEXT_BYTES = 4 * 1_048_576;
@@ -24,6 +36,8 @@ function failure(connection, reason, message, requestId, cause) {
24
36
  }
25
37
  const REASONS = {
26
38
  connection_authorization_required: "authorization_required",
39
+ connection_owner_required: "owner_required",
40
+ connection_background_consent_required: "background_consent_required",
27
41
  connections_not_deployed: "not_deployed",
28
42
  connections_redeployment_required: "not_deployed",
29
43
  connection_not_found: "not_deployed",
@@ -50,6 +64,9 @@ const MESSAGES = {
50
64
  timeout: "The connection call exceeded its deadline.",
51
65
  invalid_request: "The connection proxy refused the request.",
52
66
  invalid_response: "The connection proxy answered with an invalid response.",
67
+ owner_required: "The connection is owned by each user; only code running as a signed-in user, or in a " +
68
+ "workflow run of one that lists it, may call it.",
69
+ background_consent_required: "The connection's owner has not allowed it to be used while nobody is asking for the work.",
53
70
  };
54
71
  function isRecord(value) {
55
72
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -206,6 +223,9 @@ export function deployedConnections(environment, fetchImpl = fetch) {
206
223
  "x-segmentstream-ontology-action": audit.action,
207
224
  "x-segmentstream-ontology-principal": audit.principalId,
208
225
  "x-segmentstream-request-id": audit.requestId,
226
+ // Only an owned connection's call names whose credential it uses: the runtime sets it
227
+ // beside the call, never a field a builder's call could carry.
228
+ ...ownerHeaders(callOwner(call)),
209
229
  },
210
230
  call: { ...call, api: call.api },
211
231
  });
@@ -280,13 +280,39 @@ function connectionFailure(error, requestId) {
280
280
  const connection = error.connection;
281
281
  switch (error.reason) {
282
282
  case "authorization_required":
283
+ // An owned connection is connected by the acting user in the app, at `connect`.
283
284
  return {
284
285
  status: 409,
285
286
  body: {
286
287
  error: "connection_authorization_required",
287
- detail: `Configure or authorize the ${connection} connection in SegmentStream.`,
288
+ detail: error.connect === undefined
289
+ ? `Configure or authorize the ${connection} connection in SegmentStream.`
290
+ : `The acting user has not connected the ${connection} connection.`,
288
291
  requestId,
289
292
  connection,
293
+ ...(error.connect === undefined ? {} : { connect: error.connect }),
294
+ },
295
+ };
296
+ case "owner_required":
297
+ return {
298
+ status: 409,
299
+ body: {
300
+ error: "connection_owner_required",
301
+ detail: `Each user connects the ${connection} connection; only a signed-in user's code may call it.`,
302
+ requestId,
303
+ connection,
304
+ retryable: false,
305
+ },
306
+ };
307
+ case "background_consent_required":
308
+ return {
309
+ status: 409,
310
+ body: {
311
+ error: "connection_background_consent_required",
312
+ detail: `The owner has not allowed the ${connection} connection to be used in the background.`,
313
+ requestId,
314
+ connection,
315
+ retryable: false,
290
316
  },
291
317
  };
292
318
  case "not_deployed":
@@ -6,6 +6,7 @@ import { schemaIssues } from "../runtime/validation.js";
6
6
  import { uploadFields } from "../storage/attachments.js";
7
7
  import { OpenUploads } from "../storage/sessions.js";
8
8
  import { CurrentPrincipal } from "./authentication.js";
9
+ import { nestedEnvelopeIssues } from "./chat/envelope.js";
9
10
  import { InvalidRequestBody, RequestId } from "./errors.js";
10
11
  const Id = Schema.String.check(Schema.isUUID());
11
12
  const DateTime = Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/));
@@ -211,6 +212,11 @@ export function memberFileOperations(backend, plan, operations) {
211
212
  }
212
213
  if (kind === "attachments-promote") {
213
214
  const input = yield* decode(Promotion, args);
215
+ // Runtime call metadata comes only from where the request's route takes it.
216
+ const nested = nestedEnvelopeIssues(input.input);
217
+ if (nested.length > 0) {
218
+ return yield* new InvalidRequestBody({ reason: "invalid_request", issues: nested });
219
+ }
214
220
  const promoted = yield* attachments.promoteForMember(input.id, {
215
221
  entity: input.entity,
216
222
  action: input.action,
@@ -1,6 +1,7 @@
1
1
  import type { ActionRuntime } from "../runtime-source.js";
2
2
  import { Effect, Schema } from "effect";
3
3
  import type { HttpServerRequest } from "effect/unstable/http";
4
+ import { type RunConnectionOwner } from "../connection.js";
4
5
  import { ActionRejected, PermissionDenied } from "../errors.js";
5
6
  import { type ScopedPermission } from "../permissions.js";
6
7
  import { type Query, type QueryResult } from "../query.js";
@@ -50,6 +51,13 @@ export interface ActionCall {
50
51
  };
51
52
  /** The deployment's OIDC token, which authorizes the action's connection calls. */
52
53
  readonly identityToken: string | undefined;
54
+ /**
55
+ * The owner of the workflow run whose step runs the action, as the platform recorded it when the
56
+ * run started, and the owned keys the run's workflow lists. Only the workflow service sets it.
57
+ * It is bound to this action's transport alone: a hook or another action the action leads to
58
+ * gets none.
59
+ */
60
+ readonly runOwner?: RunConnectionOwner | undefined;
53
61
  }
54
62
  /** What an action answers: `{ result, validation, edits }`. */
55
63
  export interface ActionAnswer {
@@ -2,10 +2,12 @@ import { Effect, Option, Schema } from "effect";
2
2
  import { editsFromWire, generatedResultFromWire, recordFromWire } from "../authoring-records.js";
3
3
  import { nameToWire } from "../authoring-names.js";
4
4
  import { principalFromWire } from "../authoring.js";
5
+ import { withRunOwner } from "../connection.js";
5
6
  import { ActionRejected, PermissionDenied } from "../errors.js";
6
7
  import { toCamelCase } from "../names.js";
7
8
  import { missingPermission, permissionOf, READ_VERB, } from "../permissions.js";
8
9
  import { includedRelationships } from "../query.js";
10
+ import { OwnedConnectionRetirement } from "../runtime/owner-departures.js";
9
11
  import { InvalidQuery } from "../runtime/errors.js";
10
12
  import { CurrentPrincipal } from "./authentication.js";
11
13
  import { currentCaller, CurrentCaller } from "./caller-context.js";
@@ -300,10 +302,10 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
300
302
  ...(call.confirm === undefined ? {} : { confirm: call.confirm }),
301
303
  },
302
304
  requestId,
303
- connections: connections({
305
+ connections: withRunOwner(connections({
304
306
  identityToken: call.identityToken,
305
307
  audit: { action: `${planned.name}.${name}`, principalId: principal.id, requestId },
306
- }),
308
+ }), call.runOwner),
307
309
  ...(hook || backend.replicationEnabled
308
310
  ? {
309
311
  afterCommit: (committed) => Effect.gen(function* () {
@@ -343,9 +345,14 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
343
345
  }
344
346
  : {}),
345
347
  });
346
- const outcome = yield* delivery === undefined
348
+ // A user the action makes leave has their owned connection credentials retired.
349
+ const retirement = connections.retirement?.(call.identityToken);
350
+ const retiring = retirement === undefined
347
351
  ? run
348
- : run.pipe(Effect.provideService(ChatDelivery, delivery));
352
+ : run.pipe(Effect.provideService(OwnedConnectionRetirement, retirement));
353
+ const outcome = yield* delivery === undefined
354
+ ? retiring
355
+ : retiring.pipe(Effect.provideService(ChatDelivery, delivery));
349
356
  // Validating a message checks its destination, sender and exact text, sending nothing.
350
357
  if (call.validateOnly &&
351
358
  outcome.validation.ok &&
@@ -0,0 +1,80 @@
1
+ import { Layer } from "effect";
2
+ import { HttpRouter } from "effect/unstable/http";
3
+ import { type SessionExchange, type TokenVerifier } from "./authentication.js";
4
+ import { RequestId } from "./errors.js";
5
+ import { OwnedConnectionRetirement } from "../runtime/owner-departures.js";
6
+ import { OntologyBackend } from "./runtime-contract.js";
7
+ /**
8
+ * The routes a workspace user manages their own credentials of owned connections with
9
+ * (docs/private-connections-spec.md, "In the ontology SDK"), under the caller's own `me`, which no
10
+ * entity, toolset or metric may be named. Every route but the discard acts as the signed-in member
11
+ * and on that member's own credential: the owner is always the request's principal, and no route
12
+ * takes a user id. The discard names no owner at all.
13
+ */
14
+ export declare const OWNED_CONNECTIONS_PATH = "/api/ontology/me/connections";
15
+ interface OwnedConnectionsOptions {
16
+ readonly environment: {
17
+ readonly segmentstreamUrl: string;
18
+ readonly workspaceId: string;
19
+ readonly organizationId: string;
20
+ };
21
+ /**
22
+ * The keys of the deployed ontology's owned handles. The discard asks backend-next only for one
23
+ * of these; any other key is answered as a discarded code, without a request.
24
+ */
25
+ readonly ownedKeys: ReadonlySet<string>;
26
+ readonly verifyToken: TokenVerifier;
27
+ readonly exchangeSession?: SessionExchange | undefined;
28
+ readonly fetch?: typeof fetch | undefined;
29
+ }
30
+ /**
31
+ * The platform's retirement of a departed user's owned connection credentials, called with the
32
+ * request's deployment identity (`DELETE …/owners/:ownerId`) after the action that made them leave
33
+ * committed. A failure, or a request with no deployment identity, is logged and changes nothing
34
+ * else; the next deployment retires what was missed.
35
+ */
36
+ export declare function ownedConnectionRetirement(options: {
37
+ readonly environment: OwnedConnectionsOptions["environment"];
38
+ readonly fetch?: typeof fetch | undefined;
39
+ }, identityToken: string | undefined): OwnedConnectionRetirement["Service"];
40
+ /**
41
+ * Whether a departed user's owned connection credentials are retired from this service: only in
42
+ * the platform's production deployment (it names its deployment, `workloadTarget`) of an ontology
43
+ * that declares an owned handle. Anywhere else a deactivation, a deletion or an identity
44
+ * revocation calls nothing and reads nothing for it.
45
+ */
46
+ export declare function retiresOwnedConnections(input: {
47
+ readonly ownedKeys: ReadonlySet<string>;
48
+ readonly preview: boolean;
49
+ readonly workloadTarget: {
50
+ readonly deploymentId: string;
51
+ } | undefined;
52
+ }): boolean;
53
+ /** One page of the owners eligible for a scheduled run, as backend-next answers it. */
54
+ export interface EligibleOwnersPage {
55
+ readonly owners: ReadonlyArray<string>;
56
+ /** The owner id to continue after; `null` on the last page. */
57
+ readonly next: string | null;
58
+ /** Users who hold a credential on some listed key but are not eligible, on every page. */
59
+ readonly ineligible: number;
60
+ }
61
+ /** Why backend-next did not answer a page of eligible owners. */
62
+ export declare class EligibleOwnersUnavailable extends Error {
63
+ constructor(message: string, options?: {
64
+ readonly cause?: unknown;
65
+ });
66
+ }
67
+ /**
68
+ * Reads the owners eligible for a scheduled run of a workflow listing these owned keys, a page of
69
+ * 500 at a time (`listEligibleConnectionOwners`), with the deployment's OIDC token: users with an
70
+ * active credential and background consent on every key.
71
+ */
72
+ export type EligibleOwners = (input: {
73
+ readonly identityToken: string;
74
+ readonly keys: ReadonlyArray<string>;
75
+ readonly after: string | null;
76
+ readonly requestId: string;
77
+ }) => Promise<EligibleOwnersPage>;
78
+ export declare function eligibleOwners(environment: OwnedConnectionsOptions["environment"], fetchImpl?: typeof fetch): EligibleOwners;
79
+ export declare function ownedConnectionsLayer(options: OwnedConnectionsOptions): Layer.Layer<never, never, OntologyBackend | HttpRouter.HttpRouter | HttpRouter.Request<"Requires", RequestId>>;
80
+ export {};