@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,10 +1,12 @@
1
1
  import { Context, Duration, Effect, Option, Schema } from "effect";
2
+ import { createHash } from "node:crypto";
2
3
  import { NO_INPUT } from "../analyze.js";
3
4
  import { actionInputToWire } from "../authoring-input.js";
4
5
  import { nameToWire } from "../authoring-names.js";
5
6
  import { editsFromWire, generatedResultFromWire, recordFromWire } from "../authoring-records.js";
6
7
  import { principalFromWire } from "../authoring.js";
7
8
  import { isActionTrigger } from "../manifest.js";
9
+ import { ownedConnectionKeys } from "../owned-workflows.js";
8
10
  import { referenceTarget } from "../property.js";
9
11
  import { NIL_RECORD_ID, WORKFLOW_STARTS_TABLE } from "../storage/tables.js";
10
12
  import { isWorkflowTrigger, } from "../workflow.js";
@@ -24,6 +26,47 @@ export const STARTED_RETENTION_DAYS = 30;
24
26
  const START_CONCURRENCY = 10;
25
27
  /** How long one start may take before it counts as failed and its row stays pending. */
26
28
  const START_TIMEOUT = Duration.seconds(15);
29
+ /** The run attributes that record a run's owner, next to `startedBy.*`. */
30
+ export const OWNER_ATTRIBUTES = {
31
+ entity: "owner.entity",
32
+ id: "owner.id",
33
+ call: "owner.call",
34
+ };
35
+ /** A user id as the ontology stores it: a uuid. */
36
+ const USER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
37
+ /** The attributes that record `owner` on a run; none without one. */
38
+ export function ownerAttributes(owner) {
39
+ return owner === undefined
40
+ ? {}
41
+ : {
42
+ [OWNER_ATTRIBUTES.entity]: owner.entity,
43
+ [OWNER_ATTRIBUTES.id]: owner.id,
44
+ [OWNER_ATTRIBUTES.call]: owner.call,
45
+ };
46
+ }
47
+ /**
48
+ * The owner a run's attributes record: `undefined` for a run without one, such as every run
49
+ * started before owners were recorded, and `"invalid"` for attributes that name an owner this SDK
50
+ * cannot read, which no step may run as anyone else for.
51
+ */
52
+ export function recordedOwner(attributes) {
53
+ const entity = attributes?.[OWNER_ATTRIBUTES.entity];
54
+ const id = attributes?.[OWNER_ATTRIBUTES.id];
55
+ const call = attributes?.[OWNER_ATTRIBUTES.call];
56
+ if (entity === undefined && id === undefined && call === undefined) {
57
+ return undefined;
58
+ }
59
+ return entity === "user" &&
60
+ id !== undefined &&
61
+ USER_ID.test(id) &&
62
+ (call === "interactive" || call === "background")
63
+ ? { entity, id, call }
64
+ : "invalid";
65
+ }
66
+ /** The owner whose credential a run's calls use, as the connection runtime takes it. */
67
+ export function connectionOwnerOf(owner) {
68
+ return { id: owner.id, call: owner.call };
69
+ }
27
70
  /** The Workflow SDK refused or did not answer a start; the row stays pending. */
28
71
  export class WorkflowStartFailed extends Schema.TaggedError()("WorkflowStartFailed", {
29
72
  reason: Schema.Literals([
@@ -46,7 +89,7 @@ export class WorkflowStartFailed extends Schema.TaggedError()("WorkflowStartFail
46
89
  */
47
90
  export class WorkflowStarter extends Context.Service()("@segmentstream/ontology/WorkflowStarter") {
48
91
  }
49
- /** The `startedBy` of a run an action trigger started. */
92
+ /** The `startedBy` of a run an action trigger started, and its owner. */
50
93
  export function triggerContext(start) {
51
94
  return {
52
95
  startedBy: {
@@ -56,6 +99,21 @@ export function triggerContext(start) {
56
99
  actionId: start.actionId,
57
100
  ...(start.recordId === null ? {} : { recordId: start.recordId }),
58
101
  },
102
+ ...(start.owner === undefined
103
+ ? {}
104
+ : { owner: { entity: start.owner.entity, id: start.owner.id } }),
105
+ };
106
+ }
107
+ /**
108
+ * A run's plaintext attributes: who started it, `startedBy.*`, and its owner, `owner.*`. Workflow
109
+ * SDK 5 attributes are flat strings; `$` keys belong to the SDK.
110
+ */
111
+ export function runAttributes(startedBy, owner) {
112
+ return {
113
+ ...Object.fromEntries(Object.entries(startedBy)
114
+ .filter((entry) => typeof entry[1] === "string")
115
+ .map(([key, value]) => [`startedBy.${key}`, value])),
116
+ ...ownerAttributes(owner),
59
117
  };
60
118
  }
61
119
  const resolvedTriggers = new WeakMap();
@@ -75,6 +133,7 @@ export function actionTriggers(ontology) {
75
133
  return [];
76
134
  }
77
135
  const codec = declaration.input === undefined ? NO_INPUT : actionInputToWire(declaration.input);
136
+ const owned = ownedConnectionKeys(ontology.manifest, manifest).length > 0;
78
137
  return manifest.triggers.filter(isActionTrigger).flatMap((trigger) => {
79
138
  const authored = declaration.triggers.find((candidate) => isWorkflowTrigger(candidate) &&
80
139
  candidate.kind === "action" &&
@@ -90,6 +149,7 @@ export function actionTriggers(ontology) {
90
149
  when: authored.when,
91
150
  input: authored.input,
92
151
  codec,
152
+ owned,
93
153
  },
94
154
  ];
95
155
  });
@@ -97,10 +157,6 @@ export function actionTriggers(ontology) {
97
157
  resolvedTriggers.set(ontology, resolved);
98
158
  return resolved;
99
159
  }
100
- /** Whether the ontology declares any action trigger, so that `_workflow_starts` exists. */
101
- export function hasActionTriggers(ontology) {
102
- return actionTriggers(ontology).length > 0;
103
- }
104
160
  /**
105
161
  * The triggers that fire for an action of `entity` run by `principal`: on that action or on the
106
162
  * entity, except the triggers of the workflow whose user runs it, so that a workflow never starts
@@ -213,6 +269,15 @@ export function evaluateTriggers(triggers, evaluation) {
213
269
  actionId: evaluation.actionId,
214
270
  recordId: named ? null : id,
215
271
  input,
272
+ ...(trigger.owned && evaluation.owner !== undefined
273
+ ? {
274
+ owner: {
275
+ entity: "user",
276
+ id: evaluation.owner.id,
277
+ call: evaluation.owner.call,
278
+ },
279
+ }
280
+ : {}),
216
281
  });
217
282
  }
218
283
  }
@@ -241,6 +306,8 @@ const INSERT_CHUNK = 1_000;
241
306
  export function insertStarts(sql, starts) {
242
307
  return Effect.gen(function* () {
243
308
  const capture = Option.getOrUndefined(yield* Effect.serviceOption(WorkflowStarter))?.capture;
309
+ // Only an owned workflow's starts have owners, and only its ontology has the owner columns.
310
+ const owners = starts.some((start) => start.owner !== undefined);
244
311
  for (let offset = 0; offset < starts.length; offset += INSERT_CHUNK) {
245
312
  const chunk = starts.slice(offset, offset + INSERT_CHUNK);
246
313
  const params = [];
@@ -248,27 +315,50 @@ export function insertStarts(sql, starts) {
248
315
  const bound = capture?.(start);
249
316
  params.push(start.trigger, start.actionId, start.recordId, start.workflow, JSON.stringify(start.input), process.env.VERCEL_DEPLOYMENT_ID ?? null, bound?.workflowId ?? null, bound ? JSON.stringify(encodeWorkflowArguments(bound.arguments)) : null, bound ? JSON.stringify(bound.attributes) : null);
250
317
  const at = params.length - 9;
251
- return (`($${at + 1}, $${at + 2}::uuid, $${at + 3}::uuid, $${at + 4}, $${at + 5}::jsonb, ` +
318
+ const row = `$${at + 1}, $${at + 2}::uuid, $${at + 3}::uuid, $${at + 4}, $${at + 5}::jsonb, ` +
252
319
  `$${at + 6},$${at + 7},` +
253
- `$${at + 8}::jsonb,$${at + 9}::jsonb)`);
320
+ `$${at + 8}::jsonb,$${at + 9}::jsonb`;
321
+ if (!owners) {
322
+ return `(${row})`;
323
+ }
324
+ params.push(start.owner?.entity ?? null, start.owner?.id ?? null, start.owner?.call ?? null);
325
+ return `(${row}, $${at + 10}, $${at + 11}, $${at + 12})`;
254
326
  });
255
327
  yield* sql.unsafe(`INSERT INTO "${WORKFLOW_STARTS_TABLE}" ("trigger", "action_id", "record_id", "workflow", "input", ` +
256
- `admission_deployment_id,provider_workflow_id,arguments,admission_attributes) ` +
328
+ `admission_deployment_id,provider_workflow_id,arguments,admission_attributes` +
329
+ `${owners ? `, "owner_entity", "owner_id", "owner_call"` : ""}) ` +
257
330
  `VALUES ${values.join(", ")}`, params);
258
331
  }
259
332
  });
260
333
  }
261
- /** Runs the starts, a few at a time; each failure is kept, never raised. */
262
- function attempt(starter, starts) {
263
- return Effect.forEach(starts, (start) => starter.start(start).pipe(Effect.timeoutOrElse({
264
- duration: START_TIMEOUT,
265
- orElse: () => Effect.fail(new WorkflowStartFailed({
266
- reason: "timeout",
267
- message: `The Workflow SDK did not accept the run within ${Duration.format(START_TIMEOUT)}.`,
268
- })),
269
- }), Effect.result, Effect.map((result) => ({ start, result }))), { concurrency: START_CONCURRENCY }).pipe(Effect.map((results) => ({
270
- started: results.flatMap(({ start, result }) => result._tag === "Success" ? [{ start, runId: result.success }] : []),
271
- failed: results.flatMap(({ start, result }) => result._tag === "Failure" ? [{ start, error: result.failure }] : []),
334
+ /**
335
+ * Runs the starts, a few at a time; each failure is kept, never raised. With a deadline, no start
336
+ * is launched once it has passed, and a start still in flight then is cut off, so the call ends by
337
+ * the deadline whatever the Workflow SDK does.
338
+ */
339
+ function attempt(starter, starts, until) {
340
+ return Effect.forEach(starts, (start) => Effect.suspend(() => {
341
+ const remaining = until === undefined ? undefined : until.deadline - until.clock();
342
+ if (remaining !== undefined && remaining <= 0) {
343
+ return Effect.succeed({ start, result: undefined });
344
+ }
345
+ const started = starter.start(start).pipe(Effect.timeoutOrElse({
346
+ duration: START_TIMEOUT,
347
+ orElse: () => Effect.fail(new WorkflowStartFailed({
348
+ reason: "timeout",
349
+ message: `The Workflow SDK did not accept the run within ${Duration.format(START_TIMEOUT)}.`,
350
+ })),
351
+ }), Effect.result, Effect.map((result) => ({ start, result })));
352
+ return remaining === undefined
353
+ ? started
354
+ : started.pipe(Effect.timeoutOrElse({
355
+ duration: Duration.millis(remaining),
356
+ orElse: () => Effect.succeed({ start, result: undefined }),
357
+ }));
358
+ }), { concurrency: START_CONCURRENCY }).pipe(Effect.map((results) => ({
359
+ started: results.flatMap(({ start, result }) => result?._tag === "Success" ? [{ start, runId: result.success }] : []),
360
+ failed: results.flatMap(({ start, result }) => result?._tag === "Failure" ? [{ start, error: result.failure }] : []),
361
+ deferred: results.flatMap(({ start, result }) => (result === undefined ? [start] : [])),
272
362
  })));
273
363
  }
274
364
  /** `(trigger, action_id, record_id)` of each start as a VALUES list, from `$offset + 1`. */
@@ -296,7 +386,9 @@ const SAME_ROW = `s."trigger" = v."trigger" AND s."action_id" = v."action_id" `
296
386
  * each that failed, logged with the request id. A start that reaches {@link MAX_START_ATTEMPTS} is
297
387
  * logged as abandoned.
298
388
  */
299
- function record(sql, attempted, requestId) {
389
+ function record(sql, attempted, requestId,
390
+ /** Keep a failed row's lease, so that a sweep that goes on until its deadline skips it. */
391
+ keepFailedLeased = false) {
300
392
  return Effect.gen(function* () {
301
393
  if (attempted.started.length > 0) {
302
394
  const params = [];
@@ -307,12 +399,21 @@ function record(sql, attempted, requestId) {
307
399
  `FROM (VALUES ${values}) AS v ("trigger", "action_id", "record_id", "run_id") ` +
308
400
  `WHERE ${SAME_ROW} AND s."run_id" IS NULL`, params);
309
401
  }
402
+ if (attempted.deferred.length > 0) {
403
+ const params = [];
404
+ const values = keys(attempted.deferred, params);
405
+ // Released at once, so that the recovery run need not wait out the lease.
406
+ yield* sql.unsafe(`UPDATE "${WORKFLOW_STARTS_TABLE}" AS s SET submission_lease_until=NULL ` +
407
+ `FROM (VALUES ${values}) AS v ("trigger", "action_id", "record_id") ` +
408
+ `WHERE ${SAME_ROW} AND s."run_id" IS NULL`, params);
409
+ }
310
410
  if (attempted.failed.length === 0) {
311
411
  return;
312
412
  }
313
413
  const params = [];
314
414
  const values = keys(attempted.failed.map(({ start }) => start), params);
315
- const counted = yield* sql.unsafe(`UPDATE "${WORKFLOW_STARTS_TABLE}" AS s SET "attempts" = s."attempts" + 1, submission_lease_until=NULL ` +
415
+ const counted = yield* sql.unsafe(`UPDATE "${WORKFLOW_STARTS_TABLE}" AS s SET "attempts" = s."attempts" + 1` +
416
+ `${keepFailedLeased ? "" : ", submission_lease_until=NULL"} ` +
316
417
  `FROM (VALUES ${values}) AS v ("trigger", "action_id", "record_id") ` +
317
418
  `WHERE ${SAME_ROW} AND s."run_id" IS NULL ` +
318
419
  `RETURNING s."trigger", s."action_id"::text AS "action_id", s."record_id"::text AS "record_id", s."attempts"`, params);
@@ -363,13 +464,30 @@ function hasStartsTable(sql) {
363
464
  .unsafe(`SELECT to_regclass('"${WORKFLOW_STARTS_TABLE}"') IS NOT NULL AS "present"`)
364
465
  .pipe(Effect.map(([row]) => row?.present === true));
365
466
  }
467
+ function rowOwner(row) {
468
+ if (row.owner_id === null || row.owner_id === undefined) {
469
+ return undefined;
470
+ }
471
+ const owner = recordedOwner({
472
+ ...(row.owner_entity ? { [OWNER_ATTRIBUTES.entity]: row.owner_entity } : {}),
473
+ [OWNER_ATTRIBUTES.id]: row.owner_id,
474
+ ...(row.owner_call ? { [OWNER_ATTRIBUTES.call]: row.owner_call } : {}),
475
+ });
476
+ // Only this SDK writes the columns; a row it cannot read is a defect, never a start with no owner.
477
+ if (owner === "invalid" || owner === undefined) {
478
+ throw new Error(`The start of ${row.trigger} records an owner this SDK cannot read.`);
479
+ }
480
+ return owner;
481
+ }
366
482
  function pendingOf(row) {
483
+ const owner = rowOwner(row);
367
484
  return {
368
485
  trigger: row.trigger,
369
486
  workflow: row.workflow,
370
487
  actionId: row.action_id,
371
488
  recordId: row.record_id,
372
489
  input: typeof row.input === "string" ? JSON.parse(row.input) : row.input,
490
+ ...(owner === undefined ? {} : { owner }),
373
491
  ...(row.reservation ? { reservation: row.reservation } : {}),
374
492
  ...(row.arguments ? { arguments: decodeWorkflowArguments(row.arguments) } : {}),
375
493
  ...(row.provider_workflow_id ? { workflowId: row.provider_workflow_id } : {}),
@@ -377,42 +495,68 @@ function pendingOf(row) {
377
495
  ...(row.admission_deployment_id ? { deploymentId: row.admission_deployment_id } : {}),
378
496
  };
379
497
  }
498
+ /**
499
+ * What a sweep reads of a pending row, and with `owners` its owner: only an ontology that declares
500
+ * an owned workflow has the owner columns, and every other ontology's sweep reads what it read
501
+ * before them.
502
+ */
503
+ function startColumns(owners) {
504
+ return (`"trigger", "action_id"::text AS "action_id", "record_id"::text AS "record_id", ` +
505
+ `"workflow", "input",reservation,arguments,provider_workflow_id,admission_attributes,` +
506
+ `admission_deployment_id${owners ? `, "owner_entity", "owner_id", "owner_call"` : ""}`);
507
+ }
508
+ /** Holds the selected rows for 30 seconds, so that no other sweep starts them meanwhile. */
509
+ function lease(sql, rows) {
510
+ return Effect.forEach(rows, (row) => sql.unsafe(`UPDATE _workflow_starts SET submission_lease_until=clock_timestamp()+interval '30 seconds'
511
+ WHERE trigger=$1 AND action_id=$2::uuid AND record_id IS NOT DISTINCT FROM $3::uuid`, [row.trigger, row.action_id, row.record_id]), { discard: true });
512
+ }
380
513
  /**
381
514
  * The sweep: starts up to {@link SWEEP_BATCH} rows pending for more than
382
515
  * {@link SWEEP_DELAY_SECONDS}, oldest first, locked with `SKIP LOCKED` so that concurrent sweeps
383
- * take different rows, and records each outcome before the locks are released. Rows that failed
384
- * {@link MAX_START_ATTEMPTS} times are taken only with `retryAbandoned`. Started rows older than
385
- * {@link STARTED_RETENTION_DAYS} days are deleted. `waiting` counts the pending rows an automatic
386
- * sweep still takes, young ones included, created before `before` when it is given: the recovery
387
- * run's horizon.
516
+ * take different rows, and records each outcome before the locks are released. With a `deadline`
517
+ * it takes batch after batch until none is left or the deadline passes, and launches no start after
518
+ * it: the recovery run of an ontology with an owned workflow drains a cron's rows this way. Rows
519
+ * that failed {@link MAX_START_ATTEMPTS} times are taken only with `retryAbandoned`. Started rows
520
+ * older than {@link STARTED_RETENTION_DAYS} days are deleted. `waiting` counts the pending rows an
521
+ * automatic sweep still takes, young ones included, created before `before` when it is given: the
522
+ * recovery run's horizon.
388
523
  */
389
524
  export function sweepStarts(sql, starter, options) {
390
525
  return Effect.gen(function* () {
391
526
  if (!(yield* hasStartsTable(sql))) {
392
527
  return nothingToSweep();
393
528
  }
394
- const selected = yield* sql.withTransaction(Effect.gen(function* () {
395
- const rows = yield* sql.unsafe(`SELECT "trigger", "action_id"::text AS "action_id", "record_id"::text AS "record_id", ` +
396
- `"workflow", "input",reservation,arguments,provider_workflow_id,admission_attributes,` +
397
- `admission_deployment_id FROM "${WORKFLOW_STARTS_TABLE}" ` +
398
- `WHERE "run_id" IS NULL AND "created_at" < now() - make_interval(secs => $1) ` +
399
- `AND (submission_lease_until IS NULL OR submission_lease_until < clock_timestamp()) ` +
400
- `AND ($2 OR "attempts" < $3) ORDER BY "created_at" LIMIT $4 FOR UPDATE SKIP LOCKED`, [SWEEP_DELAY_SECONDS, options.retryAbandoned, MAX_START_ATTEMPTS, SWEEP_BATCH]);
401
- for (const row of rows) {
402
- yield* sql.unsafe(`UPDATE _workflow_starts SET submission_lease_until=clock_timestamp()+interval '30 seconds'
403
- WHERE trigger=$1 AND action_id=$2::uuid AND record_id IS NOT DISTINCT FROM $3::uuid`, [row.trigger, row.action_id, row.record_id]);
529
+ const clock = options.clock ?? Date.now;
530
+ const until = options.deadline === undefined ? undefined : { deadline: options.deadline, clock };
531
+ let started = 0;
532
+ let failed = 0;
533
+ do {
534
+ const selected = yield* sql.withTransaction(Effect.gen(function* () {
535
+ const rows = yield* sql.unsafe(`SELECT ${startColumns(options.owners === true)} FROM "${WORKFLOW_STARTS_TABLE}" ` +
536
+ `WHERE "run_id" IS NULL AND "created_at" < now() - make_interval(secs => $1) ` +
537
+ `AND (submission_lease_until IS NULL OR submission_lease_until < clock_timestamp()) ` +
538
+ `AND ($2 OR "attempts" < $3) ORDER BY "created_at" LIMIT $4 FOR UPDATE SKIP LOCKED`, [SWEEP_DELAY_SECONDS, options.retryAbandoned, MAX_START_ATTEMPTS, SWEEP_BATCH]);
539
+ yield* lease(sql, rows);
540
+ return rows;
541
+ }));
542
+ if (selected.length === 0) {
543
+ break;
404
544
  }
405
- return rows;
406
- }));
407
- if (selected.length > 0 && starter === undefined) {
408
- return yield* Effect.die(new Error("The sweep needs the ontology service's starter."));
409
- }
410
- const attempted = selected.length === 0
411
- ? { started: [], failed: [] }
412
- : yield* attempt(starter, selected.map(pendingOf));
413
- // Provider submission is outside the lease transaction. Concurrent/reclaimed attempts use the
414
- // same persisted reservation rather than generating another provider run.
415
- yield* record(sql, attempted, options.requestId);
545
+ if (starter === undefined) {
546
+ return yield* Effect.die(new Error("The sweep needs the ontology service's starter."));
547
+ }
548
+ const attempted = yield* attempt(starter, selected.map(pendingOf), until);
549
+ // Provider submission is outside the lease transaction. Concurrent/reclaimed attempts use
550
+ // the same persisted reservation rather than generating another provider run.
551
+ // A row whose start failed keeps its lease, which outlasts the sweep's deadline, so that it
552
+ // waits for the recovery run's next, later sweep, as without a deadline.
553
+ yield* record(sql, attempted, options.requestId, until !== undefined);
554
+ started += attempted.started.length;
555
+ failed += attempted.failed.length;
556
+ if (attempted.deferred.length > 0) {
557
+ break;
558
+ }
559
+ } while (until !== undefined && clock() < until.deadline);
416
560
  yield* sql.unsafe(`DELETE FROM "${WORKFLOW_STARTS_TABLE}" WHERE "run_id" IS NOT NULL ` +
417
561
  `AND "started_at" < now() - make_interval(days => $1)`, [STARTED_RETENTION_DAYS]);
418
562
  const [left] = yield* sql.unsafe(`SELECT count(*) FILTER (WHERE "attempts" >= $1)::text AS "abandoned", ` +
@@ -420,14 +564,97 @@ export function sweepStarts(sql, starter, options) {
420
564
  `AND ($2::timestamptz IS NULL OR "created_at" < $2::timestamptz))::text AS "waiting", ` +
421
565
  `${SWEEP_CLOCK} AS "at" FROM "${WORKFLOW_STARTS_TABLE}" WHERE "run_id" IS NULL`, [MAX_START_ATTEMPTS, options.before ?? null]);
422
566
  return {
423
- started: attempted.started.length,
424
- failed: attempted.failed.length,
567
+ started,
568
+ failed,
425
569
  abandoned: Number(left?.abandoned ?? 0),
426
570
  waiting: Number(left?.waiting ?? 0),
427
571
  at: left?.at ?? new Date().toISOString(),
428
572
  };
429
573
  });
430
574
  }
575
+ /**
576
+ * The action id of an owner's cron start: derived from its trigger, minute and owner, so that a
577
+ * repeated delivery of the cron names the same row.
578
+ */
579
+ export function cronStartId(trigger, fireKey, ownerId) {
580
+ const hash = createHash("sha256").update(`${trigger}\n${fireKey}\n${ownerId}`).digest("hex");
581
+ return [
582
+ hash.slice(0, 8),
583
+ hash.slice(8, 12),
584
+ `5${hash.slice(13, 16)}`,
585
+ `${((Number.parseInt(hash.slice(16, 17), 16) & 0x3) | 0x8).toString(16)}${hash.slice(17, 20)}`,
586
+ hash.slice(20, 32),
587
+ ].join("-");
588
+ }
589
+ /** Rows per INSERT of owned cron starts: thirteen parameters each. */
590
+ const OWNED_INSERT_CHUNK = 500;
591
+ /**
592
+ * Writes one pending row per owner, each in a statement of its own page, and answers how many were
593
+ * new. A row a repeated delivery of the cron already wrote is left as it is: the unique index on
594
+ * the trigger, the minute and the owner, and the derived action id, both name it.
595
+ */
596
+ export function insertOwnedCronStarts(sql, starts) {
597
+ return Effect.gen(function* () {
598
+ let written = 0;
599
+ for (let offset = 0; offset < starts.length; offset += OWNED_INSERT_CHUNK) {
600
+ const params = [];
601
+ const values = starts.slice(offset, offset + OWNED_INSERT_CHUNK).map((start) => {
602
+ params.push(start.trigger, cronStartId(start.trigger, start.fireKey, start.owner.id), start.workflow, JSON.stringify(start.input), process.env.VERCEL_DEPLOYMENT_ID ?? null, start.workflowId, JSON.stringify(encodeWorkflowArguments(start.arguments)), JSON.stringify(start.attributes), start.owner.entity, start.owner.id, start.owner.call, start.fireKey);
603
+ const at = params.length - 12;
604
+ return (`($${at + 1}, $${at + 2}::uuid, NULL, $${at + 3}, $${at + 4}::jsonb, $${at + 5}, ` +
605
+ `$${at + 6}, $${at + 7}::jsonb, $${at + 8}::jsonb, $${at + 9}, $${at + 10}, ` +
606
+ `$${at + 11}, $${at + 12})`);
607
+ });
608
+ const inserted = yield* sql.unsafe(`INSERT INTO "${WORKFLOW_STARTS_TABLE}" ("trigger", "action_id", "record_id", "workflow", ` +
609
+ `"input", admission_deployment_id, provider_workflow_id, arguments, admission_attributes, ` +
610
+ `"owner_entity", "owner_id", "owner_call", "fire_key") VALUES ${values.join(", ")} ` +
611
+ `ON CONFLICT DO NOTHING RETURNING "trigger"`, params);
612
+ written += inserted.length;
613
+ }
614
+ return written;
615
+ });
616
+ }
617
+ /**
618
+ * Starts the pending rows one cron fire wrote, {@link SWEEP_BATCH} at a time, until none is left
619
+ * or `deadline` (epoch ms) passes: the cron's request starts what it can, and the recovery run it
620
+ * armed starts the rest. Rows are leased as the sweep leases them, so a sweep or a repeated
621
+ * delivery never starts the same row at the same time, and the starter's reservation keeps a
622
+ * retried start to one run. One owner's failed start is recorded on its row and stops no other; a
623
+ * row whose start failed once is left to the recovery run's growing delays.
624
+ */
625
+ export function startFiredStarts(sql, starter, input) {
626
+ return Effect.gen(function* () {
627
+ const clock = input.clock ?? Date.now;
628
+ let started = 0;
629
+ let failed = 0;
630
+ while (clock() < input.deadline) {
631
+ const selected = yield* sql.withTransaction(Effect.gen(function* () {
632
+ const rows = yield* sql.unsafe(`SELECT ${startColumns(true)} FROM "${WORKFLOW_STARTS_TABLE}" ` +
633
+ `WHERE "trigger" = $1 AND "fire_key" = $2 AND "run_id" IS NULL ` +
634
+ `AND (submission_lease_until IS NULL OR submission_lease_until < clock_timestamp()) ` +
635
+ `AND "attempts" = 0 ORDER BY "owner_id" LIMIT $3 FOR UPDATE SKIP LOCKED`, [input.trigger, input.fireKey, SWEEP_BATCH]);
636
+ yield* lease(sql, rows);
637
+ return rows;
638
+ }));
639
+ if (selected.length === 0) {
640
+ break;
641
+ }
642
+ const attempted = yield* attempt(starter, selected.map(pendingOf), {
643
+ deadline: input.deadline,
644
+ clock,
645
+ });
646
+ yield* record(sql, attempted, input.requestId);
647
+ started += attempted.started.length;
648
+ failed += attempted.failed.length;
649
+ if (attempted.deferred.length > 0) {
650
+ break;
651
+ }
652
+ }
653
+ const [left] = yield* sql.unsafe(`SELECT count(*)::text AS "pending" FROM "${WORKFLOW_STARTS_TABLE}" ` +
654
+ `WHERE "trigger" = $1 AND "fire_key" = $2 AND "run_id" IS NULL`, [input.trigger, input.fireKey]);
655
+ return { started, failed, pending: Number(left?.pending ?? 0) };
656
+ });
657
+ }
431
658
  /** The starts listing's cursor does not decode: it was not one this listing gave. */
432
659
  export class InvalidStartsCursor extends Schema.TaggedError()("InvalidStartsCursor", { message: Schema.String }) {
433
660
  }
@@ -1,14 +1,15 @@
1
1
  import { PermissionDenied } from "../../errors.js";
2
- import { consumeChatEnvelope } from "../chat/envelope.js";
2
+ import { consumeChatEnvelope, nestedEnvelopeIssues } from "../chat/envelope.js";
3
3
  import { Cause, Effect, Layer, Result, Schema } from "effect";
4
4
  import { HttpRouter, HttpServerResponse } from "effect/unstable/http";
5
5
  import { ATTACHMENT_SOURCES, } from "../../storage/attachments.js";
6
6
  import { schemaIssues } from "../../runtime/validation.js";
7
7
  import { CurrentPrincipal } from "../authentication.js";
8
+ import { CurrentCaller } from "../caller-context.js";
8
9
  import { RequestId, errorBodyForWire, failureResponse } from "../errors.js";
9
10
  import { identityToken, makeOperations } from "../operations.js";
10
11
  import { OntologyBackend } from "../runtime-contract.js";
11
- import { authenticateAgentCaller } from "./authentication.js";
12
+ import { authenticateAgentCaller, runtimeActingMember } from "./authentication.js";
12
13
  import { checkRuntimeOperation } from "../mcp/runtime-policy.js";
13
14
  import { AGENT_PATH } from "./server.js";
14
15
  export { CHAT_HEADER, SESSION_HEADER } from "./authentication.js";
@@ -171,11 +172,19 @@ export function attachmentsLayer(options) {
171
172
  return invalidBody(requestId, body.issues);
172
173
  }
173
174
  const promotion = body.value;
174
- const metadata = yield* consumeChatEnvelope(promotion._meta ?? {}, {
175
+ // The chat's provenance comes only from `_meta`, never from the action's input.
176
+ const nested = nestedEnvelopeIssues(promotion.input);
177
+ if (nested.length > 0) {
178
+ return invalidBody(requestId, nested);
179
+ }
180
+ // The credential that authenticated: the app's own agent acting for the member, or
181
+ // an API key with delegation, which `delegatedBy` names.
182
+ const verified = {
175
183
  kind: "runtime",
176
184
  subjectId: caller.principal.id,
177
185
  ...(caller.delegatedBy === undefined ? {} : { delegatedBy: caller.delegatedBy }),
178
- });
186
+ };
187
+ const metadata = yield* consumeChatEnvelope(promotion._meta ?? {}, verified);
179
188
  const attachmentId = yield* idOf;
180
189
  const envelopeSource = metadata.envelope?.source;
181
190
  // Only a Telegram source names the provider files a message carried.
@@ -198,6 +207,14 @@ export function attachmentsLayer(options) {
198
207
  message: "Runtime attachment provenance requires a current channel pairing.",
199
208
  });
200
209
  }
210
+ // The action runs with the verified caller only for a member reached as on every
211
+ // other agent route: the sender `_meta` names, the member a key with delegation acts
212
+ // through, or one paired with the agent or reached through their web grant. A member
213
+ // this file route admits without a pairing runs it with none, so an owned connection
214
+ // selects no credential for them.
215
+ const acting = source !== undefined ||
216
+ caller.delegatedBy !== undefined ||
217
+ (yield* runtimeActingMember(request, agents))?.id === caller.principal.id;
201
218
  // This file route permits unpaired members; do not grant posting provenance.
202
219
  // It is nevertheless a verified runtime path and cannot invoke the agent.
203
220
  yield* checkRuntimeOperation({ kind: "runtime", subjectId: caller.principal.id }, promotion);
@@ -214,8 +231,9 @@ export function attachmentsLayer(options) {
214
231
  return yield* Effect.die(new Error("The promotion's action was not planned."));
215
232
  }
216
233
  // The action runs as the member, with the after-commit hooks and connections
217
- // of any other call.
218
- const answer = yield* operations
234
+ // of any other call: an owned connection selects the member's credential only
235
+ // for the app's own agent acting for them, never for a key with delegation.
236
+ const run = operations
219
237
  .runAction(planned, action, {
220
238
  input: call.input,
221
239
  ...(source === undefined ? {} : { runtime: { source } }),
@@ -224,6 +242,9 @@ export function attachmentsLayer(options) {
224
242
  identityToken: identityToken(request),
225
243
  })
226
244
  .pipe(Effect.provideService(CurrentPrincipal, principal), Effect.provideService(RequestId, requestId));
245
+ const answer = yield* acting
246
+ ? Effect.provideService(run, CurrentCaller, verified)
247
+ : run;
227
248
  return { result: answer.result, edits: answer.edits };
228
249
  }));
229
250
  return json({
@@ -33,6 +33,11 @@ export declare function authenticateAgentCaller(input: {
33
33
  * store without web grants. A guest is admitted only where the caller says so.
34
34
  */
35
35
  export declare function webMember(agents: AgentStore, userId: string, grantId: string): Effect.Effect<Principal | undefined>;
36
+ /**
37
+ * The member the runtime acts for: a web member by the grant their agent token stands for, anyone
38
+ * else by their pairing with the agent. `undefined` when the headers name nobody admitted.
39
+ */
40
+ export declare function runtimeActingMember(request: HttpServerRequest.HttpServerRequest, agents: AgentStore): Effect.Effect<Principal | undefined>;
36
41
  /**
37
42
  * Authenticate the deployment's own runtime acting for the member `X-SegmentStream-Act-As` names,
38
43
  * on a route only that runtime calls: an API key, with delegation or not, and a task's secret are
@@ -82,7 +82,7 @@ export function webMember(agents, userId, grantId) {
82
82
  * The member the runtime acts for: a web member by the grant their agent token stands for, anyone
83
83
  * else by their pairing with the agent. `undefined` when the headers name nobody admitted.
84
84
  */
85
- function runtimeActingMember(request, agents) {
85
+ export function runtimeActingMember(request, agents) {
86
86
  const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
87
87
  const grant = request.headers[AGENT_GRANT_HEADER]?.trim() ?? "";
88
88
  if (actAs === "") {
@@ -13,8 +13,10 @@ export type AgentTaskCaller = {
13
13
  readonly detail: string;
14
14
  };
15
15
  /**
16
- * The live task a secret names and the user it acts as: its workflow's user, resolved as the
17
- * workflow's steps resolve it, with the roles it holds now. Refused when the secret matches no live
16
+ * The live task a secret names and the user it acts as: its workflow's user, resolved as the steps
17
+ * of a run with no owner resolve it, with the roles it holds now. A task a step of an owned run
18
+ * starts acts as the workflow's user too, never as the run's owner, so its owned connection calls
19
+ * fail with `owner_required` (docs/agent-tasks-spec.md, decision 2). Refused when the secret matches no live
18
20
  * task (an unknown secret, a terminal task or one past its deadline) or the workflow user is
19
21
  * missing or inactive. The ontology resolves the identity from the task; the caller never names it.
20
22
  */
@@ -4,8 +4,10 @@ import { taskSecretSha256 } from "./task-start.js";
4
4
  /** How a principal that a task's secret authenticated says it authenticated. */
5
5
  export const AGENT_TASK_AUTHENTICATION = "agent_task";
6
6
  /**
7
- * The live task a secret names and the user it acts as: its workflow's user, resolved as the
8
- * workflow's steps resolve it, with the roles it holds now. Refused when the secret matches no live
7
+ * The live task a secret names and the user it acts as: its workflow's user, resolved as the steps
8
+ * of a run with no owner resolve it, with the roles it holds now. A task a step of an owned run
9
+ * starts acts as the workflow's user too, never as the run's owner, so its owned connection calls
10
+ * fail with `owner_required` (docs/agent-tasks-spec.md, decision 2). Refused when the secret matches no live
9
11
  * task (an unknown secret, a terminal task or one past its deadline) or the workflow user is
10
12
  * missing or inactive. The ontology resolves the identity from the task; the caller never names it.
11
13
  */
@@ -163,6 +163,13 @@ export declare function neonAuthSessionExchange(config: {
163
163
  * with same-origin `POST`s, so a change without one is refused too.
164
164
  */
165
165
  export declare function sessionMayAuthenticate(request: HttpServerRequest.HttpServerRequest): boolean;
166
+ /**
167
+ * Whether a browser sent this request from another site: it names an origin other than the app's
168
+ * own, or Fetch Metadata says it is not same-origin. A server-side caller sends neither header.
169
+ * Routes that change something without a credential refuse such a request, as the session cookie
170
+ * is refused on one ({@link sessionMayAuthenticate}).
171
+ */
172
+ export declare function crossSiteRequest(request: HttpServerRequest.HttpServerRequest): boolean;
166
173
  type Authenticated = {
167
174
  readonly status: "authenticated";
168
175
  readonly principal: Principal;
@@ -452,6 +452,18 @@ export function sessionMayAuthenticate(request) {
452
452
  const origin = request.headers.origin;
453
453
  return origin !== undefined && origin === requestOrigin(request);
454
454
  }
455
+ /**
456
+ * Whether a browser sent this request from another site: it names an origin other than the app's
457
+ * own, or Fetch Metadata says it is not same-origin. A server-side caller sends neither header.
458
+ * Routes that change something without a credential refuse such a request, as the session cookie
459
+ * is refused on one ({@link sessionMayAuthenticate}).
460
+ */
461
+ export function crossSiteRequest(request) {
462
+ const site = request.headers["sec-fetch-site"];
463
+ const origin = request.headers.origin;
464
+ return ((site !== undefined && site !== "same-origin" && site !== "none") ||
465
+ (origin !== undefined && origin !== requestOrigin(request)));
466
+ }
455
467
  /**
456
468
  * The chat a verified runtime caller names, kept as the principal's when it can be the chat it acts
457
469
  * in: on the web, the member's or guest's own chat, which their agent token names; on a messenger,