@operad-io/engine 0.1.0 → 0.2.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 (80) hide show
  1. package/config.schema.json +2 -1
  2. package/package.json +1 -1
  3. package/src/config/config.ts +74 -45
  4. package/src/flow/types.ts +4 -0
  5. package/src/flow/validate.ts +5 -0
  6. package/src/http/index.ts +2 -0
  7. package/src/http/plugins.ts +66 -0
  8. package/src/http/server.ts +342 -48
  9. package/src/kernel/decide.ts +115 -30
  10. package/src/kernel/state.ts +9 -0
  11. package/src/kernel/types.ts +25 -40
  12. package/src/log/open-log.ts +2 -5
  13. package/src/log/sqlite.ts +127 -85
  14. package/src/log/types.ts +35 -9
  15. package/src/loop/code-watch.ts +108 -2
  16. package/src/loop/older-code.ts +3 -4
  17. package/src/loop/serve.ts +122 -95
  18. package/src/notify/notify.ts +2 -6
  19. package/src/platform/atomic-write.ts +163 -0
  20. package/src/platform/file-lock.ts +43 -21
  21. package/src/platform/index.ts +2 -0
  22. package/src/platform/kept-workers.ts +290 -0
  23. package/src/platform/process-group.ts +11 -3
  24. package/src/platform/sqlite-open.ts +20 -6
  25. package/src/platform/sqlite-schema.ts +30 -0
  26. package/src/platform/step-reap.ts +33 -18
  27. package/src/platform/watch.ts +1 -11
  28. package/src/plugin/action-schema.ts +59 -1
  29. package/src/plugin/choice-info.ts +133 -0
  30. package/src/plugin/context.ts +279 -0
  31. package/src/plugin/declared-flows.ts +3 -10
  32. package/src/plugin/errors.ts +9 -0
  33. package/src/plugin/freeze.ts +12 -0
  34. package/src/plugin/harness.ts +28 -0
  35. package/src/plugin/index.ts +8 -7
  36. package/src/plugin/install.ts +265 -17
  37. package/src/plugin/keys.ts +2 -12
  38. package/src/plugin/load.ts +47 -23
  39. package/src/plugin/logger.ts +14 -0
  40. package/src/plugin/open-store.ts +0 -6
  41. package/src/plugin/question-form.ts +323 -0
  42. package/src/plugin/registry.ts +512 -76
  43. package/src/plugin/secrets.ts +14 -24
  44. package/src/plugin/semver.ts +52 -0
  45. package/src/plugin/settings.ts +1 -9
  46. package/src/plugin/sqlite-store.ts +94 -64
  47. package/src/plugin/store.ts +5 -0
  48. package/src/plugin/types.ts +566 -21
  49. package/src/plugin/validate.ts +396 -26
  50. package/src/runner/answer.ts +26 -68
  51. package/src/runner/ask.ts +227 -28
  52. package/src/runner/cancel.ts +10 -7
  53. package/src/runner/grants.ts +2 -2
  54. package/src/runner/index.ts +1 -3
  55. package/src/runner/limits.ts +2 -2
  56. package/src/runner/runner.ts +15 -14
  57. package/src/runner/service.ts +52 -19
  58. package/src/runner/step-worker.ts +9 -0
  59. package/src/testing/answer.ts +69 -0
  60. package/src/testing/clock-manual.ts +152 -0
  61. package/src/testing/config.ts +16 -0
  62. package/src/testing/fs.ts +172 -0
  63. package/src/testing/home.ts +43 -0
  64. package/src/testing/index.ts +19 -0
  65. package/src/testing/types.ts +2 -0
  66. package/src/testing/world.ts +9 -2
  67. package/src/trigger/kernel.ts +13 -46
  68. package/src/trigger/rules.ts +22 -12
  69. package/src/trigger/types.ts +2 -6
  70. package/src/util.ts +99 -0
  71. package/src/views/event-line.ts +22 -0
  72. package/src/views/history.ts +36 -19
  73. package/src/views/live-logs.ts +313 -0
  74. package/src/views/pending.ts +23 -5
  75. package/src/views/presentation.ts +629 -81
  76. package/src/views/running.ts +5 -5
  77. package/src/views/settings.ts +205 -66
  78. package/src/views/types.ts +3 -2
  79. package/src/views/uploads.ts +15 -7
  80. package/triggers.schema.json +4 -0
@@ -6,16 +6,19 @@
6
6
 
7
7
  import { readFileSync } from "node:fs";
8
8
  import { objectLink } from "../http/link.ts";
9
- import type { LogBackend } from "../log/types.ts";
9
+ import type { LogBackend, RunInfo } from "../log/types.ts";
10
10
  import {
11
11
  followsChanges,
12
- type FollowOptions,
12
+ resolveSubscriptionWatch,
13
+ type SubscriptionWatchOptions,
13
14
  } from "../platform/index.ts";
14
15
  import { runTimes } from "./running.ts";
15
16
  import type { PluginRegistry, ActionInfo } from "../plugin/registry.ts";
16
17
  import { rankOf, sortByRank, splitActionName } from "../plugin/registry.ts";
17
18
  import { messageOf } from "../plugin/errors.ts";
18
19
  import { createPluginLogger } from "../plugin/logger.ts";
20
+ import { LiveLogWatch } from "./live-logs.ts";
21
+ import { fitsEventLine } from "./event-line.ts";
19
22
  import { FileSecretStore } from "../plugin/secrets.ts";
20
23
  import {
21
24
  assertWhere,
@@ -29,10 +32,11 @@ import {
29
32
  } from "../plugin/paging.ts";
30
33
  import { ALL_FILTER, filterShows, typeFilters, type TypeFilter } from "../plugin/filters.ts";
31
34
  import { ActionArgsError, fileProperties, noteProperty, validateActionArgs } from "../plugin/action-schema.ts";
32
- import { attachmentDir, UploadMissingError, Uploads } from "./uploads.ts";
35
+ import { attachmentDir, findAttachment, UploadMissingError, Uploads } from "./uploads.ts";
33
36
  import type {
34
37
  ActionTypeDefinition,
35
38
  Actor,
39
+ AskQuestionAnswer,
36
40
  FactWriter,
37
41
  FactsOptions,
38
42
  FactsPage,
@@ -43,10 +47,14 @@ import type {
43
47
  PluginStore,
44
48
  StoredObject,
45
49
  RowMark,
50
+ SectionRetry,
51
+ SectionStatus,
46
52
  ViewContext,
53
+ ViewSkill,
47
54
  } from "../plugin/types.ts";
48
55
  import { ROW_BADGE_MAX, ROW_MARKS } from "../plugin/types.ts";
49
56
  import {
57
+ historyEntry,
50
58
  localMinute,
51
59
  runHistoryLines,
52
60
  type HistoryFact,
@@ -62,7 +70,7 @@ import {
62
70
  type SettingInfo,
63
71
  type SettingsOptions,
64
72
  } from "./settings.ts";
65
- import { isRecord } from "../util.ts";
73
+ import { bareId, isRecord, objectKey, parseObjectId } from "../util.ts";
66
74
  import { configPath } from "../config/config.ts";
67
75
  import { prepareSettings } from "../plugin/settings.ts";
68
76
  import type { JsonValue } from "../log/types.ts";
@@ -89,6 +97,13 @@ export const DEFAULT_MAX_EVENT_IDS = 1024;
89
97
  */
90
98
  export const GROWTH_EVENT_INTERVAL_MS = 250;
91
99
 
100
+ /**
101
+ * How often one object's live part is pushed. A live part is sent as its own
102
+ * event so a client can render it without reading the section again; the
103
+ * change event keeps its own, slower window.
104
+ */
105
+ const LIVE_PUSH_INTERVAL_MS = 50;
106
+
92
107
  /** A row as a client sees it: the plugin's row plus the kernel's two flags. */
93
108
  export interface ViewRow {
94
109
  readonly id: string;
@@ -113,6 +128,8 @@ export interface ViewRow {
113
128
  readonly waiting: boolean;
114
129
  /** The object's run is working. */
115
130
  readonly running: boolean;
131
+ /** Structured data the plugin defines for its clients, passed through unchanged. */
132
+ readonly data?: Readonly<Record<string, JsonValue>> | undefined;
116
133
  /** Set when the plugin's `row` failed; the row is then an error row. */
117
134
  readonly error?: string | undefined;
118
135
  }
@@ -130,6 +147,15 @@ export interface ViewAction extends ActionInfo {
130
147
  readonly key?: string | undefined;
131
148
  }
132
149
 
150
+ /** How a run ended: the outcome, the reason line of a failure, and when. */
151
+ export interface ViewRunEnd {
152
+ readonly outcome: "done" | "failed" | "cancelled";
153
+ /** The reason the run recorded; left out when it recorded none. */
154
+ readonly reason?: string | undefined;
155
+ /** When the run ended, in milliseconds since the epoch. */
156
+ readonly endedAt: number;
157
+ }
158
+
133
159
  /** What `get` returns: a row, the section directory and the actions. */
134
160
  export interface ViewObject {
135
161
  readonly id: string;
@@ -139,10 +165,22 @@ export interface ViewObject {
139
165
  readonly row: ViewRow;
140
166
  readonly sections: readonly ViewSectionInfo[];
141
167
  readonly actions: readonly ViewAction[];
168
+ /** The skills this object offers as `/name` commands, such as a chat's. */
169
+ readonly skills?: readonly ViewSkill[] | undefined;
142
170
  /** Set when the object's plugin is no longer loaded. */
143
171
  readonly unavailable?: string | undefined;
172
+ /** How the object's newest run ended; absent when it has no run or that run is still going. */
173
+ readonly lastRun?: ViewRunEnd | undefined;
144
174
  /** The ids of the objects of this type whose row has this one in `after`. */
145
175
  readonly dependents?: readonly string[] | undefined;
176
+ /** Numbers the plugin shows beside the row, such as a chat's context usage. */
177
+ readonly context?:
178
+ | {
179
+ readonly used: number;
180
+ readonly window?: number | undefined;
181
+ readonly model?: string | undefined;
182
+ }
183
+ | undefined;
146
184
  }
147
185
 
148
186
  /** What one section read returns. */
@@ -161,6 +199,23 @@ export interface ViewSectionContent {
161
199
  * cap never cuts it; it shortens the finished page instead.
162
200
  */
163
201
  readonly tail?: string | undefined;
202
+ /**
203
+ * What the live section is doing now, passed through from the plugin. The
204
+ * kernel does not read it; a client that does not know it ignores it.
205
+ */
206
+ readonly status?: SectionStatus | undefined;
207
+ /** A model request the harness waits to try again, passed through from the plugin. */
208
+ readonly retry?: SectionRetry | undefined;
209
+ /** Numbers the plugin shows beside the section, such as a chat's context usage. */
210
+ readonly context?:
211
+ | {
212
+ readonly used: number;
213
+ readonly window?: number | undefined;
214
+ readonly model?: string | undefined;
215
+ }
216
+ | undefined;
217
+ /** Structured data the plugin defines for its clients, passed through unchanged. */
218
+ readonly data?: Readonly<Record<string, JsonValue>> | undefined;
164
219
  /**
165
220
  * Present on a read that asked with `after`: true when `markdown` holds only
166
221
  * what follows the mark, false when the plugin answered with a whole page
@@ -178,6 +233,18 @@ export interface ViewSectionPage {
178
233
  /** One change a client may react to. */
179
234
  export interface ViewEvent {
180
235
  readonly id: string;
236
+ /**
237
+ * The object type when this is a pushed tail event, with the live section's
238
+ * `section`, whole current `tail`, `status` and `data`. A tail event is not
239
+ * part of the resume window: a reconnecting client reads the section again.
240
+ * A client that does not know it ignores it.
241
+ */
242
+ readonly type?: string | undefined;
243
+ readonly section?: string | undefined;
244
+ readonly tail?: string | undefined;
245
+ readonly status?: SectionStatus | undefined;
246
+ readonly retry?: SectionRetry | undefined;
247
+ readonly data?: Readonly<Record<string, JsonValue>> | undefined;
181
248
  }
182
249
 
183
250
  /** Why a presentation call refused. */
@@ -193,6 +260,7 @@ export type ViewErrorKind =
193
260
  | "note"
194
261
  | "confirm"
195
262
  | "args"
263
+ | "refused"
196
264
  | "where"
197
265
  | "filter"
198
266
  | "cursor";
@@ -214,7 +282,7 @@ export class ViewError extends Error {
214
282
  }
215
283
  }
216
284
 
217
- export interface ViewsOptions extends FollowOptions {
285
+ export interface ViewsOptions extends SubscriptionWatchOptions {
218
286
  readonly registry: PluginRegistry;
219
287
  readonly store?: PluginStore | undefined;
220
288
  readonly log?: LogBackend | undefined;
@@ -258,7 +326,10 @@ export interface AnswerViewOptions {
258
326
  readonly runId: string;
259
327
  /** The wait id the pending item named. */
260
328
  readonly waitId: string;
261
- readonly choice: string;
329
+ /** The one choice a question of choices takes; absent for a form's answer. */
330
+ readonly choice: string | undefined;
331
+ /** The person's answer to each question, when the question was a form. */
332
+ readonly answers?: readonly AskQuestionAnswer[] | undefined;
262
333
  readonly note?: string | undefined;
263
334
  /** Confirms an action-backed choice whose action asks to confirm. */
264
335
  readonly confirmed?: boolean | undefined;
@@ -350,14 +421,57 @@ function textOf(value: unknown): string | undefined {
350
421
  return typeof value === "string" ? value : undefined;
351
422
  }
352
423
 
353
- function objectKey(type: string, id: string): string {
354
- return `${type}:${id}`;
424
+ /** A plugin's status object, passed through whole when its two fields are there. */
425
+ function statusOf(value: unknown): SectionStatus | undefined {
426
+ if (!isRecord(value)) return undefined;
427
+ const text = textOf(value.text);
428
+ const since = value.since;
429
+ if (text === undefined || typeof since !== "number" || !Number.isFinite(since)) return undefined;
430
+ return { text, since };
431
+ }
432
+
433
+ /** A plugin's retry item, passed through when every field is there and sound. */
434
+ function retryOf(value: unknown): SectionRetry | undefined {
435
+ if (!isRecord(value)) return undefined;
436
+ const attempt = value.attempt;
437
+ const maxAttempts = value.maxAttempts;
438
+ const until = value.until;
439
+ const reason = textOf(value.reason);
440
+ if (
441
+ typeof attempt !== "number" ||
442
+ !Number.isInteger(attempt) ||
443
+ attempt < 1 ||
444
+ typeof maxAttempts !== "number" ||
445
+ !Number.isInteger(maxAttempts) ||
446
+ maxAttempts < 1 ||
447
+ typeof until !== "number" ||
448
+ !Number.isFinite(until) ||
449
+ reason === undefined
450
+ ) {
451
+ return undefined;
452
+ }
453
+ return { attempt, maxAttempts, until, reason };
355
454
  }
356
455
 
357
- function splitId(id: string): { readonly type: string; readonly id: string } | undefined {
358
- const at = id.indexOf(":");
359
- if (at <= 0 || at === id.length - 1) return undefined;
360
- return { type: id.slice(0, at), id: id.slice(at + 1) };
456
+ /** A plugin's context numbers, passed through when `used` is a whole count. */
457
+ function contextOf(value: unknown):
458
+ | {
459
+ readonly used: number;
460
+ readonly window?: number | undefined;
461
+ readonly model?: string | undefined;
462
+ }
463
+ | undefined {
464
+ if (!isRecord(value)) return undefined;
465
+ const used = value.used;
466
+ if (typeof used !== "number" || !Number.isInteger(used) || used < 0) return undefined;
467
+ const window = value.window;
468
+ const knownWindow = typeof window === "number" && Number.isInteger(window) && window > 0 ? window : undefined;
469
+ const model = textOf(value.model);
470
+ return {
471
+ used,
472
+ ...(knownWindow === undefined ? {} : { window: knownWindow }),
473
+ ...(model === undefined || model.length === 0 ? {} : { model }),
474
+ };
361
475
  }
362
476
 
363
477
  function capBytes(markdown: string, limit: number): string {
@@ -452,18 +566,18 @@ interface RunFlags {
452
566
  readonly running: boolean;
453
567
  }
454
568
 
455
- /** A bounded, coalescing stream of ids. */
569
+ /** A bounded, coalescing stream of changes. */
456
570
  class EventStream implements AsyncIterable<ViewEvent> {
457
- private readonly pending = new Set<string>();
571
+ private readonly pending = new Map<string, ViewEvent>();
458
572
  private readonly max: number;
459
- private readonly listeners: Set<(id: string) => void>;
573
+ private readonly listeners: Set<(event: ViewEvent) => void>;
460
574
  private readonly flush: () => void;
461
575
  private closed = false;
462
576
  private resume: (() => void) | undefined;
463
577
 
464
578
  constructor(
465
579
  max: number,
466
- listeners: Set<(id: string) => void>,
580
+ listeners: Set<(event: ViewEvent) => void>,
467
581
  flush: () => void,
468
582
  ) {
469
583
  this.max = Math.max(1, max);
@@ -471,14 +585,19 @@ class EventStream implements AsyncIterable<ViewEvent> {
471
585
  this.flush = flush;
472
586
  }
473
587
 
474
- readonly listener = (id: string): void => {
588
+ readonly listener = (event: ViewEvent): void => {
475
589
  if (this.closed) return;
476
- if (this.pending.size >= this.max && !this.pending.has(id)) {
477
- const oldest = this.pending.values().next().value;
590
+ // A live push is its own event; a later change of the same object does not
591
+ // replace it, and a later live push replaces the earlier one.
592
+ const key = event.section === undefined
593
+ ? event.id
594
+ : `tail:${event.type}:${event.id}`;
595
+ if (this.pending.size >= this.max && !this.pending.has(key)) {
596
+ const oldest = this.pending.keys().next().value;
478
597
  if (oldest !== undefined) this.pending.delete(oldest);
479
598
  }
480
- this.pending.delete(id);
481
- this.pending.add(id);
599
+ this.pending.delete(key);
600
+ this.pending.set(key, event);
482
601
  this.wake();
483
602
  };
484
603
 
@@ -501,10 +620,11 @@ class EventStream implements AsyncIterable<ViewEvent> {
501
620
  });
502
621
  }
503
622
  if (this.closed) return { done: true, value: undefined };
504
- const id = this.pending.values().next().value;
505
- if (id === undefined) return { done: false, value: { id: "" } };
506
- this.pending.delete(id);
507
- return { done: false, value: { id } };
623
+ const found = this.pending.entries().next().value;
624
+ if (found === undefined) return { done: false, value: { id: "" } };
625
+ const [key, event] = found;
626
+ this.pending.delete(key);
627
+ return { done: false, value: event };
508
628
  }
509
629
 
510
630
  private stop(): IteratorResult<ViewEvent> {
@@ -580,14 +700,28 @@ export class Views {
580
700
  private readonly onLog: (message: string) => void;
581
701
  private readonly home: string;
582
702
  private readonly uploads: Uploads;
583
- private readonly eventListeners = new Set<(id: string) => void>();
703
+ private readonly eventListeners = new Set<(event: ViewEvent) => void>();
584
704
  /** When each object's live growth was last announced, for the rate limit. */
585
705
  private readonly growthAnnouncedAt = new Map<string, number>();
586
706
  /** Objects whose growth was held back in the current rate window. */
587
707
  private readonly growthPending = new Set<string>();
588
708
  /** The timer that announces an object when its rate window ends. */
589
709
  private readonly growthTimers = new Map<string, ReturnType<typeof setTimeout>>();
710
+ /** The same window for a live section's pushed part, keyed by type and id. */
711
+ private readonly liveAnnouncedAt = new Map<string, number>();
712
+ private readonly livePending = new Map<string, ObjectRef>();
713
+ private readonly liveTimers = new Map<string, ReturnType<typeof setTimeout>>();
714
+ private readonly liveGenerations = new Map<string, number>();
715
+ /** The section of the last tail an object pushed, so an empty tail can clear it. */
716
+ private readonly liveSections = new Map<string, string>();
717
+ private closed = false;
718
+ /** How the newest ended run of an object ended, keyed by its run and last fact. */
719
+ private readonly lastRunEnds = new Map<
720
+ string,
721
+ { readonly runId: string; readonly lastSeq: number; readonly end: ViewRunEnd | undefined }
722
+ >();
590
723
  private readonly unsubscribe: (() => void)[] = [];
724
+ private readonly liveLogs: LiveLogWatch | undefined = undefined;
591
725
  private candidateSource: CandidateSource | undefined;
592
726
  private preparing: Promise<void> | undefined;
593
727
 
@@ -608,9 +742,10 @@ export class Views {
608
742
  this.uploads = new Uploads({ home: this.home, clock: this.clock });
609
743
 
610
744
  if (followsChanges(options)) {
745
+ const subscriptionWatch = resolveSubscriptionWatch(options);
611
746
  if (typeof this.store.subscribe === "function") {
612
747
  this.unsubscribe.push(
613
- this.store.subscribe((object) => this.publish(object.id)),
748
+ this.store.subscribe((object) => this.publish(object)),
614
749
  );
615
750
  }
616
751
  if (typeof this.log?.subscribe === "function") {
@@ -618,13 +753,30 @@ export class Views {
618
753
  this.log.subscribe((change) => {
619
754
  const parsed = change.object === undefined
620
755
  ? undefined
621
- : splitId(change.object);
756
+ : parseObjectId(change.object);
622
757
  if (parsed === undefined) return;
623
758
  if (parsed.type === "flow") return;
624
- this.publish(parsed.id, true);
759
+ this.publish(parsed, true);
760
+ // A step appends to its log between facts; look for a new run's log.
761
+ void this.liveLogs?.sync();
625
762
  }),
626
763
  );
627
764
  }
765
+ const log = this.log;
766
+ this.liveLogs =
767
+ log === undefined
768
+ ? undefined
769
+ : new LiveLogWatch({
770
+ storeRoot: this.store.root,
771
+ registry: this.registry,
772
+ store: this.store,
773
+ log,
774
+ watch: subscriptionWatch.watch,
775
+ repeat: subscriptionWatch.repeat,
776
+ pollMs: subscriptionWatch.pollMs,
777
+ onGrowth: (object) => this.publish(object, true),
778
+ onLog: this.onLog,
779
+ });
628
780
  }
629
781
  }
630
782
 
@@ -699,11 +851,20 @@ export class Views {
699
851
 
700
852
  /** Closes the change listeners this view opened. */
701
853
  close(): void {
854
+ this.closed = true;
855
+ this.liveLogs?.close();
702
856
  for (const unsubscribe of this.unsubscribe.splice(0)) unsubscribe();
703
857
  for (const timer of this.growthTimers.values()) clearTimeout(timer);
704
858
  this.growthTimers.clear();
705
859
  this.growthPending.clear();
706
860
  this.growthAnnouncedAt.clear();
861
+ for (const timer of this.liveTimers.values()) clearTimeout(timer);
862
+ this.liveTimers.clear();
863
+ this.livePending.clear();
864
+ this.liveAnnouncedAt.clear();
865
+ this.liveGenerations.clear();
866
+ this.liveSections.clear();
867
+ this.lastRunEnds.clear();
707
868
  }
708
869
 
709
870
  /** The filter a list of this type uses when the caller names none. */
@@ -1154,6 +1315,46 @@ export class Views {
1154
1315
  return this.store.facts({ type: resolved.type, id: resolved.id }, options);
1155
1316
  }
1156
1317
 
1318
+ /**
1319
+ * The file a `/v1/attachments/<rel>` request may serve. A type that declares
1320
+ * `file` serves only what its records name; every other type keeps the
1321
+ * attachment directories' own bounds. The name and type come from the file
1322
+ * itself, and a link out of the root is still refused.
1323
+ */
1324
+ async file(
1325
+ rel: readonly string[],
1326
+ ): Promise<
1327
+ { readonly path: string; readonly type: string; readonly name: string } | undefined
1328
+ > {
1329
+ const type = rel[0];
1330
+ const id = rel[1];
1331
+ if (type !== undefined && id !== undefined) {
1332
+ const owner = this.registry.viewsFor(type);
1333
+ if (owner?.views.file !== undefined) {
1334
+ let object: StoredObject | undefined;
1335
+ try {
1336
+ object = await this.store.get(type, id);
1337
+ } catch (error) {
1338
+ this.onLog(`plugin "${owner.plugin}": file lookup for "${type}:${id}" failed: ${messageOf(error)}`);
1339
+ return undefined;
1340
+ }
1341
+ if (object === undefined) return undefined;
1342
+ try {
1343
+ const allowed = await owner.views.file(
1344
+ this.viewContext(owner.plugin, new AbortController().signal),
1345
+ object,
1346
+ rel.slice(2),
1347
+ );
1348
+ if (allowed !== true) return undefined;
1349
+ } catch (error) {
1350
+ this.onLog(`plugin "${owner.plugin}": file check for "${type}:${id}" failed: ${messageOf(error)}`);
1351
+ return undefined;
1352
+ }
1353
+ }
1354
+ }
1355
+ return findAttachment(this.home, rel);
1356
+ }
1357
+
1157
1358
  /** One object: its row, its section directory and the actions available now. */
1158
1359
  async get(id: string): Promise<ViewObject> {
1159
1360
  const resolved = await this.resolve(id);
@@ -1179,6 +1380,14 @@ export class Views {
1179
1380
  const actions: ViewAction[] = [];
1180
1381
  let unavailable: string | undefined;
1181
1382
  let dependents: readonly string[] = [];
1383
+ let skills: readonly ViewSkill[] | undefined;
1384
+ let context:
1385
+ | {
1386
+ readonly used: number;
1387
+ readonly window?: number | undefined;
1388
+ readonly model?: string | undefined;
1389
+ }
1390
+ | undefined;
1182
1391
 
1183
1392
  if (owner !== undefined && object !== undefined) {
1184
1393
  const { scope, ...guarded } = this.guardedRow(
@@ -1195,6 +1404,32 @@ export class Views {
1195
1404
  );
1196
1405
  sections = [];
1197
1406
  }
1407
+ if (owner.views.context !== undefined) {
1408
+ try {
1409
+ context = contextOf(
1410
+ await owner.views.context(
1411
+ this.viewContext(owner.plugin, new AbortController().signal),
1412
+ object,
1413
+ ),
1414
+ );
1415
+ } catch (error) {
1416
+ this.onLog(
1417
+ `plugin "${owner.plugin}": context failed for "${resolved.type}:${resolved.id}": ${messageOf(error)}`,
1418
+ );
1419
+ }
1420
+ }
1421
+ if (owner.views.skills !== undefined) {
1422
+ try {
1423
+ skills = await owner.views.skills(
1424
+ this.viewContext(owner.plugin, new AbortController().signal),
1425
+ object,
1426
+ );
1427
+ } catch (error) {
1428
+ this.onLog(
1429
+ `plugin "${owner.plugin}": skills failed for "${resolved.type}:${resolved.id}": ${messageOf(error)}`,
1430
+ );
1431
+ }
1432
+ }
1198
1433
  actions.push(...(await this.availableActions(resolved.type, object)));
1199
1434
  dependents = await this.dependentsOf(owner.plugin, resolved.type, row.id, scope);
1200
1435
  } else {
@@ -1211,6 +1446,7 @@ export class Views {
1211
1446
 
1212
1447
  sections = sections.filter((section) => section.id !== HISTORY_SECTION);
1213
1448
  sections.push({ id: HISTORY_SECTION, title: "History" });
1449
+ const lastRun = await this.lastRunEnd(resolved.type, resolved.id);
1214
1450
 
1215
1451
  return {
1216
1452
  id: resolved.id,
@@ -1219,8 +1455,11 @@ export class Views {
1219
1455
  row,
1220
1456
  sections,
1221
1457
  actions,
1458
+ ...(skills === undefined ? {} : { skills }),
1222
1459
  ...(unavailable === undefined ? {} : { unavailable }),
1460
+ ...(lastRun === undefined ? {} : { lastRun }),
1223
1461
  ...(dependents.length === 0 ? {} : { dependents }),
1462
+ ...(context === undefined ? {} : { context }),
1224
1463
  };
1225
1464
  }
1226
1465
 
@@ -1278,6 +1517,9 @@ export class Views {
1278
1517
  undefined,
1279
1518
  undefined,
1280
1519
  undefined,
1520
+ undefined,
1521
+ undefined,
1522
+ undefined,
1281
1523
  options.full === true,
1282
1524
  after === undefined ? undefined : false,
1283
1525
  );
@@ -1327,6 +1569,7 @@ export class Views {
1327
1569
  owner.views.load(ctx, object, sectionId, {
1328
1570
  ...(cursor === undefined ? {} : { cursor }),
1329
1571
  ...(after === undefined ? {} : { after }),
1572
+ ...(options.full === true ? { full: true } : {}),
1330
1573
  }),
1331
1574
  );
1332
1575
  content = await Promise.race([work, timeout]);
@@ -1352,6 +1595,13 @@ export class Views {
1352
1595
  const pages = isRecord(content) ? pagesOf(content.pages) : undefined;
1353
1596
  const rawMark = isRecord(content) ? textOf(content.mark) : undefined;
1354
1597
  const tail = isRecord(content) ? textOf(content.tail) : undefined;
1598
+ const status = isRecord(content) ? statusOf(content.status) : undefined;
1599
+ const retry = isRecord(content) ? retryOf(content.retry) : undefined;
1600
+ const context = isRecord(content) ? contextOf(content.context) : undefined;
1601
+ const data =
1602
+ isRecord(content) && isRecord(content.data)
1603
+ ? (content.data as Readonly<Record<string, JsonValue>>)
1604
+ : undefined;
1355
1605
  // A plugin that ignored `after` answers with a whole page; only one that
1356
1606
  // says its answer is the delta may be appended to by a client.
1357
1607
  const honoured =
@@ -1367,18 +1617,26 @@ export class Views {
1367
1617
  next,
1368
1618
  mark,
1369
1619
  tail,
1620
+ status,
1621
+ retry,
1622
+ data,
1370
1623
  options.full === true,
1371
1624
  after === undefined ? undefined : honoured,
1372
1625
  );
1373
- return pages === undefined ? finished : { ...finished, pages };
1626
+ return pages === undefined
1627
+ ? { ...finished, ...(context === undefined ? {} : { context }) }
1628
+ : { ...finished, pages, ...(context === undefined ? {} : { context }) };
1374
1629
  }
1375
1630
 
1376
- /** An async stream of ids that changed. Repeated ids coalesce. */
1631
+ /** An async stream of changes. Repeated ids coalesce. */
1377
1632
  events(): AsyncIterable<ViewEvent> {
1378
1633
  return new EventStream(
1379
1634
  this.maxEventIds,
1380
1635
  this.eventListeners,
1381
- () => this.flushDueGrowth(),
1636
+ () => {
1637
+ this.flushDueGrowth();
1638
+ this.flushDueLive();
1639
+ },
1382
1640
  );
1383
1641
  }
1384
1642
 
@@ -1441,6 +1699,7 @@ export class Views {
1441
1699
  // action, so its note, confirmation and object update still happen.
1442
1700
  const throughAction =
1443
1701
  item !== undefined &&
1702
+ item.questions === undefined &&
1444
1703
  item.choices.every((name) =>
1445
1704
  item.actions.some((action) => action.action === name),
1446
1705
  )
@@ -1470,6 +1729,7 @@ export class Views {
1470
1729
  runId: options.runId,
1471
1730
  waitId: options.waitId,
1472
1731
  choice: options.choice,
1732
+ ...(options.answers === undefined ? {} : { answers: options.answers }),
1473
1733
  ...(options.note === undefined ? {} : { note: options.note }),
1474
1734
  actor: options.actor,
1475
1735
  });
@@ -1521,15 +1781,21 @@ export class Views {
1521
1781
  `action "${name}" needs an actor: { via, id } says who asked`,
1522
1782
  );
1523
1783
  }
1524
- // An action that targets no object names no id. The kernel has no such
1525
- // action today, but the HTTP body allows it, so the views say why it
1526
- // cannot run instead of refusing the request before looking it up.
1784
+ // An action that targets no object names no id: the HTTP body allows it,
1785
+ // and the action itself says whether it can run without one.
1527
1786
  if (id === undefined) {
1528
1787
  const info = this.resolveActionInfo(name);
1529
- throw new ViewError(
1530
- "not-found",
1531
- `action "${info.name}" targets ${info.on} objects; pass the object id`,
1532
- );
1788
+ if (info.on !== undefined) {
1789
+ throw new ViewError(
1790
+ "not-found",
1791
+ `action "${info.name}" targets ${info.on} objects; pass the object id`,
1792
+ );
1793
+ }
1794
+ const action = this.registry.targetlessAction(info.plugin, info.action);
1795
+ if (action === undefined) {
1796
+ throw new ViewError("action", `there is no action "${name}"`);
1797
+ }
1798
+ return this.runAction({ plugin: info.plugin, action, info }, undefined, undefined, options);
1533
1799
  }
1534
1800
  const resolved = await this.resolve(id);
1535
1801
  const object = resolved.object;
@@ -1546,11 +1812,28 @@ export class Views {
1546
1812
  ? resolved.id
1547
1813
  : this.guardedRow(owner.plugin, resolved.type, object).id;
1548
1814
  const target = this.resolveAction(name, resolved.type, subject);
1549
- const env = this.registry.actionEnv();
1815
+ return this.runAction(target, object, subject, options);
1816
+ }
1817
+
1818
+ /** The checks and the call one resolved action shares, with or without an object. */
1819
+ private async runAction(
1820
+ target: {
1821
+ readonly plugin: string;
1822
+ readonly action: ActionTypeDefinition;
1823
+ readonly info: ActionInfo;
1824
+ },
1825
+ object: StoredObject | undefined,
1826
+ subject: string | undefined,
1827
+ options: ActOptions,
1828
+ ): Promise<ViewActionRun> {
1829
+ const env = this.registry.actionEnv(
1830
+ object === undefined ? undefined : { type: object.type, id: object.id },
1831
+ );
1832
+ const label = subject ?? target.info.name;
1550
1833
 
1551
1834
  // A result that is already true is not an error: the plugin says so and
1552
1835
  // nothing runs.
1553
- if (target.action.settled !== undefined) {
1836
+ if (object !== undefined && target.action.settled !== undefined) {
1554
1837
  let message: string | undefined;
1555
1838
  try {
1556
1839
  message = await target.action.settled(object, options.args ?? {}, env);
@@ -1572,18 +1855,23 @@ export class Views {
1572
1855
 
1573
1856
  let holds: unknown;
1574
1857
  try {
1575
- holds = await target.action.when(object.data, env);
1858
+ holds = await target.action.when(object?.data ?? {}, env);
1576
1859
  } catch (error) {
1577
1860
  this.onLog(
1578
1861
  `plugin "${target.plugin}": action "${target.action.name}": when failed: ${messageOf(error)}`,
1579
1862
  );
1580
1863
  throw new ViewError(
1581
1864
  "not-available",
1582
- `${subject} cannot ${target.info.name} now`,
1865
+ `${label} cannot ${target.info.name} now`,
1583
1866
  );
1584
1867
  }
1585
1868
  if (holds !== true) {
1586
- throw new ViewError("not-available", await this.refusal(target, object, subject));
1869
+ throw new ViewError(
1870
+ "not-available",
1871
+ object === undefined || subject === undefined
1872
+ ? `${target.info.name} cannot run now`
1873
+ : await this.refusal(target, object, subject),
1874
+ );
1587
1875
  }
1588
1876
 
1589
1877
  const args: Record<string, unknown> = { ...(options.args ?? {}) };
@@ -1607,10 +1895,14 @@ export class Views {
1607
1895
  );
1608
1896
  }
1609
1897
 
1898
+ const schema =
1899
+ object === undefined
1900
+ ? target.action.args
1901
+ : target.action.argsFor?.(object, env) ?? target.action.args;
1610
1902
  let personArgs: Record<string, unknown>;
1611
1903
  try {
1612
1904
  personArgs = validateActionArgs(
1613
- target.action.argsFor?.(object, env) ?? target.action.args,
1905
+ schema,
1614
1906
  args,
1615
1907
  `action "${target.info.name}"`,
1616
1908
  );
@@ -1634,20 +1926,34 @@ export class Views {
1634
1926
 
1635
1927
  // An uploaded file is taken only now that nothing else can refuse the call;
1636
1928
  // the action gets the stored path where the client sent the reference.
1637
- const stored = await this.takeFiles(
1638
- target.action.argsFor?.(object, env) ?? target.action.args,
1639
- personArgs,
1640
- resolved.type,
1641
- resolved.id,
1642
- target.info.name,
1643
- );
1929
+ let stored = personArgs;
1930
+ if (object === undefined) {
1931
+ const given = fileProperties(schema).filter(
1932
+ (file) => personArgs[file.name] !== undefined,
1933
+ );
1934
+ if (given.length > 0) {
1935
+ throw new ViewError(
1936
+ "args",
1937
+ `action "${target.info.name}" targets no object, so it takes no file`,
1938
+ );
1939
+ }
1940
+ } else {
1941
+ stored = await this.takeFiles(
1942
+ schema,
1943
+ personArgs,
1944
+ object.type,
1945
+ object.id,
1946
+ target.info.name,
1947
+ );
1948
+ }
1644
1949
 
1645
- const runId = await this.waitingRunId(resolved.type, resolved.id);
1950
+ const runId =
1951
+ object === undefined ? undefined : await this.waitingRunId(object.type, object.id);
1646
1952
  const result = await this.registry.runAction(
1647
1953
  `${target.plugin}/${target.action.name}`,
1648
1954
  stored,
1649
1955
  {
1650
- object,
1956
+ ...(object === undefined ? {} : { object }),
1651
1957
  ...(runId === undefined ? {} : { runId }),
1652
1958
  actor: options.actor,
1653
1959
  cwd: this.cwd,
@@ -1698,7 +2004,7 @@ export class Views {
1698
2004
  /** `opens` when it names an object that exists; otherwise the log says why. */
1699
2005
  private async existingOpens(action: string, opens: string | undefined): Promise<string | undefined> {
1700
2006
  if (opens === undefined) return undefined;
1701
- const typed = splitId(opens);
2007
+ const typed = parseObjectId(opens);
1702
2008
  if (typed === undefined) {
1703
2009
  this.onLog(`action "${action}": opens "${opens}" is not <type>:<id>; not passed on`);
1704
2010
  return undefined;
@@ -1724,6 +2030,9 @@ export class Views {
1724
2030
  next: string | undefined,
1725
2031
  mark: string | undefined,
1726
2032
  tail: string | undefined,
2033
+ status: SectionStatus | undefined,
2034
+ retry: SectionRetry | undefined,
2035
+ data: Readonly<Record<string, JsonValue>> | undefined,
1727
2036
  full: boolean,
1728
2037
  delta: boolean | undefined,
1729
2038
  ): ViewSectionContent {
@@ -1735,6 +2044,9 @@ export class Views {
1735
2044
  ...(next === undefined ? {} : { next }),
1736
2045
  ...(mark === undefined ? {} : { mark }),
1737
2046
  ...(shownTail === undefined ? {} : { tail: shownTail }),
2047
+ ...(status === undefined ? {} : { status }),
2048
+ ...(retry === undefined ? {} : { retry }),
2049
+ ...(data === undefined ? {} : { data }),
1738
2050
  ...(delta === undefined ? {} : { delta }),
1739
2051
  });
1740
2052
  if (full) return result(markdown, tail);
@@ -1743,19 +2055,20 @@ export class Views {
1743
2055
  const limit = this.sectionCapBytes;
1744
2056
  const markdownBytes = Buffer.byteLength(markdown, "utf8");
1745
2057
  const tailBytes = tail === undefined ? 0 : Buffer.byteLength(tail, "utf8");
1746
- if (markdownBytes + tailBytes <= limit) return result(markdown, tail);
2058
+ const dataBytes = data === undefined ? 0 : Buffer.byteLength(JSON.stringify(data), "utf8");
2059
+ if (markdownBytes + tailBytes + dataBytes <= limit) return result(markdown, tail);
1747
2060
 
1748
- // The cap covers the finished page, the changing tail and the note
1749
- // together. The tail is never cut: if even the tail and the note do not
1750
- // fit, the section is refused and the client asks for it whole.
2061
+ // The cap covers the finished page, the changing tail, the plugin's data
2062
+ // and the note together. The tail is never cut: if even the tail, data and
2063
+ // note do not fit, the section is refused and the client asks for it whole.
1751
2064
  const suffixBytes = Buffer.byteLength(suffix, "utf8");
1752
- if (tailBytes + suffixBytes > limit) {
2065
+ if (tailBytes + dataBytes + suffixBytes > limit) {
1753
2066
  throw new ViewError(
1754
2067
  "section",
1755
2068
  `section "${sectionId}" of "${id}" is over the ${limit}-byte size cap; ${suffix.trim()}`,
1756
2069
  );
1757
2070
  }
1758
- const body = capBytes(markdown, limit - suffixBytes - tailBytes);
2071
+ const body = capBytes(markdown, Math.max(0, limit - suffixBytes - tailBytes - dataBytes));
1759
2072
  return result(`${body}${suffix}`, tail);
1760
2073
  }
1761
2074
 
@@ -1800,7 +2113,8 @@ export class Views {
1800
2113
  ? info.action === name
1801
2114
  : info.plugin === target.plugin && info.action === target.action,
1802
2115
  )
1803
- .map((info) => info.on),
2116
+ .map((info) => info.on)
2117
+ .filter((on): on is string => on !== undefined),
1804
2118
  ),
1805
2119
  ];
1806
2120
  return new ViewError(
@@ -1864,7 +2178,7 @@ export class Views {
1864
2178
  ): Promise<readonly ViewAction[]> {
1865
2179
  const keys = new Map(this.registry.keyBindings().map((item) => [item.name, item.key]));
1866
2180
  const actions: (ViewAction & { readonly rank: number })[] = [];
1867
- const env = this.registry.actionEnv();
2181
+ const env = this.registry.actionEnv({ type: object.type, id: object.id });
1868
2182
  for (const info of this.registry.actions()) {
1869
2183
  if (info.on !== type) continue;
1870
2184
  const action = this.registry.actionDefinition(
@@ -1897,7 +2211,7 @@ export class Views {
1897
2211
 
1898
2212
  private async resolve(id: string): Promise<ResolvedObject> {
1899
2213
  await this.prepared();
1900
- const typed = splitId(id);
2214
+ const typed = parseObjectId(id);
1901
2215
  // A qualified id names its namespace; a different `--repo` is a mistake.
1902
2216
  const qualified = (typed?.id ?? id).split("/");
1903
2217
  if (this.scope !== undefined && qualified.length > 1 && qualified[0] !== this.scope) {
@@ -2028,7 +2342,7 @@ export class Views {
2028
2342
 
2029
2343
  if (this.log !== undefined) {
2030
2344
  const found = (await this.log.runs({ object: id }))[0];
2031
- const parsed = found === undefined ? undefined : splitId(found.object);
2345
+ const parsed = found === undefined ? undefined : parseObjectId(found.object);
2032
2346
  if (parsed !== undefined) {
2033
2347
  const object = await this.store.get(parsed.type, parsed.id);
2034
2348
  return { type: parsed.type, id: parsed.id, object };
@@ -2089,6 +2403,61 @@ export class Views {
2089
2403
  return matches[0];
2090
2404
  }
2091
2405
 
2406
+ /** How the newest run of an object ended, read from its ending fact. */
2407
+ private async lastRunEnd(type: string, id: string): Promise<ViewRunEnd | undefined> {
2408
+ if (this.log === undefined) return undefined;
2409
+ const key = objectKey(type, id);
2410
+ const runs = await this.log.runs({ object: key });
2411
+ let newest: RunInfo | undefined;
2412
+ for (const run of runs) if (newest === undefined || run.startedAt >= newest.startedAt) newest = run;
2413
+ if (newest === undefined || newest.active) {
2414
+ this.lastRunEnds.delete(key);
2415
+ return undefined;
2416
+ }
2417
+ const cached = this.lastRunEnds.get(key);
2418
+ if (
2419
+ cached !== undefined &&
2420
+ cached.runId === newest.runId &&
2421
+ cached.lastSeq === newest.lastSeq
2422
+ ) {
2423
+ return cached.end;
2424
+ }
2425
+ let found: ViewRunEnd | undefined;
2426
+ // What the last step said when it failed: a flow that fails by moving to
2427
+ // an end step records no reason of its own.
2428
+ let stepWhy = "";
2429
+ try {
2430
+ for await (const fact of this.log.read(newest.runId)) {
2431
+ if (fact.kind === "step_result") {
2432
+ stepWhy = historyEntry(fact).why;
2433
+ if (!isRecord(fact.payload) || fact.payload.result !== "failed") stepWhy = "";
2434
+ continue;
2435
+ }
2436
+ if (fact.kind !== "run_ended") continue;
2437
+ if (!isRecord(fact.payload)) continue;
2438
+ const payload = fact.payload;
2439
+ const status = payload.status;
2440
+ if (status !== "done" && status !== "failed" && status !== "cancelled") continue;
2441
+ const recorded = payload.reason;
2442
+ const reason =
2443
+ typeof recorded === "string" && recorded.length > 0
2444
+ ? recorded
2445
+ : status === "failed" && stepWhy.length > 0
2446
+ ? stepWhy
2447
+ : undefined;
2448
+ found = {
2449
+ outcome: status,
2450
+ ...(reason === undefined ? {} : { reason }),
2451
+ endedAt: fact.time,
2452
+ };
2453
+ }
2454
+ } catch (error) {
2455
+ this.onLog(`could not read how the run of "${type}:${id}" ended: ${messageOf(error)}`);
2456
+ }
2457
+ this.lastRunEnds.set(key, { runId: newest.runId, lastSeq: newest.lastSeq, end: found });
2458
+ return found;
2459
+ }
2460
+
2092
2461
  private async hasRun(type: string, id: string): Promise<boolean> {
2093
2462
  if (this.log === undefined) return false;
2094
2463
  const runs = await this.log.runs({ object: objectKey(type, id) });
@@ -2204,6 +2573,14 @@ export class Views {
2204
2573
  new Error("row after must be an array of non-empty object ids"),
2205
2574
  );
2206
2575
  }
2576
+ const data = outcome.data;
2577
+ if (data !== undefined && !isRecord(data)) {
2578
+ return this.failRow(
2579
+ plugin,
2580
+ object,
2581
+ new Error("row data must be an object"),
2582
+ );
2583
+ }
2207
2584
  return {
2208
2585
  id,
2209
2586
  title,
@@ -2216,6 +2593,7 @@ export class Views {
2216
2593
  ...(outcome.final === true ? { final: true } : {}),
2217
2594
  ...(mark === undefined ? {} : { mark }),
2218
2595
  ...(typeof badge === "string" ? { badge } : {}),
2596
+ ...(data === undefined ? {} : { data: data as Readonly<Record<string, JsonValue>> }),
2219
2597
  waiting: outcome.waiting === true,
2220
2598
  running: false,
2221
2599
  };
@@ -2294,6 +2672,7 @@ export class Views {
2294
2672
  signal,
2295
2673
  settings: this.registry.settingsFor(plugin),
2296
2674
  settingsInForce: (name: string) => this.settingsInForce(name),
2675
+ sectionCapBytes: this.sectionCapBytes,
2297
2676
  refreshedObject: (type: string, id: string) =>
2298
2677
  this.refreshedObject(type, id),
2299
2678
  secrets: new FileSecretStore({ home: this.registry.home, plugin }),
@@ -2325,7 +2704,7 @@ export class Views {
2325
2704
  if (this.log === undefined) return flags;
2326
2705
  const runs = await this.log.runs({ active: true });
2327
2706
  for (const run of runs) {
2328
- const parsed = splitId(run.object);
2707
+ const parsed = parseObjectId(run.object);
2329
2708
  if (parsed === undefined) continue;
2330
2709
  let state;
2331
2710
  try {
@@ -2460,8 +2839,7 @@ export class Views {
2460
2839
 
2461
2840
  /** The ids nearest to a name that matched nothing, nearest first. */
2462
2841
  async closest(id: string, limit: number): Promise<readonly RecentObject[]> {
2463
- const wanted = (id.includes(":") ? id.slice(id.indexOf(":") + 1) : id)
2464
- .toLowerCase();
2842
+ const wanted = bareId(id).toLowerCase();
2465
2843
  const scored: { readonly score: number; readonly entry: RecentObject }[] = [];
2466
2844
  for (const entry of this.registry.objectTypes()) {
2467
2845
  const owner = this.registry.viewsFor(entry.type);
@@ -2509,7 +2887,10 @@ export class Views {
2509
2887
  subject: string,
2510
2888
  ): Promise<string> {
2511
2889
  try {
2512
- const why = await target.action.why?.(object, this.registry.actionEnv());
2890
+ const why = await target.action.why?.(
2891
+ object,
2892
+ this.registry.actionEnv({ type: object.type, id: object.id }),
2893
+ );
2513
2894
  if (why !== undefined && why.length > 0) return why;
2514
2895
  } catch (error) {
2515
2896
  this.onLog(`action "${target.info.name}": why failed: ${messageOf(error)}`);
@@ -2538,26 +2919,34 @@ export class Views {
2538
2919
  * Announces an object. A run's growth can arrive far faster than a client
2539
2920
  * can read it, so growth is announced at most once per object per window;
2540
2921
  * the last growth in a window is announced when the window ends. An object's
2541
- * own stored change is always announced.
2922
+ * own stored change is always announced. A type that opts into `live` also
2923
+ * pushes its live section's changing part, on its own faster window.
2542
2924
  */
2543
- private publish(id: string, growth = false): void {
2925
+ private publish(ref: ObjectRef, growth = false): void {
2926
+ const key = `${ref.type}:${ref.id}`;
2927
+ const live = this.registry.viewsFor(ref.type)?.views.tail;
2928
+ if (live !== undefined && growth) {
2929
+ // A newer growth makes an older live computation stale.
2930
+ this.liveGenerations.set(key, (this.liveGenerations.get(key) ?? 0) + 1);
2931
+ this.publishLive(ref, key);
2932
+ }
2544
2933
  if (growth) {
2545
2934
  const now = this.clock();
2546
- const last = this.growthAnnouncedAt.get(id);
2935
+ const last = this.growthAnnouncedAt.get(ref.id);
2547
2936
  if (last !== undefined && now - last < GROWTH_EVENT_INTERVAL_MS) {
2548
- this.growthPending.add(id);
2549
- this.scheduleGrowth(id, GROWTH_EVENT_INTERVAL_MS - (now - last));
2937
+ this.growthPending.add(ref.id);
2938
+ this.scheduleGrowth(ref.id, GROWTH_EVENT_INTERVAL_MS - (now - last));
2550
2939
  return;
2551
2940
  }
2552
- this.growthPending.delete(id);
2553
- this.clearGrowthTimer(id);
2554
- this.growthAnnouncedAt.set(id, now);
2941
+ this.growthPending.delete(ref.id);
2942
+ this.clearGrowthTimer(ref.id);
2943
+ this.growthAnnouncedAt.set(ref.id, now);
2555
2944
  }
2556
- this.announce(id);
2945
+ this.announce({ id: ref.id });
2557
2946
  }
2558
2947
 
2559
- private announce(id: string): void {
2560
- for (const listener of this.eventListeners) listener(id);
2948
+ private announce(event: ViewEvent): void {
2949
+ for (const listener of this.eventListeners) listener(event);
2561
2950
  }
2562
2951
 
2563
2952
  /** Announces a held-back growth once its window has passed, or waits again. */
@@ -2572,7 +2961,7 @@ export class Views {
2572
2961
  this.growthPending.delete(id);
2573
2962
  this.clearGrowthTimer(id);
2574
2963
  this.growthAnnouncedAt.set(id, now);
2575
- this.announce(id);
2964
+ this.announce({ id });
2576
2965
  }
2577
2966
 
2578
2967
  /** Announces every held-back growth whose window has passed by the clock. */
@@ -2601,6 +2990,165 @@ export class Views {
2601
2990
  clearTimeout(timer);
2602
2991
  this.growthTimers.delete(id);
2603
2992
  }
2993
+
2994
+ /** Sends a live section's changing part now, or when its own window ends. */
2995
+ private publishLive(ref: ObjectRef, key: string): void {
2996
+ const now = this.clock();
2997
+ const last = this.liveAnnouncedAt.get(key);
2998
+ if (last !== undefined && now - last < LIVE_PUSH_INTERVAL_MS) {
2999
+ this.livePending.set(key, ref);
3000
+ this.scheduleLive(key, LIVE_PUSH_INTERVAL_MS - (now - last));
3001
+ return;
3002
+ }
3003
+ this.livePending.delete(key);
3004
+ this.clearLiveTimer(key);
3005
+ this.liveAnnouncedAt.set(key, now);
3006
+ this.pushLive(ref, key);
3007
+ }
3008
+
3009
+ /**
3010
+ * Reads the plugin's live part and sends it, unless a newer change won. When
3011
+ * the plugin has nothing left to say, one last event with an empty tail tells
3012
+ * a client that renders only from push to drop what it kept. A part that
3013
+ * would not fit one event line is not sent: the growth change announced
3014
+ * beside it, within the change window, asks for the section read instead.
3015
+ */
3016
+ private pushLive(ref: ObjectRef, key: string): void {
3017
+ const generation = this.liveGenerations.get(key) ?? 0;
3018
+ void this.liveEvent(ref)
3019
+ .then((result) => {
3020
+ if (this.closed) return;
3021
+ if (this.liveGenerations.get(key) !== generation) return;
3022
+ if (result === undefined) return;
3023
+ if (result.event !== undefined && result.section !== undefined) {
3024
+ this.liveSections.set(key, result.section);
3025
+ if (fitsEventLine(result.event)) this.announce(result.event);
3026
+ return;
3027
+ }
3028
+ const section = result.section ?? this.liveSections.get(key);
3029
+ if (section === undefined) return;
3030
+ this.liveSections.delete(key);
3031
+ this.announce({ id: ref.id, type: ref.type, section, tail: "" });
3032
+ })
3033
+ .catch((error: unknown) => {
3034
+ this.onLog(
3035
+ `tail "${key}" failed: ${messageOf(error)}`,
3036
+ );
3037
+ });
3038
+ }
3039
+
3040
+ /**
3041
+ * The plugin's live part. Undefined when the type has no tail, the object is
3042
+ * gone, or the call failed; the section alone when it has nothing to say now;
3043
+ * otherwise the section and the event to announce.
3044
+ */
3045
+ private async liveEvent(
3046
+ ref: ObjectRef,
3047
+ ): Promise<{ readonly section?: string | undefined; readonly event?: ViewEvent | undefined } | undefined> {
3048
+ const owner = this.registry.viewsFor(ref.type);
3049
+ const live = owner?.views.tail;
3050
+ if (owner === undefined || live === undefined) return undefined;
3051
+ let object: StoredObject | undefined;
3052
+ try {
3053
+ object = await this.store.get(ref.type, ref.id);
3054
+ } catch (error) {
3055
+ this.onLog(`tail "${ref.type}:${ref.id}": ${messageOf(error)}`);
3056
+ return undefined;
3057
+ }
3058
+ if (object === undefined) return undefined;
3059
+
3060
+ const controller = new AbortController();
3061
+ let timer: ReturnType<typeof setTimeout> | undefined;
3062
+ const timeout = new Promise<never>((_, reject) => {
3063
+ timer = setTimeout(() => {
3064
+ controller.abort();
3065
+ reject(new Error(`did not answer within ${this.loadTimeoutMs}ms`));
3066
+ }, this.loadTimeoutMs);
3067
+ });
3068
+ try {
3069
+ const content = await Promise.race([
3070
+ Promise.resolve().then(() =>
3071
+ live(this.viewContext(owner.plugin, controller.signal), object),
3072
+ ),
3073
+ timeout,
3074
+ ]);
3075
+ // The plugin may have no live content now; that is not a failure.
3076
+ if (content === undefined) return {};
3077
+ if (!isRecord(content)) return undefined;
3078
+ const section = textOf(content.section);
3079
+ if (section === undefined || section.length === 0) return undefined;
3080
+ const tail = textOf(content.tail);
3081
+ const status = statusOf(content.status);
3082
+ const retry = retryOf(content.retry);
3083
+ const data =
3084
+ isRecord(content.data) ? (content.data as Readonly<Record<string, JsonValue>>) : undefined;
3085
+ if (tail === undefined && status === undefined && retry === undefined && data === undefined) {
3086
+ return { section };
3087
+ }
3088
+ return {
3089
+ section,
3090
+ event: {
3091
+ id: ref.id,
3092
+ type: ref.type,
3093
+ section,
3094
+ ...(tail === undefined ? {} : { tail }),
3095
+ ...(status === undefined ? {} : { status }),
3096
+ ...(retry === undefined ? {} : { retry }),
3097
+ ...(data === undefined ? {} : { data }),
3098
+ },
3099
+ };
3100
+ } catch (error) {
3101
+ this.onLog(
3102
+ `plugin "${owner.plugin}": tail for "${ref.type}:${ref.id}" failed: ${messageOf(error)}`,
3103
+ );
3104
+ return undefined;
3105
+ } finally {
3106
+ if (timer !== undefined) clearTimeout(timer);
3107
+ }
3108
+ }
3109
+
3110
+ /** Sends a held-back live part once its window has passed, or waits again. */
3111
+ private flushLive(key: string): void {
3112
+ const ref = this.livePending.get(key);
3113
+ if (ref === undefined) return;
3114
+ const now = this.clock();
3115
+ const last = this.liveAnnouncedAt.get(key);
3116
+ if (last !== undefined && now - last < LIVE_PUSH_INTERVAL_MS) {
3117
+ this.scheduleLive(key, LIVE_PUSH_INTERVAL_MS - (now - last));
3118
+ return;
3119
+ }
3120
+ this.livePending.delete(key);
3121
+ this.clearLiveTimer(key);
3122
+ this.liveAnnouncedAt.set(key, now);
3123
+ this.pushLive(ref, key);
3124
+ }
3125
+
3126
+ /** Sends every held-back live part whose window has passed by the clock. */
3127
+ private flushDueLive(): void {
3128
+ for (const key of [...this.livePending.keys()]) {
3129
+ const last = this.liveAnnouncedAt.get(key);
3130
+ if (last === undefined || this.clock() - last >= LIVE_PUSH_INTERVAL_MS) {
3131
+ this.flushLive(key);
3132
+ }
3133
+ }
3134
+ }
3135
+
3136
+ /** The one timer per object that wakes a reader when its live window ends. */
3137
+ private scheduleLive(key: string, waitMs: number): void {
3138
+ if (this.liveTimers.has(key)) return;
3139
+ const timer = setTimeout(() => {
3140
+ this.liveTimers.delete(key);
3141
+ this.flushLive(key);
3142
+ }, Math.max(0, waitMs));
3143
+ this.liveTimers.set(key, timer);
3144
+ }
3145
+
3146
+ private clearLiveTimer(key: string): void {
3147
+ const timer = this.liveTimers.get(key);
3148
+ if (timer === undefined) return;
3149
+ clearTimeout(timer);
3150
+ this.liveTimers.delete(key);
3151
+ }
2604
3152
  }
2605
3153
 
2606
3154
  /** Builds the presentation API for a registry and its store. */