@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
@@ -0,0 +1,488 @@
1
+ import { Effect, Layer } from "effect";
2
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
3
+ import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
+ import { CONNECTION_KEY } from "../connection.js";
5
+ import { actingConnectionOwner } from "../runtime/pipeline.js";
6
+ import { currentCaller } from "./caller-context.js";
7
+ import { CurrentPrincipal, crossSiteRequest, withPrincipal, } from "./authentication.js";
8
+ import { RequestId, forbidden, notFound, toServerResponse } from "./errors.js";
9
+ import { identityToken } from "./operations.js";
10
+ import { OwnedConnectionRetirement } from "../runtime/owner-departures.js";
11
+ import { OntologyBackend } from "./runtime-contract.js";
12
+ /**
13
+ * The routes a workspace user manages their own credentials of owned connections with
14
+ * (docs/private-connections-spec.md, "In the ontology SDK"), under the caller's own `me`, which no
15
+ * entity, toolset or metric may be named. Every route but the discard acts as the signed-in member
16
+ * and on that member's own credential: the owner is always the request's principal, and no route
17
+ * takes a user id. The discard names no owner at all.
18
+ */
19
+ export const OWNED_CONNECTIONS_PATH = "/api/ontology/me/connections";
20
+ const NO_STORE = { "cache-control": "private, no-store" };
21
+ const BACKEND_TIMEOUT_MS = 15_000;
22
+ const MAXIMUM_CONFIRMATION = 128;
23
+ const MAXIMUM_TOKEN = 8192;
24
+ const MAXIMUM_ACCOUNT = 64;
25
+ const MAXIMUM_CURSOR = 256;
26
+ function isRecord(value) {
27
+ return typeof value === "object" && value !== null && !Array.isArray(value);
28
+ }
29
+ function invalid(requestId, detail) {
30
+ return { status: 400, body: { error: "invalid_request", detail, requestId } };
31
+ }
32
+ function unavailable(requestId, detail) {
33
+ return {
34
+ status: 503,
35
+ body: { error: "connection_unavailable", detail, requestId, retryable: true },
36
+ };
37
+ }
38
+ /** A credential state as backend-next answers it, on the ontology's snake_case wire. */
39
+ function stateOf(value) {
40
+ if (!isRecord(value) ||
41
+ typeof value.key !== "string" ||
42
+ typeof value.state !== "string" ||
43
+ typeof value.background !== "boolean" ||
44
+ (value.connectedAt !== null && typeof value.connectedAt !== "string")) {
45
+ return undefined;
46
+ }
47
+ return {
48
+ key: value.key,
49
+ state: value.state,
50
+ connected_at: value.connectedAt,
51
+ background: value.background,
52
+ };
53
+ }
54
+ function callOf(value) {
55
+ if (!isRecord(value) ||
56
+ typeof value.calledAt !== "string" ||
57
+ typeof value.callKind !== "string" ||
58
+ typeof value.source !== "string" ||
59
+ typeof value.method !== "string" ||
60
+ typeof value.path !== "string" ||
61
+ typeof value.outcome !== "string") {
62
+ return undefined;
63
+ }
64
+ return {
65
+ called_at: value.calledAt,
66
+ call_kind: value.callKind,
67
+ source: value.source,
68
+ method: value.method,
69
+ api: typeof value.api === "string" ? value.api : null,
70
+ path: value.path,
71
+ outcome: value.outcome,
72
+ request_id: typeof value.requestId === "string" ? value.requestId : null,
73
+ };
74
+ }
75
+ function json(body, status = 200) {
76
+ return HttpServerResponse.jsonUnsafe(body, { status, headers: NO_STORE });
77
+ }
78
+ /**
79
+ * The platform's retirement of a departed user's owned connection credentials, called with the
80
+ * request's deployment identity (`DELETE …/owners/:ownerId`) after the action that made them leave
81
+ * committed. A failure, or a request with no deployment identity, is logged and changes nothing
82
+ * else; the next deployment retires what was missed.
83
+ */
84
+ export function ownedConnectionRetirement(options, identityToken) {
85
+ const fetchImpl = options.fetch ?? fetch;
86
+ const base = `${options.environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
87
+ `${encodeURIComponent(options.environment.workspaceId)}/ontology/connections`;
88
+ return OwnedConnectionRetirement.of({
89
+ retire: (ownerId) => Effect.gen(function* () {
90
+ if (identityToken === undefined || identityToken === "") {
91
+ return yield* Effect.logWarning("ontology.owned_connections.retire_unavailable");
92
+ }
93
+ const status = yield* Effect.tryPromise({
94
+ try: async (signal) => {
95
+ const response = await fetchImpl(`${base}/owners/${encodeURIComponent(ownerId)}`, {
96
+ method: "DELETE",
97
+ redirect: "error",
98
+ headers: {
99
+ accept: "application/json",
100
+ "x-segmentstream-runtime-identity": identityToken,
101
+ "x-segmentstream-organization-id": options.environment.organizationId,
102
+ },
103
+ signal: AbortSignal.any([signal, AbortSignal.timeout(BACKEND_TIMEOUT_MS)]),
104
+ });
105
+ await response.body?.cancel();
106
+ return response.status;
107
+ },
108
+ catch: (cause) => cause,
109
+ });
110
+ if (status < 200 || status >= 300) {
111
+ yield* Effect.logWarning("ontology.owned_connections.retire_refused").pipe(Effect.annotateLogs({ status }));
112
+ }
113
+ }).pipe(Effect.catchCause((cause) => Effect.logWarning("ontology.owned_connections.retire_failed", cause))),
114
+ });
115
+ }
116
+ /**
117
+ * Whether a departed user's owned connection credentials are retired from this service: only in
118
+ * the platform's production deployment (it names its deployment, `workloadTarget`) of an ontology
119
+ * that declares an owned handle. Anywhere else a deactivation, a deletion or an identity
120
+ * revocation calls nothing and reads nothing for it.
121
+ */
122
+ export function retiresOwnedConnections(input) {
123
+ return input.ownedKeys.size > 0 && !input.preview && input.workloadTarget !== undefined;
124
+ }
125
+ /** Why backend-next did not answer a page of eligible owners. */
126
+ export class EligibleOwnersUnavailable extends Error {
127
+ constructor(message, options) {
128
+ super(message, options);
129
+ this.name = "EligibleOwnersUnavailable";
130
+ }
131
+ }
132
+ export function eligibleOwners(environment, fetchImpl = fetch) {
133
+ const base = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
134
+ `${encodeURIComponent(environment.workspaceId)}/ontology/connections/owners`;
135
+ return async ({ identityToken, keys, after, requestId }) => {
136
+ const query = new URLSearchParams({ keys: keys.join(",") });
137
+ if (after !== null) {
138
+ query.set("after", after);
139
+ }
140
+ let response;
141
+ try {
142
+ response = await fetchImpl(`${base}?${query.toString()}`, {
143
+ method: "GET",
144
+ redirect: "error",
145
+ headers: {
146
+ accept: "application/json",
147
+ "x-segmentstream-runtime-identity": identityToken,
148
+ "x-segmentstream-organization-id": environment.organizationId,
149
+ "x-segmentstream-request-id": requestId,
150
+ },
151
+ signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
152
+ });
153
+ }
154
+ catch (cause) {
155
+ throw new EligibleOwnersUnavailable("SegmentStream could not be reached.", { cause });
156
+ }
157
+ const text = await response.text();
158
+ let body;
159
+ try {
160
+ body = text === "" ? null : JSON.parse(text);
161
+ }
162
+ catch {
163
+ body = null;
164
+ }
165
+ if (!response.ok) {
166
+ const code = isRecord(body) && typeof body.error === "string" ? body.error : "unknown";
167
+ throw new EligibleOwnersUnavailable(`SegmentStream refused the eligible owners with ${response.status} (${code}).`);
168
+ }
169
+ if (!isRecord(body) ||
170
+ !Array.isArray(body.owners) ||
171
+ !body.owners.every((owner) => typeof owner === "string") ||
172
+ (body.next !== null && typeof body.next !== "string") ||
173
+ typeof body.ineligible !== "number") {
174
+ throw new EligibleOwnersUnavailable("SegmentStream answered the eligible owners unexpectedly.");
175
+ }
176
+ return {
177
+ owners: body.owners,
178
+ next: body.next,
179
+ ineligible: body.ineligible,
180
+ };
181
+ };
182
+ }
183
+ export function ownedConnectionsLayer(options) {
184
+ const fetchImpl = options.fetch ?? fetch;
185
+ const base = `${options.environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
186
+ `${encodeURIComponent(options.environment.workspaceId)}/ontology/connections`;
187
+ /**
188
+ * One request to backend-next with the deployment's OIDC token. A refusal backend-next words for
189
+ * the caller (a 4xx other than the runtime's own authentication) is answered as it is; anything
190
+ * else is the platform's fault, logged with its cause and answered as unavailable.
191
+ */
192
+ const send = (request, call) => Effect.gen(function* () {
193
+ const requestId = yield* RequestId;
194
+ const token = identityToken(request);
195
+ if (token === undefined || token === "") {
196
+ return {
197
+ ok: false,
198
+ response: unavailable(requestId, "Owned connections are available to production deployments, which carry a Vercel " +
199
+ "OIDC token."),
200
+ };
201
+ }
202
+ const answered = yield* Effect.tryPromise({
203
+ try: async (signal) => {
204
+ const response = await fetchImpl(`${base}${call.path}`, {
205
+ method: call.method,
206
+ redirect: "error",
207
+ headers: {
208
+ accept: "application/json",
209
+ "x-segmentstream-runtime-identity": token,
210
+ "x-segmentstream-organization-id": options.environment.organizationId,
211
+ "x-segmentstream-request-id": requestId,
212
+ ...(call.body === undefined ? {} : { "content-type": "application/json" }),
213
+ },
214
+ ...(call.body === undefined ? {} : { body: JSON.stringify(call.body) }),
215
+ signal: AbortSignal.any([signal, AbortSignal.timeout(BACKEND_TIMEOUT_MS)]),
216
+ });
217
+ const text = await response.text();
218
+ let body = null;
219
+ try {
220
+ body = text === "" ? null : JSON.parse(text);
221
+ }
222
+ catch {
223
+ body = null;
224
+ }
225
+ return { status: response.status, body };
226
+ },
227
+ catch: (cause) => cause,
228
+ }).pipe(Effect.map((answer) => ({ _tag: "answered", ...answer })), Effect.catch((cause) => Effect.succeed({ _tag: "unreachable", cause })));
229
+ if (answered._tag === "unreachable") {
230
+ yield* Effect.logError("ontology.owned_connections.unreachable", answered.cause).pipe(Effect.annotateLogs({ requestId }));
231
+ return {
232
+ ok: false,
233
+ response: unavailable(requestId, "SegmentStream could not be reached. Try again."),
234
+ };
235
+ }
236
+ if (answered.status >= 200 && answered.status < 300) {
237
+ return { ok: true, status: answered.status, body: answered.body };
238
+ }
239
+ const code = isRecord(answered.body) && typeof answered.body.error === "string"
240
+ ? answered.body.error
241
+ : undefined;
242
+ const detail = isRecord(answered.body) && typeof answered.body.detail === "string"
243
+ ? answered.body.detail
244
+ : undefined;
245
+ if (answered.status >= 400 &&
246
+ answered.status < 500 &&
247
+ answered.status !== 401 &&
248
+ answered.status !== 403 &&
249
+ code !== undefined) {
250
+ return {
251
+ ok: false,
252
+ response: {
253
+ status: answered.status,
254
+ body: {
255
+ error: code,
256
+ detail: detail ?? code,
257
+ requestId,
258
+ ...(isRecord(answered.body) && typeof answered.body.retryable === "boolean"
259
+ ? { retryable: answered.body.retryable }
260
+ : {}),
261
+ },
262
+ },
263
+ };
264
+ }
265
+ yield* Effect.logError("ontology.owned_connections.refused").pipe(Effect.annotateLogs({ requestId, status: answered.status, code: code ?? "unknown" }));
266
+ return {
267
+ ok: false,
268
+ response: unavailable(requestId, "SegmentStream could not serve the request. Try again."),
269
+ };
270
+ });
271
+ /** The request's JSON body as an object; `undefined` when it is not one. */
272
+ const bodyOf = (request) => request.json.pipe(Effect.map((value) => (isRecord(value) ? value : undefined)), Effect.catch(() => Effect.succeed(undefined)));
273
+ const keyOf = Effect.map(HttpRouter.params, (params) => {
274
+ const key = params.key ?? "";
275
+ return CONNECTION_KEY.test(key) ? key : undefined;
276
+ });
277
+ return Layer.effectDiscard(Effect.gen(function* () {
278
+ const router = yield* HttpRouter.HttpRouter;
279
+ const backend = yield* OntologyBackend;
280
+ const credential = HttpApiBuilder.securityDecode(HttpApiSecurity.bearer);
281
+ /**
282
+ * A route for the signed-in member only, on their own credential. A guest, a service, a
283
+ * workflow's user and an agent task are refused: none of them is a person who connects. The
284
+ * session cookie authenticates a change only from the app's own origin, as on every route.
285
+ */
286
+ const asMember = (answer) => (request) => Effect.gen(function* () {
287
+ const bearer = yield* Effect.provideService(credential, HttpServerRequest.HttpServerRequest, request);
288
+ const decided = Effect.gen(function* () {
289
+ const requestId = yield* RequestId;
290
+ const principal = yield* CurrentPrincipal;
291
+ const owner = actingConnectionOwner(principal, yield* currentCaller);
292
+ if (owner === undefined) {
293
+ return toServerResponse(forbidden(requestId, "Only a signed-in member manages their own connections."));
294
+ }
295
+ return yield* answer(request, yield* keyOf, owner.id);
296
+ });
297
+ return yield* withPrincipal(bearer, options.verifyToken, backend, decided, {
298
+ session: { request, exchange: options.exchangeSession },
299
+ });
300
+ });
301
+ const withKey = (requestId, key, answer) => key === undefined
302
+ ? Effect.succeed(toServerResponse(notFound(requestId, "There is no such connection.")))
303
+ : answer(key);
304
+ const answerState = (answered, requestId) => {
305
+ if (!answered.ok) {
306
+ return toServerResponse(answered.response);
307
+ }
308
+ const state = stateOf(answered.body);
309
+ return state === undefined
310
+ ? toServerResponse(unavailable(requestId, "SegmentStream answered unexpectedly."))
311
+ : json(state);
312
+ };
313
+ // GET: the caller's own owned connections.
314
+ yield* router.add("GET", OWNED_CONNECTIONS_PATH, asMember((request, _key, owner) => Effect.gen(function* () {
315
+ const requestId = yield* RequestId;
316
+ const answered = yield* send(request, {
317
+ method: "GET",
318
+ path: `/owned?${new URLSearchParams({ owner }).toString()}`,
319
+ });
320
+ if (!answered.ok) {
321
+ return toServerResponse(answered.response);
322
+ }
323
+ const listed = isRecord(answered.body) ? answered.body.connections : undefined;
324
+ const connections = Array.isArray(listed) ? listed.map(stateOf) : undefined;
325
+ return connections === undefined || connections.includes(undefined)
326
+ ? toServerResponse(unavailable(requestId, "SegmentStream answered unexpectedly."))
327
+ : json({ connections });
328
+ })));
329
+ // GET: the caller's own calls with their credential of the key, newest first.
330
+ yield* router.add("GET", `${OWNED_CONNECTIONS_PATH}/:key/calls`, asMember((request, key, owner) => Effect.gen(function* () {
331
+ const requestId = yield* RequestId;
332
+ return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
333
+ const after = new URL(request.url, "https://ontology.invalid").searchParams.get("after");
334
+ if (after !== null && (after === "" || after.length > MAXIMUM_CURSOR)) {
335
+ return toServerResponse(invalid(requestId, "The cursor is invalid."));
336
+ }
337
+ const query = after === null ? "" : `?${new URLSearchParams({ after })}`;
338
+ const answered = yield* send(request, {
339
+ method: "GET",
340
+ path: `/${key}/owners/${encodeURIComponent(owner)}/calls${query}`,
341
+ });
342
+ if (!answered.ok) {
343
+ return toServerResponse(answered.response);
344
+ }
345
+ const body = isRecord(answered.body) ? answered.body : {};
346
+ const calls = Array.isArray(body.calls) ? body.calls.map(callOf) : undefined;
347
+ return calls === undefined ||
348
+ calls.includes(undefined) ||
349
+ (body.next !== null && typeof body.next !== "string")
350
+ ? toServerResponse(unavailable(requestId, "SegmentStream answered unexpectedly."))
351
+ : json({ calls, next: body.next });
352
+ }));
353
+ })));
354
+ // POST: starts the provider's consent for the caller. The consent returns to the app's
355
+ // connections page on its production origin; no caller names where.
356
+ yield* router.add("POST", `${OWNED_CONNECTIONS_PATH}/:key/authorization`, asMember((request, key, owner) => Effect.gen(function* () {
357
+ const requestId = yield* RequestId;
358
+ return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
359
+ const body = yield* bodyOf(request);
360
+ if (body === undefined || typeof body.background !== "boolean") {
361
+ return toServerResponse(invalid(requestId, "Send { background }."));
362
+ }
363
+ const answered = yield* send(request, {
364
+ method: "POST",
365
+ path: `/${key}/authorization`,
366
+ body: { owner, background: body.background },
367
+ });
368
+ if (!answered.ok) {
369
+ return toServerResponse(answered.response);
370
+ }
371
+ const started = isRecord(answered.body) ? answered.body : {};
372
+ return typeof started.authorizationUrl !== "string" ||
373
+ typeof started.expiresAt !== "string"
374
+ ? toServerResponse(unavailable(requestId, "SegmentStream answered unexpectedly."))
375
+ : json({
376
+ authorization_url: started.authorizationUrl,
377
+ expires_at: started.expiresAt,
378
+ });
379
+ }));
380
+ })));
381
+ // POST: connects the caller with a token they supply, for a provider that admits one.
382
+ yield* router.add("POST", `${OWNED_CONNECTIONS_PATH}/:key/authorization/token`, asMember((request, key, owner) => Effect.gen(function* () {
383
+ const requestId = yield* RequestId;
384
+ return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
385
+ const body = yield* bodyOf(request);
386
+ if (body === undefined ||
387
+ typeof body.background !== "boolean" ||
388
+ typeof body.token !== "string" ||
389
+ body.token === "" ||
390
+ body.token.length > MAXIMUM_TOKEN ||
391
+ (body.account_id !== undefined &&
392
+ (typeof body.account_id !== "string" ||
393
+ body.account_id.length > MAXIMUM_ACCOUNT))) {
394
+ return toServerResponse(invalid(requestId, "Send { token, background } and an optional account_id."));
395
+ }
396
+ return answerState(yield* send(request, {
397
+ method: "POST",
398
+ path: `/${key}/authorization/token`,
399
+ body: {
400
+ owner,
401
+ token: body.token,
402
+ background: body.background,
403
+ ...(body.account_id === undefined ? {} : { accountId: body.account_id }),
404
+ },
405
+ }), requestId);
406
+ }));
407
+ })));
408
+ // POST: the caller, back from the provider, confirms the code the page read from its
409
+ // fragment. backend-next activates the credential only for the attempt's own owner.
410
+ yield* router.add("POST", `${OWNED_CONNECTIONS_PATH}/:key/authorization/confirm`, asMember((request, key, owner) => Effect.gen(function* () {
411
+ const requestId = yield* RequestId;
412
+ return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
413
+ const body = yield* bodyOf(request);
414
+ if (body === undefined ||
415
+ typeof body.confirmation !== "string" ||
416
+ body.confirmation === "" ||
417
+ body.confirmation.length > MAXIMUM_CONFIRMATION) {
418
+ return toServerResponse(invalid(requestId, "Send { confirmation }."));
419
+ }
420
+ return answerState(yield* send(request, {
421
+ method: "POST",
422
+ path: `/${key}/authorization/confirm`,
423
+ body: { owner, confirmation: body.confirmation },
424
+ }), requestId);
425
+ }));
426
+ })));
427
+ // POST, with no credential: spends a code the page could not confirm because nobody is
428
+ // signed in, so its secret is deleted. It names no owner, can never activate a credential
429
+ // and answers the same whether or not the code matched; a browser may send it only from the
430
+ // app's own pages. A key that is not an owned handle, or a body that is not a code, has no
431
+ // code to spend: it is answered as a discarded one without asking backend-next, so the route
432
+ // neither tells which keys are owned nor turns anonymous requests into backend load.
433
+ yield* router.add("POST", `${OWNED_CONNECTIONS_PATH}/:key/authorization/discard`, (request) => Effect.gen(function* () {
434
+ const requestId = yield* RequestId;
435
+ const discarded = HttpServerResponse.empty({ status: 204, headers: NO_STORE });
436
+ if (crossSiteRequest(request)) {
437
+ return toServerResponse(forbidden(requestId, "A confirmation is discarded only from the app's own pages."));
438
+ }
439
+ // No rate limit: the starter calls this route from its own server, so every person
440
+ // would share one client address, and a discard spends only a code its caller holds.
441
+ const key = yield* keyOf;
442
+ if (key === undefined || !options.ownedKeys.has(key)) {
443
+ return discarded;
444
+ }
445
+ const body = yield* bodyOf(request);
446
+ if (body === undefined ||
447
+ typeof body.confirmation !== "string" ||
448
+ body.confirmation === "" ||
449
+ body.confirmation.length > MAXIMUM_CONFIRMATION) {
450
+ return discarded;
451
+ }
452
+ const answered = yield* send(request, {
453
+ method: "POST",
454
+ path: `/${key}/authorization/discard`,
455
+ body: { confirmation: body.confirmation },
456
+ });
457
+ return answered.ok ? discarded : toServerResponse(answered.response);
458
+ }));
459
+ // PATCH: sets or clears the caller's background consent on their own credential.
460
+ yield* router.add("PATCH", `${OWNED_CONNECTIONS_PATH}/:key`, asMember((request, key, owner) => Effect.gen(function* () {
461
+ const requestId = yield* RequestId;
462
+ return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
463
+ const body = yield* bodyOf(request);
464
+ if (body === undefined || typeof body.background !== "boolean") {
465
+ return toServerResponse(invalid(requestId, "Send { background }."));
466
+ }
467
+ return answerState(yield* send(request, {
468
+ method: "PATCH",
469
+ path: `/${key}/owners/${encodeURIComponent(owner)}`,
470
+ body: { background: body.background },
471
+ }), requestId);
472
+ }));
473
+ })));
474
+ // DELETE: disconnects the caller's own credential of the key.
475
+ yield* router.add("DELETE", `${OWNED_CONNECTIONS_PATH}/:key`, asMember((request, key, owner) => Effect.gen(function* () {
476
+ const requestId = yield* RequestId;
477
+ return yield* withKey(requestId, key, (key) => Effect.gen(function* () {
478
+ const answered = yield* send(request, {
479
+ method: "DELETE",
480
+ path: `/owners/${encodeURIComponent(owner)}?${new URLSearchParams({ key })}`,
481
+ });
482
+ return answered.ok
483
+ ? HttpServerResponse.empty({ status: 204, headers: NO_STORE })
484
+ : toServerResponse(answered.response);
485
+ }));
486
+ })));
487
+ }));
488
+ }
@@ -967,6 +967,8 @@ declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segm
967
967
  readonly requestId: string;
968
968
  /** The recovery run's horizon: count as waiting only the rows created before it. */
969
969
  readonly before?: string | undefined;
970
+ /** Epoch ms: sweep batch after batch until this instant, launching no start after it. */
971
+ readonly deadline?: number | undefined;
970
972
  }) => Effect.Effect<SweepResult>;
971
973
  readonly list: (input: {
972
974
  /** The workflow's wire name. */
@@ -976,6 +978,18 @@ declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segm
976
978
  readonly limit: number;
977
979
  readonly after?: string | undefined;
978
980
  }) => Effect.Effect<WorkflowStartsPage, InvalidStartsCursor>;
981
+ /**
982
+ * Writes the pending rows a cron decided for the owners of an owned workflow, one per owner
983
+ * and scheduled minute, and answers how many were new. Absent on a backend that cannot.
984
+ */
985
+ readonly writeOwned?: (starts: ReadonlyArray<import("../runtime/workflow-starts.js").OwnedCronStart>) => Effect.Effect<number>;
986
+ /** Starts the pending rows of one cron fire until `deadline`, as a sweep starts rows. */
987
+ readonly startFired?: (input: {
988
+ readonly trigger: string;
989
+ readonly fireKey: string;
990
+ readonly requestId: string;
991
+ readonly deadline: number;
992
+ }) => Effect.Effect<import("../runtime/workflow-starts.js").FiredStarts>;
979
993
  };
980
994
  /** The tasks workflows hand the app's agent, in `_agent_tasks`. */
981
995
  readonly agentTasks?: AgentTaskStore;
@@ -1021,6 +1035,14 @@ declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segm
1021
1035
  readonly workspaceId: string;
1022
1036
  readonly workflow: string;
1023
1037
  }) => Effect.Effect<Principal | undefined>;
1038
+ /**
1039
+ * The owner a workflow run acts as: the member `userId` names, with the roles, permissions and
1040
+ * scopes they hold now. `undefined` once they are inactive, blocked or deleted, or are not a
1041
+ * member. No token resolves it; only a run's recorded owner names it.
1042
+ */
1043
+ readonly resolveRunOwner?: (userId: string) => Effect.Effect<Principal | undefined>;
1044
+ /** Of the user ids given, those of active members, who may own a run a cron starts. */
1045
+ readonly activeMembers?: (userIds: ReadonlyArray<string>) => Effect.Effect<ReadonlySet<string>>;
1024
1046
  /**
1025
1047
  * Finds, links or creates the member's user. `undefined` when the user may not sign in, and
1026
1048
  * {@link NotInvited} when the sign-in policy turns away a person nobody invited.
@@ -531,6 +531,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
531
531
  readonly key: Schema.String;
532
532
  readonly description: Schema.String;
533
533
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
534
+ readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
534
535
  }>>>;
535
536
  readonly chat: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
536
537
  readonly telegram: Schema.optionalKey<Schema.Struct<{
@@ -926,6 +927,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
926
927
  readonly key: Schema.String;
927
928
  readonly description: Schema.String;
928
929
  readonly delivers: Schema.optionalKey<Schema.Literal<true>>;
930
+ readonly owner: Schema.optionalKey<Schema.Literal<"user">>;
929
931
  }>>>>;
930
932
  readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
931
933
  readonly telegram: Schema.optionalKey<Schema.Struct<{
@@ -17,6 +17,7 @@ import { implicitMemberOf } from "../role.js";
17
17
  import { sqlServiceRuntime } from "../runtime/service-binding.js";
18
18
  import { neonSignInLinks, segmentstreamSignInLinks } from "../runtime/sign-in-links.js";
19
19
  import { memberFileRoutes } from "./member-file-routes.js";
20
+ import { eligibleOwners, ownedConnectionRetirement, ownedConnectionsLayer, retiresOwnedConnections, } from "./owned-connections.js";
20
21
  import { attachmentsLayer } from "./agent/attachments.js";
21
22
  import { filesLayer } from "./agent/files.js";
22
23
  import { workspaceSourceLayer } from "./agent/source.js";
@@ -372,6 +373,15 @@ export function createOntologyService(ontology, config) {
372
373
  }
373
374
  : {}),
374
375
  });
376
+ // The keys the deployed ontology declares owned on a handle: one credential for each user.
377
+ const ownedKeys = new Set((ontology.manifest.connections ?? [])
378
+ .filter((candidate) => candidate.owner === "user")
379
+ .map((candidate) => candidate.key));
380
+ const retiresOwned = retiresOwnedConnections({
381
+ ownedKeys,
382
+ preview,
383
+ workloadTarget: config.workloadTarget,
384
+ });
375
385
  const connections = preview
376
386
  ? () => ({
377
387
  request: () => Effect.die(new DeploymentAdmissionError("preview_capability_unavailable", "connections")),
@@ -379,7 +389,11 @@ export function createOntologyService(ontology, config) {
379
389
  })
380
390
  : (config.connections ??
381
391
  (config.localConnections === undefined
382
- ? deployedConnections(config)
392
+ ? retiresOwned
393
+ ? Object.assign(deployedConnections(config), {
394
+ retirement: (token) => ownedConnectionRetirement({ environment: config, fetch: config.ownedConnectionsFetch }, token),
395
+ })
396
+ : deployedConnections(config)
383
397
  : localConnections(config.localConnections)));
384
398
  const replicate = deployedReplication(config);
385
399
  // The platform keeps chat history for production agents only.
@@ -535,7 +549,13 @@ export function createOntologyService(ontology, config) {
535
549
  chatDelivery,
536
550
  verifyToken,
537
551
  exchangeSession,
538
- }), withoutAgent ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
552
+ }), withoutAgent ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), ownedConnectionsLayer({
553
+ environment: config,
554
+ ownedKeys,
555
+ verifyToken,
556
+ exchangeSession,
557
+ fetch: config.ownedConnectionsFetch,
558
+ }), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
539
559
  ? Layer.empty
540
560
  : archiveRoutes({
541
561
  transport: chatHistory,
@@ -558,6 +578,7 @@ export function createOntologyService(ontology, config) {
558
578
  engine: workflowEngine,
559
579
  agentOrigin: config.agentOrigin,
560
580
  agentTransport: config.agentTaskTransport,
581
+ eligibleOwners: eligibleOwners(config, config.ownedConnectionsFetch),
561
582
  webhookSecret: config.webhookSecret,
562
583
  webhookVerifier: config.webhookVerifier ??
563
584
  deployedWebhookVerifier({
@@ -1,4 +1,4 @@
1
- import { Cause } from "effect";
1
+ import { Cause, Schema } from "effect";
2
2
  import type { WorkflowStepContext } from "../workflow-runtime.js";
3
3
  /** Public diagnostics contain declared safe messages, never the operator report or inputs. */
4
4
  export interface WorkflowErrorView {
@@ -15,6 +15,16 @@ export interface WorkflowErrorView {
15
15
  readonly appliedDeploymentId?: string;
16
16
  readonly generation?: string;
17
17
  }
18
+ declare const OwnerInactive_base: Schema.Class<OwnerInactive, Schema.TaggedStruct<"OwnerInactive", {
19
+ readonly reason: Schema.Literal<"owner_inactive">;
20
+ readonly message: Schema.String;
21
+ }>, Cause.YieldableError>;
22
+ /**
23
+ * The owner of a workflow run is no longer an active member: deactivated, blocked or deleted after
24
+ * the run started. The step fails, and the run never acts as the workflow's user instead.
25
+ */
26
+ export declare class OwnerInactive extends OwnerInactive_base {
27
+ }
18
28
  /** The SDK preserves Error.cause; custom Error properties are otherwise discarded. */
19
29
  export declare class WorkflowStepFailed extends Error {
20
30
  readonly fatal: boolean;
@@ -24,3 +34,10 @@ export declare class WorkflowStepFailed extends Error {
24
34
  export declare function stepFailure(cause: Cause.Cause<unknown>, requestId: string, step: WorkflowStepContext, workflow: string, credentials: readonly (string | undefined)[]): WorkflowStepFailed;
25
35
  /** Find our envelope through retry-exhaustion/run wrappers, with bounded cycle-safe traversal. */
26
36
  export declare function workflowErrorView(value: unknown): WorkflowErrorView | null;
37
+ /**
38
+ * A run's error, with the runtime's own classification when it failed the run for outgrowing a
39
+ * per-run limit: the code (`MAX_EVENTS_EXCEEDED`, `REPLAY_TIMEOUT`, `MAX_DELIVERIES_EXCEEDED`) and
40
+ * the first line of the runtime's message, which names the limit. Other failures are unchanged.
41
+ */
42
+ export declare function workflowRunErrorView(value: unknown, errorCode: unknown): WorkflowErrorView | null;
43
+ export {};