@operad-io/engine 0.1.1 → 0.3.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 (81) 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 +68 -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/git-program.ts +108 -0
  22. package/src/platform/index.ts +3 -0
  23. package/src/platform/kept-workers.ts +290 -0
  24. package/src/platform/process-group.ts +11 -3
  25. package/src/platform/sqlite-open.ts +20 -6
  26. package/src/platform/sqlite-schema.ts +30 -0
  27. package/src/platform/step-reap.ts +33 -18
  28. package/src/platform/watch.ts +1 -11
  29. package/src/plugin/action-schema.ts +59 -1
  30. package/src/plugin/choice-info.ts +133 -0
  31. package/src/plugin/context.ts +279 -0
  32. package/src/plugin/declared-flows.ts +3 -10
  33. package/src/plugin/errors.ts +9 -0
  34. package/src/plugin/freeze.ts +12 -0
  35. package/src/plugin/harness.ts +28 -0
  36. package/src/plugin/index.ts +8 -7
  37. package/src/plugin/install.ts +265 -17
  38. package/src/plugin/keys.ts +2 -12
  39. package/src/plugin/load.ts +47 -23
  40. package/src/plugin/logger.ts +14 -0
  41. package/src/plugin/open-store.ts +0 -6
  42. package/src/plugin/question-form.ts +323 -0
  43. package/src/plugin/registry.ts +519 -76
  44. package/src/plugin/secrets.ts +14 -24
  45. package/src/plugin/semver.ts +52 -0
  46. package/src/plugin/settings.ts +1 -9
  47. package/src/plugin/sqlite-store.ts +94 -64
  48. package/src/plugin/store.ts +5 -0
  49. package/src/plugin/types.ts +575 -21
  50. package/src/plugin/validate.ts +402 -26
  51. package/src/runner/answer.ts +26 -68
  52. package/src/runner/ask.ts +227 -28
  53. package/src/runner/cancel.ts +10 -7
  54. package/src/runner/grants.ts +2 -2
  55. package/src/runner/index.ts +1 -3
  56. package/src/runner/limits.ts +2 -2
  57. package/src/runner/runner.ts +15 -14
  58. package/src/runner/service.ts +52 -19
  59. package/src/runner/step-worker.ts +9 -0
  60. package/src/testing/answer.ts +69 -0
  61. package/src/testing/clock-manual.ts +152 -0
  62. package/src/testing/config.ts +16 -0
  63. package/src/testing/fs.ts +172 -0
  64. package/src/testing/home.ts +43 -0
  65. package/src/testing/index.ts +19 -0
  66. package/src/testing/types.ts +2 -0
  67. package/src/testing/world.ts +9 -2
  68. package/src/trigger/kernel.ts +13 -46
  69. package/src/trigger/rules.ts +22 -12
  70. package/src/trigger/types.ts +2 -6
  71. package/src/util.ts +99 -0
  72. package/src/views/event-line.ts +22 -0
  73. package/src/views/history.ts +36 -19
  74. package/src/views/live-logs.ts +313 -0
  75. package/src/views/pending.ts +23 -5
  76. package/src/views/presentation.ts +629 -81
  77. package/src/views/running.ts +5 -5
  78. package/src/views/settings.ts +205 -66
  79. package/src/views/types.ts +8 -2
  80. package/src/views/uploads.ts +15 -7
  81. package/triggers.schema.json +4 -0
@@ -6,6 +6,7 @@ import { FlowError, validateFlow } from "../flow/validate.ts";
6
6
  import type { JsonValue } from "../log/types.ts";
7
7
  import { validateActionArgs } from "./action-schema.ts";
8
8
  import { readDeclaredFlows, writeDeclaredFlow } from "./declared-flows.ts";
9
+ import { readFile } from "node:fs/promises";
9
10
  import { AccessError, AskTimeoutError, messageOf, PluginError, StepNotLoadedError } from "./errors.ts";
10
11
  import { defaultOperadHome } from "./home.ts";
11
12
  import { createPluginLogger } from "./logger.ts";
@@ -20,7 +21,9 @@ import {
20
21
  type ProjectSettingsDeclaration,
21
22
  type ActionContext,
22
23
  type ActionEnv,
24
+ type HarnessCapabilities,
23
25
  type HarnessEfforts,
26
+ type HarnessModelContext,
24
27
  type HarnessModels,
25
28
  type ActionEvent,
26
29
  type ActionRun,
@@ -40,17 +43,17 @@ import {
40
43
  type ObjectRef,
41
44
  type StoredObject,
42
45
  type ObjectTypeDefinition,
46
+ type RunObject,
43
47
  type RunLookup,
44
48
  type ObjectViews,
45
49
  type KeyBindings,
46
50
  type PendingActionView,
47
51
  type PendingEntry,
48
- type StandingContext,
49
- type StandingItem,
50
52
  type PluginBaseContext,
53
+ type MissingItem,
51
54
  type PluginCheck,
52
- type PluginKind,
53
- type PluginRequires,
55
+ type SetupGuide,
56
+ type SetupReader,
54
57
  type PluginStepResult,
55
58
  type PluginStore,
56
59
  type ResolvedCommand,
@@ -75,10 +78,40 @@ import type {
75
78
  TriggerRule,
76
79
  } from "../trigger/types.ts";
77
80
  import { askGraceOf, collectStepTypes, grantRequestProblem, narrowerOf, noteInfo, normalizePlugin, parseObjectKeyMaybe, splitActionName, validateFlows, validatePluginSet, validateRuleFlows, type LoadedPlugin } from "./validate.ts";
81
+ import { choiceInfoJson, choiceInfoProblem, normalizeChoiceInfo } from "./choice-info.ts";
82
+ import { normalizeQuestions, questionsJson, questionsProblem } from "./question-form.ts";
78
83
  import { isRecord } from "../util.ts";
79
84
 
80
85
  export { splitActionName };
81
86
 
87
+ /** The items of a check's result; a malformed item makes the check throw. */
88
+ function missingItemsOf(result: { readonly missing: readonly MissingItem[] }): readonly MissingItem[] {
89
+ if (!Array.isArray(result.missing)) throw new PluginError("check: missing must be a list");
90
+ const seen = new Set<string>();
91
+ const items: MissingItem[] = [];
92
+ for (const item of result.missing as readonly unknown[]) {
93
+ if (
94
+ !isRecord(item) ||
95
+ typeof item.name !== "string" ||
96
+ item.name.trim().length === 0 ||
97
+ typeof item.description !== "string" ||
98
+ item.description.trim().length === 0
99
+ ) {
100
+ throw new PluginError("check: each missing item needs a name and a description");
101
+ }
102
+ if (seen.has(item.name)) throw new PluginError(`check: the missing item "${item.name}" is listed twice`);
103
+ seen.add(item.name);
104
+ items.push({ name: item.name, description: item.description });
105
+ }
106
+ return items;
107
+ }
108
+
109
+ /** A `SKILL.md`'s text without its front matter. */
110
+ export function guideBody(text: string): string {
111
+ const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(text);
112
+ return (match === null ? text : text.slice(match[0].length)).trim();
113
+ }
114
+
82
115
  /** An action's rank for an object's data; a failing `rank` counts as 0. */
83
116
  export function rankOf(action: ActionTypeDefinition, data: ObjectData): number {
84
117
  if (action.rank === undefined) return 0;
@@ -126,29 +159,34 @@ export interface PluginRegistryOptions {
126
159
  | undefined;
127
160
  /** Cancels one run when a plugin action asks; the kernel writes the input. */
128
161
  readonly onCancelRun?:
129
- | ((runId: string, flow?: FlowDefinition) => MaybePromise<void>)
162
+ | ((runId: string, flow?: FlowDefinition) => MaybePromise<boolean | void>)
130
163
  | undefined;
164
+ /** Tells whether a run has not ended, for a plugin that reports on it. */
165
+ readonly onRunActive?: ((runId: string) => MaybePromise<boolean | void>) | undefined;
131
166
  /** The specifier each definition was loaded from, aligned with it. */
132
167
  readonly sources?: readonly (string | undefined)[] | undefined;
133
168
  /** The raw config section of each plugin, keyed by plugin name. */
134
169
  readonly settings?: Readonly<Record<string, unknown>> | undefined;
135
170
  /** Plugins the config switched off; a dependent is refused with the reason. */
136
171
  readonly disabled?: readonly string[] | undefined;
172
+ /** The plugins that are off, switched off or not in the file yet; defaults to `disabled`. */
173
+ readonly off?: readonly string[] | undefined;
174
+ /**
175
+ * The path of a switched-off plugin's guide, read from its module; undefined
176
+ * when it has none. Absent: an off plugin's guide is not readable.
177
+ */
178
+ readonly disabledGuide?: ((plugin: string) => Promise<string | undefined>) | undefined;
137
179
  /** Whether to resolve `requires` against the loaded plugins. */
138
180
  readonly requireDependencies?: boolean | undefined;
139
181
  /** Whether to validate each plugin's settings section. */
140
182
  readonly validateSettings?: boolean | undefined;
141
- /** The routing rules, given to source plugins. */
142
- readonly rules?: readonly TriggerRule[] | undefined;
183
+ /** The kernel's runs, so a standing or action hook can tell a live one. */
184
+ readonly runLookup?: RunLookup | undefined;
143
185
  /**
144
186
  * Called when an action sends an event with `ctx.emit`: the kernel routes it
145
187
  * through the rules. Without it an action has no `emit`.
146
188
  */
147
189
  readonly onEvent?: ((event: TriggerEvent) => MaybePromise<void>) | undefined;
148
- /** Called when a source plugin sends an event. */
149
- readonly onSourceEvent?:
150
- | ((event: TriggerEvent, plugin: string) => MaybePromise<void>)
151
- | undefined;
152
190
  }
153
191
 
154
192
  /** A plugin the registry left out, and the line that says why. */
@@ -161,8 +199,8 @@ export interface PluginRefusal {
161
199
  export interface ActionInfo {
162
200
  readonly plugin: string;
163
201
  readonly action: string;
164
- /** The object type the action works on. */
165
- readonly on: string;
202
+ /** The object type the action works on; absent when it targets no object. */
203
+ readonly on?: string | undefined;
166
204
  /** Addressed as `<plugin>:<action>`. */
167
205
  readonly name: string;
168
206
  /** The person's input, as a JSON Schema object. */
@@ -171,10 +209,18 @@ export interface ActionInfo {
171
209
  readonly note?: string | undefined;
172
210
  readonly noteRequired: boolean;
173
211
  readonly confirm: boolean;
212
+ /** The one-line description when a chat may run this action as a command. */
213
+ readonly command?: string | undefined;
174
214
  /** The action ends the object, so a main key or button never runs it. */
175
215
  readonly ends?: boolean | undefined;
176
216
  /** The object type the action creates; a client lists it where that type is created. */
177
217
  readonly creates?: string | undefined;
218
+ /**
219
+ * Whether the action's `when` holds for this object now. Set on the actions
220
+ * an action receives; absent on the list a client reads, which already holds
221
+ * only the available actions.
222
+ */
223
+ readonly available?: boolean | undefined;
178
224
  }
179
225
 
180
226
  /** Where a key binding came from. */
@@ -228,13 +274,14 @@ export class PluginRegistry {
228
274
  ) => MaybePromise<void>)
229
275
  | undefined;
230
276
  private readonly onCancelRun:
231
- | ((runId: string, flow?: FlowDefinition) => MaybePromise<void>)
277
+ | ((runId: string, flow?: FlowDefinition) => MaybePromise<boolean | void>)
232
278
  | undefined;
233
- private readonly rules: readonly TriggerRule[];
234
- private readonly onEvent: ((event: TriggerEvent) => MaybePromise<void>) | undefined;
235
- private readonly onSourceEvent:
236
- | ((event: TriggerEvent, plugin: string) => MaybePromise<void>)
279
+ private readonly onRunActive:
280
+ | ((runId: string) => MaybePromise<boolean | void>)
237
281
  | undefined;
282
+ private readonly onEvent: ((event: TriggerEvent) => MaybePromise<void>) | undefined;
283
+ /** The kernel's runs when the host supplies them; a hook can tell a live one. */
284
+ private runLookup: RunLookup | undefined;
238
285
  private readonly plugins: readonly LoadedPlugin[];
239
286
  private readonly byName: ReadonlyMap<string, LoadedPlugin>;
240
287
  private readonly viewByType: ReadonlyMap<string, { readonly plugin: LoadedPlugin; readonly views: ObjectViews }>;
@@ -257,6 +304,8 @@ export class PluginRegistry {
257
304
  Readonly<Record<string, JsonValue>>
258
305
  >;
259
306
  private readonly disabledNames: ReadonlySet<string>;
307
+ private readonly offNames: ReadonlySet<string>;
308
+ private readonly disabledGuide: ((plugin: string) => Promise<string | undefined>) | undefined;
260
309
 
261
310
  constructor(
262
311
  definitions: readonly unknown[],
@@ -269,9 +318,9 @@ export class PluginRegistry {
269
318
  this.onStartRun = options.onStartRun;
270
319
  this.onAnswer = options.onAnswer;
271
320
  this.onCancelRun = options.onCancelRun;
272
- this.rules = options.rules ?? [];
273
- this.onSourceEvent = options.onSourceEvent;
321
+ this.onRunActive = options.onRunActive;
274
322
  this.onEvent = options.onEvent;
323
+ this.runLookup = options.runLookup;
275
324
 
276
325
  const clock = options.clock ?? (() => Date.now());
277
326
  this.store =
@@ -291,6 +340,8 @@ export class PluginRegistry {
291
340
  }
292
341
  this.sourceByPlugin = sourceMap;
293
342
  this.disabledNames = new Set(options.disabled ?? []);
343
+ this.disabledGuide = options.disabledGuide;
344
+ this.offNames = new Set(options.off ?? options.disabled ?? []);
294
345
 
295
346
  const settingsByPlugin = new Map<
296
347
  string,
@@ -414,15 +465,22 @@ export class PluginRegistry {
414
465
  }
415
466
  for (const action of plugin.actions) {
416
467
  const note = noteInfo(action.args);
468
+ const command =
469
+ typeof action.command === "string"
470
+ ? action.command
471
+ : action.command === true
472
+ ? action.args?.description?.trim() || action.name
473
+ : undefined;
417
474
  actionInfos.push({
418
475
  plugin: plugin.name,
419
476
  action: action.name,
420
- on: action.on,
477
+ ...(action.on === undefined ? {} : { on: action.on }),
421
478
  name: `${plugin.name}:${action.name}`,
422
479
  ...(action.args === undefined ? {} : { args: action.args }),
423
480
  ...(note.name === undefined ? {} : { note: note.name }),
424
481
  noteRequired: note.required,
425
482
  confirm: action.confirm === true,
483
+ ...(command === undefined ? {} : { command }),
426
484
  ...(action.ends === true ? { ends: true } : {}),
427
485
  ...(action.creates === undefined ? {} : { creates: action.creates }),
428
486
  });
@@ -467,6 +525,17 @@ export class PluginRegistry {
467
525
  return this.actionInfos;
468
526
  }
469
527
 
528
+ /** Every command a loaded plugin declares, as `<plugin> <verb>` or its short form. */
529
+ commandNames(): readonly string[] {
530
+ const names = new Set<string>(this.shortCommands.keys());
531
+ for (const plugin of this.plugins) {
532
+ for (const command of plugin.commands) {
533
+ names.add(`${plugin.name} ${command.name}`);
534
+ }
535
+ }
536
+ return [...names];
537
+ }
538
+
470
539
  /** The default and user key bindings in force, by key. */
471
540
  keyBindings(): readonly KeyBinding[] {
472
541
  return [...this.bindingByKey.values()];
@@ -497,6 +566,16 @@ export class PluginRegistry {
497
566
  );
498
567
  }
499
568
 
569
+ /** The definition of one action that targets no object, or undefined. */
570
+ targetlessAction(
571
+ plugin: string,
572
+ action: string,
573
+ ): ActionTypeDefinition | undefined {
574
+ return this.byName
575
+ .get(plugin)
576
+ ?.actions.find((item) => item.name === action && item.on === undefined);
577
+ }
578
+
500
579
  /** The plugin names in load order. */
501
580
  names(): readonly string[] {
502
581
  return this.plugins.map((plugin) => plugin.name);
@@ -507,6 +586,11 @@ export class PluginRegistry {
507
586
  return this.byName.get(plugin)?.objectsUnderSettings === true;
508
587
  }
509
588
 
589
+ /** The title a plugin gives its list, if it declares one. */
590
+ listTitleOf(plugin: string): string | undefined {
591
+ return this.byName.get(plugin)?.listTitle;
592
+ }
593
+
510
594
  /** The trigger rules plugins ship, in load order, with their plugin. */
511
595
  triggerRules(): readonly {
512
596
  readonly plugin: string;
@@ -907,6 +991,24 @@ export class PluginRegistry {
907
991
  `step "${use}": ask: choices: must be a list of strings`,
908
992
  );
909
993
  }
994
+ const choices = request.choices ?? [];
995
+ const questionsProblemText = questionsProblem(request.questions);
996
+ if (questionsProblemText !== undefined) {
997
+ throw new PluginError(`step "${use}": ask: questions: ${questionsProblemText}`);
998
+ }
999
+ if (request.questions !== undefined && choices.length > 0) {
1000
+ throw new PluginError(
1001
+ `step "${use}": ask: a form takes no choices of its own; each question carries its own`,
1002
+ );
1003
+ }
1004
+ const questions = normalizeQuestions(request.questions);
1005
+ const infoProblem = choiceInfoProblem(request.choiceInfo, choices);
1006
+ if (infoProblem !== undefined) {
1007
+ throw new PluginError(
1008
+ `step "${use}": ask: choiceInfo: ${infoProblem}`,
1009
+ );
1010
+ }
1011
+ const choiceInfo = normalizeChoiceInfo(request.choiceInfo, choices);
910
1012
  if (
911
1013
  request.onTimeout !== undefined &&
912
1014
  request.onTimeout !== "waiting" &&
@@ -936,6 +1038,14 @@ export class PluginRegistry {
936
1038
  // gets one answer or a refusal, whatever the call said.
937
1039
  const onTimeout =
938
1040
  found.step.resumable === false ? "reject_once" : request.onTimeout;
1041
+ if (
1042
+ questions?.some((question) => question.secret === true) === true &&
1043
+ onTimeout !== "reject_once"
1044
+ ) {
1045
+ throw new PluginError(
1046
+ `step "${use}": ask: a secret question cannot wait, so its onTimeout must be "reject_once"`,
1047
+ );
1048
+ }
939
1049
  if (
940
1050
  onTimeout !== "reject_once" &&
941
1051
  !found.step.results.includes("waiting")
@@ -950,7 +1060,12 @@ export class PluginRegistry {
950
1060
  }
951
1061
  const graceSecs = narrowerOf(request.graceSecs, askGraceOf(params));
952
1062
  const outcome = await options.asker.ask(
953
- { ...request, ...(graceSecs === undefined ? {} : { graceSecs }) },
1063
+ {
1064
+ ...request,
1065
+ ...(questions === undefined ? {} : { questions }),
1066
+ ...(choiceInfo === undefined ? {} : { choiceInfo }),
1067
+ ...(graceSecs === undefined ? {} : { graceSecs }),
1068
+ },
954
1069
  options.signal,
955
1070
  );
956
1071
  if (outcome.kind === "answered") return outcome.answer;
@@ -961,7 +1076,13 @@ export class PluginRegistry {
961
1076
  waitId: outcome.waitId,
962
1077
  prompt: outcome.prompt,
963
1078
  choices: outcome.choices,
964
- resume: request.resume ?? null,
1079
+ ...(outcome.questions === undefined && questions === undefined
1080
+ ? {}
1081
+ : { questions: outcome.questions ?? questions }),
1082
+ ...(outcome.choiceInfo === undefined && choiceInfo === undefined
1083
+ ? {}
1084
+ : { choiceInfo: outcome.choiceInfo ?? choiceInfo }),
1085
+ resume: outcome.resume ?? request.resume ?? null,
965
1086
  });
966
1087
  };
967
1088
  const useGrant = async (waitId: string): Promise<boolean> => {
@@ -987,8 +1108,10 @@ export class PluginRegistry {
987
1108
  settings: this.settingsFor(found.plugin.name),
988
1109
  secrets: this.secretsFor(found.plugin.name),
989
1110
  runId: options.runId,
1111
+ harnesses: this.plugins.filter((plugin) => plugin.kind === "harness").map((plugin) => plugin.name),
990
1112
  object: options.object,
991
1113
  params: options.params ?? null,
1114
+ flow: options.flow,
992
1115
  access: options.access ?? null,
993
1116
  trigger: options.trigger,
994
1117
  emit,
@@ -999,8 +1122,10 @@ export class PluginRegistry {
999
1122
  : (key, ahead) =>
1000
1123
  limiter.report({ key, ...(ahead === undefined ? {} : { ahead }) }),
1001
1124
  stepLoaded: (name) => this.stepIndex.has(name),
1002
- harnessModels: (name) => this.loadedModels()[name],
1125
+ harnessModels: (name) => this.loadedModelFor(name),
1126
+ harnessModelsReady: (name) => this.loadedModelsReadyFor(name),
1003
1127
  harnessEfforts: (name) => this.loadedEfforts()[name],
1128
+ harnessCapabilities: (name) => this.loadedCapabilities()[name],
1004
1129
  runStep: (nestedUse, nestedParams, nestedOptions) => {
1005
1130
  // Declarations must not drift: tests fail on a call the step did not
1006
1131
  // declare; production still runs it.
@@ -1020,6 +1145,7 @@ export class PluginRegistry {
1020
1145
  }
1021
1146
  return this.runStepInner(nestedUse, nestedParams, {
1022
1147
  ...nestedOptions,
1148
+ flow: nestedOptions.flow ?? options.flow,
1023
1149
  limits: nestedOptions.limits ?? options.limits,
1024
1150
  asker: nestedOptions.asker ?? options.asker,
1025
1151
  // A nested step reports its events to the same destination.
@@ -1042,6 +1168,12 @@ export class PluginRegistry {
1042
1168
  waitId: error.waitId,
1043
1169
  prompt: error.prompt,
1044
1170
  choices: [...error.choices],
1171
+ ...(error.choiceInfo === undefined
1172
+ ? {}
1173
+ : { choiceInfo: choiceInfoJson(error.choiceInfo) }),
1174
+ ...(error.questions === undefined
1175
+ ? {}
1176
+ : { questions: questionsJson(error.questions) }),
1045
1177
  resume: error.resume ?? null,
1046
1178
  },
1047
1179
  };
@@ -1069,51 +1201,216 @@ export class PluginRegistry {
1069
1201
  return { result: outcome.result, data };
1070
1202
  }
1071
1203
 
1204
+ /** True when a loaded plugin declares the step `<plugin>/<step>`. */
1205
+ stepLoaded(use: string): boolean {
1206
+ return this.stepIndex.has(use);
1207
+ }
1208
+
1072
1209
  /** The names of the harness plugins loaded now. */
1073
1210
  loadedHarnesses(): readonly string[] {
1074
1211
  return this.plugins.filter((item) => item.kind === "harness").map((item) => item.name);
1075
1212
  }
1076
1213
 
1214
+ private modelContext(): HarnessModelContext {
1215
+ return { home: this.home, log: this.onLog };
1216
+ }
1217
+
1077
1218
  /** The models the loaded harness plugins declare, by plugin name. */
1078
1219
  loadedModels(): Readonly<Record<string, HarnessModels>> {
1079
1220
  const found: Record<string, HarnessModels> = {};
1221
+ const context = this.modelContext();
1080
1222
  for (const item of this.plugins) {
1081
1223
  if (item.kind !== "harness" || item.models === undefined) continue;
1082
1224
  found[item.name] =
1083
- typeof item.models === "function" ? item.models(this.settingsFor(item.name)) : item.models;
1225
+ typeof item.models === "function"
1226
+ ? item.models(this.settingsFor(item.name), context)
1227
+ : item.models;
1084
1228
  }
1085
1229
  return found;
1086
1230
  }
1087
1231
 
1232
+ /** The models one loaded harness plugin declares, without reading another's. */
1233
+ loadedModelFor(name: string): HarnessModels | undefined {
1234
+ const item = this.byName.get(name);
1235
+ if (item === undefined || item.kind !== "harness" || item.models === undefined) {
1236
+ return undefined;
1237
+ }
1238
+ return typeof item.models === "function"
1239
+ ? item.models(this.settingsFor(name), this.modelContext())
1240
+ : item.models;
1241
+ }
1242
+
1243
+ /**
1244
+ * The models the loaded harness plugins declare, waiting for a harness that
1245
+ * has no kept list yet to read one. A plugin without `modelsReady` answers
1246
+ * at once with its ordinary list.
1247
+ */
1248
+ async loadedModelsReady(): Promise<Readonly<Record<string, HarnessModels>>> {
1249
+ const found: Record<string, HarnessModels> = {};
1250
+ const context = this.modelContext();
1251
+ for (const item of this.plugins) {
1252
+ if (item.kind !== "harness") continue;
1253
+ if (item.models === undefined && item.modelsReady === undefined) continue;
1254
+ found[item.name] =
1255
+ item.modelsReady !== undefined
1256
+ ? await item.modelsReady(this.settingsFor(item.name), context)
1257
+ : item.models !== undefined && typeof item.models === "function"
1258
+ ? item.models(this.settingsFor(item.name), context)
1259
+ : item.models ?? { list: [], default: null };
1260
+ }
1261
+ return found;
1262
+ }
1263
+
1264
+ /** One harness's models, waiting for a first refresh when it needs one. */
1265
+ async loadedModelsReadyFor(name: string): Promise<HarnessModels | undefined> {
1266
+ const item = this.byName.get(name);
1267
+ if (item === undefined || item.kind !== "harness") return undefined;
1268
+ if (item.models === undefined && item.modelsReady === undefined) return undefined;
1269
+ const context = this.modelContext();
1270
+ if (item.modelsReady !== undefined) {
1271
+ return await item.modelsReady(this.settingsFor(name), context);
1272
+ }
1273
+ return item.models !== undefined && typeof item.models === "function"
1274
+ ? item.models(this.settingsFor(name), context)
1275
+ : item.models ?? { list: [], default: null };
1276
+ }
1277
+
1088
1278
  /** The efforts the loaded harness plugins declare, by plugin name. */
1089
1279
  loadedEfforts(): Readonly<Record<string, HarnessEfforts>> {
1090
1280
  const found: Record<string, HarnessEfforts> = {};
1091
1281
  for (const item of this.plugins) {
1092
- if (item.kind === "harness" && item.efforts !== undefined) found[item.name] = item.efforts;
1282
+ if (item.kind !== "harness" || item.efforts === undefined) continue;
1283
+ found[item.name] =
1284
+ typeof item.efforts === "function"
1285
+ ? item.efforts(this.settingsFor(item.name))
1286
+ : item.efforts;
1287
+ }
1288
+ return found;
1289
+ }
1290
+
1291
+ /** What the loaded harness plugins declare they can do, by plugin name. */
1292
+ loadedCapabilities(): Readonly<Record<string, HarnessCapabilities>> {
1293
+ const found: Record<string, HarnessCapabilities> = {};
1294
+ for (const item of this.plugins) {
1295
+ if (item.kind === "harness") found[item.name] = item.capabilities ?? {};
1093
1296
  }
1094
1297
  return found;
1095
1298
  }
1096
1299
 
1097
- /** What an action's checks may read. */
1098
- actionEnv(): ActionEnv {
1300
+ /**
1301
+ * Whether a loaded harness plugin's agent is signed in now: true or false
1302
+ * when it can tell, undefined when it is not a harness, declares no
1303
+ * `signedIn`, or the check fails. This is the one answer a client receives;
1304
+ * a credential is never read out.
1305
+ */
1306
+ async signedInFor(plugin: string): Promise<boolean | undefined> {
1307
+ const found = this.byName.get(plugin);
1308
+ if (found === undefined || found.kind !== "harness" || found.signedIn === undefined) {
1309
+ return undefined;
1310
+ }
1311
+ try {
1312
+ return await found.signedIn(this.settingsFor(plugin));
1313
+ } catch {
1314
+ return undefined;
1315
+ }
1316
+ }
1317
+
1318
+ /** What an action's checks may read; `object` names the object it works on. */
1319
+ actionEnv(object?: ObjectRef | undefined): ActionEnv {
1099
1320
  return {
1100
1321
  store: this.store,
1322
+ ...(object === undefined ? {} : { object }),
1323
+ home: this.home,
1101
1324
  harnesses: this.loadedHarnesses(),
1102
1325
  models: this.loadedModels(),
1103
1326
  efforts: this.loadedEfforts(),
1327
+ capabilities: this.loadedCapabilities(),
1328
+ stepLoaded: (use) => this.stepIndex.has(use),
1329
+ ...(this.onCancelRun === undefined ? {} : { runs: this.runControl() }),
1104
1330
  };
1105
1331
  }
1106
1332
 
1107
- /** Runs an action on an object, by `plugin/action` or a unique plain name. */
1333
+ /**
1334
+ * Runs another action on an object with the checks a person's action gets
1335
+ * (availability, arguments, confirmation), but without a note or files. An
1336
+ * action that forwards a person's text to another uses it; `yes` answers a
1337
+ * confirmation. The action's own check runs before anything is recorded.
1338
+ */
1339
+ async runActionChecked(
1340
+ name: string,
1341
+ args: unknown,
1342
+ options: {
1343
+ readonly object: RunObject;
1344
+ readonly actor: Actor;
1345
+ readonly yes?: boolean | undefined;
1346
+ readonly cwd?: string | undefined;
1347
+ },
1348
+ ): Promise<ActionRun> {
1349
+ const object = options.object;
1350
+ const found = this.findAction(name, object.type);
1351
+ const ref: ObjectRef = { type: object.type, id: object.id };
1352
+ const env = this.actionEnv(ref);
1353
+ let holds: unknown;
1354
+ try {
1355
+ holds = await found.action.when(object.data, env);
1356
+ } catch (error) {
1357
+ throw new PluginError(
1358
+ `action "${found.plugin.name}:${found.action.name}" cannot run now: ${messageOf(error)}`,
1359
+ );
1360
+ }
1361
+ if (holds !== true) throw new PluginError(await this.refusalLine(found, ref, env));
1362
+ const schema =
1363
+ found.action.argsFor?.(object, env) ?? found.action.args;
1364
+ const personArgs = validateActionArgs(
1365
+ schema,
1366
+ args,
1367
+ `action "${found.plugin.name}:${found.action.name}"`,
1368
+ );
1369
+ if (found.action.confirm === true && options.yes !== true) {
1370
+ throw new PluginError(
1371
+ `action "${found.plugin.name}:${found.action.name}" needs confirmation`,
1372
+ );
1373
+ }
1374
+ return this.runAction(`${found.plugin.name}/${found.action.name}`, personArgs, {
1375
+ object,
1376
+ actor: options.actor,
1377
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
1378
+ });
1379
+ }
1380
+
1381
+ /** The line a refusal prints: the plugin's `why`, else the plain one. */
1382
+ private async refusalLine(
1383
+ found: { readonly plugin: LoadedPlugin; readonly action: ActionTypeDefinition },
1384
+ object: ObjectRef,
1385
+ env: ActionEnv,
1386
+ ): Promise<string> {
1387
+ const plain = `action "${found.plugin.name}:${found.action.name}" cannot run now`;
1388
+ if (found.action.why === undefined) return plain;
1389
+ const stored = await this.store.get(object.type, object.id);
1390
+ if (stored === undefined) return plain;
1391
+ try {
1392
+ const why = await found.action.why(stored, env);
1393
+ return why !== undefined && why.length > 0 ? why : plain;
1394
+ } catch (error) {
1395
+ this.log(
1396
+ `plugin "${found.plugin.name}": action "${found.action.name}": why failed: ${messageOf(error)}`,
1397
+ );
1398
+ return plain;
1399
+ }
1400
+ }
1401
+
1402
+ /** Runs an action, by `plugin/action` or a unique plain name. */
1108
1403
  async runAction(
1109
1404
  name: string,
1110
1405
  args: unknown,
1111
1406
  options: ActionRunOptions,
1112
1407
  ): Promise<ActionRun> {
1113
- const found = this.findAction(name, options.object.type);
1408
+ const object = options.object;
1409
+ const found = this.findAction(name, object?.type);
1114
1410
  const label = `action "${found.plugin.name}:${found.action.name}"`;
1411
+ const env = this.actionEnv(object === undefined ? undefined : { type: object.type, id: object.id });
1115
1412
  const personArgs = validateActionArgs(
1116
- found.action.argsFor?.(options.object, this.actionEnv()) ?? found.action.args,
1413
+ (object === undefined ? undefined : found.action.argsFor?.(object, env)) ?? found.action.args,
1117
1414
  args,
1118
1415
  label,
1119
1416
  );
@@ -1130,7 +1427,9 @@ export class PluginRegistry {
1130
1427
  // it never changes the object's data.
1131
1428
  await this.store.append({
1132
1429
  type: "action_invoked",
1133
- object: { type: options.object.type, id: options.object.id },
1430
+ ...(object === undefined
1431
+ ? {}
1432
+ : { object: { type: object.type, id: object.id } }),
1134
1433
  cause,
1135
1434
  data: {
1136
1435
  action: `${found.plugin.name}/${found.action.name}`,
@@ -1153,13 +1452,30 @@ export class PluginRegistry {
1153
1452
  signal: options.signal ?? new AbortController().signal,
1154
1453
  settings: this.settingsFor(found.plugin.name),
1155
1454
  secrets: this.secretsFor(found.plugin.name),
1455
+ setup: this.setupReader(),
1156
1456
  runId,
1157
- object: options.object,
1457
+ // A targetless action has no object; it runs from its arguments alone.
1458
+ object: object ?? { type: "", id: "", data: {} },
1158
1459
  actor,
1159
1460
  answer,
1160
1461
  harnesses: this.loadedHarnesses(),
1462
+ ...(this.runLookup === undefined ? {} : { runLookup: this.runLookup }),
1463
+ stepLoaded: (use) => this.stepIndex.has(use),
1161
1464
  models: this.loadedModels(),
1162
1465
  efforts: this.loadedEfforts(),
1466
+ capabilities: this.loadedCapabilities(),
1467
+ actions: object === undefined ? [] : await this.actionInfosFor(object),
1468
+ ...(object === undefined
1469
+ ? {}
1470
+ : {
1471
+ act: (name: string, args: unknown, actOptions?: { readonly yes?: boolean | undefined }) =>
1472
+ this.runActionChecked(name, args, {
1473
+ object,
1474
+ actor,
1475
+ ...(actOptions?.yes === undefined ? {} : { yes: actOptions.yes }),
1476
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
1477
+ }),
1478
+ }),
1163
1479
  ...(this.onEvent === undefined
1164
1480
  ? {}
1165
1481
  : { emit: this.actionEmitter(found.plugin.name) }),
@@ -1207,40 +1523,104 @@ export class PluginRegistry {
1207
1523
  };
1208
1524
  }
1209
1525
 
1210
- /** Runs each plugin's optional `check`; a throw is a failed check, not an error. */
1526
+ /** Runs one loaded plugin's `check`; a throw is a failed check, not an error. */
1527
+ private async runCheck(plugin: LoadedPlugin): Promise<PluginCheck | undefined> {
1528
+ if (plugin.check === undefined) return undefined;
1529
+ const ctx: PluginBaseContext = {
1530
+ plugin: plugin.name,
1531
+ home: this.home,
1532
+ cwd: this.cwd,
1533
+ store: this.store,
1534
+ facts: this.factsFor(`check:${plugin.name}`),
1535
+ logger: createPluginLogger(this.store.root, plugin.name, "check"),
1536
+ signal: new AbortController().signal,
1537
+ settings: this.settingsFor(plugin.name),
1538
+ secrets: this.secretsFor(plugin.name),
1539
+ };
1540
+ try {
1541
+ const result = await plugin.check(ctx);
1542
+ if (typeof result === "string") {
1543
+ return { plugin: plugin.name, ok: true, message: result };
1544
+ }
1545
+ if (result === undefined) {
1546
+ return { plugin: plugin.name, ok: true, message: "ok" };
1547
+ }
1548
+ const missing = missingItemsOf(result);
1549
+ const note = typeof result.note === "string" ? result.note : undefined;
1550
+ return {
1551
+ plugin: plugin.name,
1552
+ ok: true,
1553
+ message: note ?? (missing.length === 0 ? "ok" : missing.map((item) => item.description).join("; ")),
1554
+ missing,
1555
+ };
1556
+ } catch (error) {
1557
+ return { plugin: plugin.name, ok: false, message: messageOf(error) };
1558
+ }
1559
+ }
1560
+
1561
+ /** Runs each plugin's optional `check`. */
1211
1562
  async checks(): Promise<readonly PluginCheck[]> {
1212
1563
  const checks: PluginCheck[] = [];
1213
1564
  for (const plugin of this.plugins) {
1214
- if (plugin.check === undefined) continue;
1215
- const ctx: PluginBaseContext = {
1216
- plugin: plugin.name,
1217
- home: this.home,
1218
- cwd: this.cwd,
1219
- store: this.store,
1220
- facts: this.factsFor(`check:${plugin.name}`),
1221
- logger: createPluginLogger(this.store.root, plugin.name, "check"),
1222
- signal: new AbortController().signal,
1223
- settings: this.settingsFor(plugin.name),
1224
- secrets: this.secretsFor(plugin.name),
1225
- };
1226
- try {
1227
- const note = await plugin.check(ctx);
1228
- checks.push({
1229
- plugin: plugin.name,
1230
- ok: true,
1231
- message: typeof note === "string" ? note : "ok",
1232
- });
1233
- } catch (error) {
1234
- checks.push({
1235
- plugin: plugin.name,
1236
- ok: false,
1237
- message: messageOf(error),
1238
- });
1239
- }
1565
+ const check = await this.runCheck(plugin);
1566
+ if (check !== undefined) checks.push(check);
1240
1567
  }
1241
1568
  return checks;
1242
1569
  }
1243
1570
 
1571
+ /**
1572
+ * The setup guides (ADR 0010 D7): a loaded plugin's guide with what its check
1573
+ * reports missing, an off plugin's guide with the one item `enable`.
1574
+ */
1575
+ setupReader(): SetupReader {
1576
+ const read = async (path: string): Promise<string | undefined> => {
1577
+ try {
1578
+ return guideBody(await readFile(path, "utf8"));
1579
+ } catch {
1580
+ return undefined;
1581
+ }
1582
+ };
1583
+ return {
1584
+ list: async () => {
1585
+ const found: { plugin: string; enabled: boolean }[] = [];
1586
+ for (const plugin of this.plugins) {
1587
+ if (plugin.guide !== undefined) found.push({ plugin: plugin.name, enabled: true });
1588
+ }
1589
+ for (const name of this.offNames) {
1590
+ if ((await this.disabledGuide?.(name)) !== undefined) found.push({ plugin: name, enabled: false });
1591
+ }
1592
+ return found;
1593
+ },
1594
+ get: async (name): Promise<SetupGuide | undefined> => {
1595
+ const plugin = this.plugins.find((item) => item.name === name);
1596
+ if (plugin !== undefined) {
1597
+ if (plugin.guide === undefined) return undefined;
1598
+ const text = await read(plugin.guide);
1599
+ if (text === undefined) return undefined;
1600
+ const check = await this.runCheck(plugin);
1601
+ const missing: readonly MissingItem[] =
1602
+ check === undefined
1603
+ ? []
1604
+ : check.ok
1605
+ ? (check.missing ?? [])
1606
+ : [{ name: "check", description: `the check failed: ${check.message}` }];
1607
+ return { plugin: name, enabled: true, text, missing };
1608
+ }
1609
+ if (!this.offNames.has(name)) return undefined;
1610
+ const path = await this.disabledGuide?.(name);
1611
+ if (path === undefined) return undefined;
1612
+ const text = await read(path);
1613
+ if (text === undefined) return undefined;
1614
+ return {
1615
+ plugin: name,
1616
+ enabled: false,
1617
+ text,
1618
+ missing: [{ name: "enable", description: `the plugin "${name}" is off` }],
1619
+ };
1620
+ },
1621
+ };
1622
+ }
1623
+
1244
1624
  /**
1245
1625
  * The short form `<command>`: offered only when exactly one plugin declares
1246
1626
  * the name and it is not a kernel verb. A command left without a short form
@@ -1344,6 +1724,8 @@ export class PluginRegistry {
1344
1724
  signal: options.signal ?? new AbortController().signal,
1345
1725
  settings: this.settingsFor(plugin.name),
1346
1726
  secrets: this.secretsFor(plugin.name),
1727
+ setup: this.setupReader(),
1728
+ flows: this.flows().map((entry) => entry.flow.name),
1347
1729
  ...(options.input === undefined ? {} : { input: options.input }),
1348
1730
  ...(this.onCancelRun === undefined ? {} : { runs: this.runControl() }),
1349
1731
  };
@@ -1355,11 +1737,12 @@ export class PluginRegistry {
1355
1737
  * The items plugins ask a person to know about. A hook that throws is
1356
1738
  * logged and shows nothing, so one plugin cannot hide the others.
1357
1739
  */
1358
- async standing(): Promise<readonly StandingEntry[]> {
1740
+ async standing(runs?: RunLookup): Promise<readonly StandingEntry[]> {
1359
1741
  const items: StandingEntry[] = [];
1360
1742
  for (const plugin of this.plugins) {
1361
1743
  if (plugin.standing === undefined) continue;
1362
1744
  try {
1745
+ const lookup = runs ?? this.runLookup;
1363
1746
  const found = await plugin.standing({
1364
1747
  plugin: plugin.name,
1365
1748
  home: this.home,
@@ -1371,6 +1754,10 @@ export class PluginRegistry {
1371
1754
  settings: this.settingsFor(plugin.name),
1372
1755
  secrets: this.secretsFor(plugin.name),
1373
1756
  loaded: this.plugins.map((item) => item.name),
1757
+ harnesses: this.plugins.filter((item) => item.kind === "harness").map((item) => item.name),
1758
+ ...(lookup === undefined ? {} : { runLookup: lookup }),
1759
+ signedIn: (harness) => this.signedInFor(harness),
1760
+ stepLoaded: (use) => this.stepIndex.has(use),
1374
1761
  });
1375
1762
  for (const item of found) {
1376
1763
  const object =
@@ -1401,10 +1788,11 @@ export class PluginRegistry {
1401
1788
  /** The actions whose `when` holds for the object; a throwing `when` is logged and hidden. */
1402
1789
  private async actionsHolding(object: StoredObject): Promise<readonly PendingActionView[]> {
1403
1790
  const held: { plugin: string; action: string; rank: number }[] = [];
1791
+ const env = this.actionEnv({ type: object.type, id: object.id });
1404
1792
  for (const { plugin, action } of this.actionsFor(object.type)) {
1405
1793
  let holds: unknown;
1406
1794
  try {
1407
- holds = await action.when(object.data, this.actionEnv());
1795
+ holds = await action.when(object.data, env);
1408
1796
  } catch (error) {
1409
1797
  this.log(
1410
1798
  `plugin "${plugin.name}": action "${action.name}": when failed: ${messageOf(error)}`,
@@ -1438,6 +1826,7 @@ export class PluginRegistry {
1438
1826
  runId: run.runId,
1439
1827
  prompt: run.prompt,
1440
1828
  choices: run.choices,
1829
+ ...(run.choiceInfo === undefined ? {} : { choiceInfo: run.choiceInfo }),
1441
1830
  object: {
1442
1831
  type: run.object.type,
1443
1832
  id: run.object.id,
@@ -1456,6 +1845,7 @@ export class PluginRegistry {
1456
1845
  runId: run.runId,
1457
1846
  prompt: run.prompt,
1458
1847
  choices: run.choices,
1848
+ ...(run.choiceInfo === undefined ? {} : { choiceInfo: run.choiceInfo }),
1459
1849
  object,
1460
1850
  actions,
1461
1851
  });
@@ -1463,6 +1853,14 @@ export class PluginRegistry {
1463
1853
  return entries;
1464
1854
  }
1465
1855
 
1856
+ /**
1857
+ * Gives the standing and action hooks the kernel's runs, so a plugin does not
1858
+ * offer a second run while one is live. `serve` calls it once its log is open.
1859
+ */
1860
+ useRunLookup(runs: RunLookup | undefined): void {
1861
+ this.runLookup = runs;
1862
+ }
1863
+
1466
1864
  /** Runs each plugin's `onTick` once; a failure is logged, not raised. */
1467
1865
  async tick(runs?: RunLookup): Promise<void> {
1468
1866
  for (const plugin of this.plugins) {
@@ -1553,15 +1951,13 @@ export class PluginRegistry {
1553
1951
  return [...this.starts];
1554
1952
  }
1555
1953
 
1556
- /** The loaded source plugins, with the function that starts each one. */
1954
+ /** The loaded plugins that start a source, with the function that starts each one. */
1557
1955
  sourcePlugins(): readonly {
1558
1956
  readonly plugin: string;
1559
1957
  readonly start: (ctx: SourceContext) => MaybePromise<SourceHandle> | SourceHandle;
1560
1958
  }[] {
1561
1959
  return this.plugins.flatMap((plugin) =>
1562
- plugin.kind !== "source" || plugin.start === undefined
1563
- ? []
1564
- : [{ plugin: plugin.name, start: plugin.start }],
1960
+ plugin.start === undefined ? [] : [{ plugin: plugin.name, start: plugin.start }],
1565
1961
  );
1566
1962
  }
1567
1963
 
@@ -1578,7 +1974,7 @@ export class PluginRegistry {
1578
1974
  }): Promise<readonly { readonly plugin: string; readonly handle: SourceHandle }[]> {
1579
1975
  const running: { plugin: string; handle: SourceHandle }[] = [];
1580
1976
  for (const plugin of this.plugins) {
1581
- if (plugin.kind !== "source" || plugin.start === undefined) continue;
1977
+ if (plugin.start === undefined) continue;
1582
1978
  const emit = async (event: SourceEvent): Promise<void> => {
1583
1979
  const trigger: TriggerEvent = {
1584
1980
  source: event.source ?? plugin.name,
@@ -1608,10 +2004,13 @@ export class PluginRegistry {
1608
2004
  signal: options.signal ?? new AbortController().signal,
1609
2005
  rules: options.rules,
1610
2006
  clock: options.clock,
2007
+ harnesses: this.plugins.filter((item) => item.kind === "harness").map((item) => item.name),
2008
+ harnessCapabilities: (name) => this.loadedCapabilities()[name],
1611
2009
  settings: this.settingsFor(plugin.name),
1612
2010
  secrets: this.secretsFor(plugin.name),
1613
2011
  emit,
1614
2012
  client: options.client,
2013
+ ...(this.onCancelRun === undefined ? {} : { runs: this.runControl() }),
1615
2014
  };
1616
2015
  try {
1617
2016
  const handle = await plugin.start(ctx);
@@ -1623,9 +2022,33 @@ export class PluginRegistry {
1623
2022
  return running;
1624
2023
  }
1625
2024
 
1626
- /** Removes and returns the start requests collected so far. */
1627
- takeStartedRuns(): StartRunRequest[] {
1628
- return this.starts.splice(0);
2025
+ /**
2026
+ * Removes and returns the start requests collected so far, or the oldest
2027
+ * `count` of them, so a loop drains only what it has tried.
2028
+ */
2029
+ takeStartedRuns(count?: number): StartRunRequest[] {
2030
+ return count === undefined ? this.starts.splice(0) : this.starts.splice(0, count);
2031
+ }
2032
+
2033
+ /** The actions declared on an object's type, each with whether it is available now. */
2034
+ private async actionInfosFor(object: RunObject): Promise<readonly ActionInfo[]> {
2035
+ const env = this.actionEnv({ type: object.type, id: object.id });
2036
+ const holding = new Set<string>();
2037
+ for (const { plugin, action } of this.actionsFor(object.type)) {
2038
+ let holds: unknown;
2039
+ try {
2040
+ holds = await action.when(object.data, env);
2041
+ } catch (error) {
2042
+ this.log(
2043
+ `plugin "${plugin.name}": action "${action.name}": when failed: ${messageOf(error)}`,
2044
+ );
2045
+ continue;
2046
+ }
2047
+ if (holds === true) holding.add(`${plugin.name}:${action.name}`);
2048
+ }
2049
+ return this.actionInfos
2050
+ .filter((info) => info.on === object.type)
2051
+ .map((info) => ({ ...info, available: holding.has(info.name) }));
1629
2052
  }
1630
2053
 
1631
2054
  private actionsFor(
@@ -1648,7 +2071,7 @@ export class PluginRegistry {
1648
2071
 
1649
2072
  private findAction(
1650
2073
  name: string,
1651
- objectType: string,
2074
+ objectType?: string | undefined,
1652
2075
  ): { readonly plugin: LoadedPlugin; readonly action: ActionTypeDefinition } {
1653
2076
  const named = splitActionName(name);
1654
2077
  if (named !== undefined) {
@@ -1657,7 +2080,11 @@ export class PluginRegistry {
1657
2080
  const plugin = this.byName.get(pluginName);
1658
2081
  if (plugin !== undefined) {
1659
2082
  const action = plugin.actions.find(
1660
- (item) => item.name === actionName && item.on === objectType,
2083
+ (item) =>
2084
+ item.name === actionName &&
2085
+ (objectType === undefined
2086
+ ? item.on === undefined
2087
+ : item.on === objectType),
1661
2088
  );
1662
2089
  if (action !== undefined) return { plugin, action };
1663
2090
  const other = plugin.actions.find((item) => item.name === actionName);
@@ -1687,7 +2114,9 @@ export class PluginRegistry {
1687
2114
  throw new PluginError(`action "${name}": no loaded plugin declares it`);
1688
2115
  }
1689
2116
  const action =
1690
- found.actions.find((item) => item.on === objectType) ?? found.actions[0];
2117
+ found.actions.find((item) =>
2118
+ objectType === undefined ? item.on === undefined : item.on === objectType,
2119
+ ) ?? found.actions[0];
1691
2120
  if (action === undefined) {
1692
2121
  throw new PluginError(`action "${name}": no loaded plugin declares it`);
1693
2122
  }
@@ -1698,11 +2127,19 @@ export class PluginRegistry {
1698
2127
  private requireActionObject(
1699
2128
  plugin: LoadedPlugin,
1700
2129
  action: ActionTypeDefinition,
1701
- objectType: string,
2130
+ objectType?: string | undefined,
1702
2131
  ): void {
2132
+ if (objectType === undefined) {
2133
+ if (action.on !== undefined) {
2134
+ throw new PluginError(
2135
+ `plugin "${plugin.name}": action "${action.name}": on: expected no object, got object type "${action.on}"`,
2136
+ );
2137
+ }
2138
+ return;
2139
+ }
1703
2140
  if (action.on !== objectType) {
1704
2141
  throw new PluginError(
1705
- `plugin "${plugin.name}": action "${action.name}": on: expected object type "${action.on}", got "${objectType}"`,
2142
+ `plugin "${plugin.name}": action "${action.name}": on: expected object type "${action.on ?? "none"}", got "${objectType}"`,
1706
2143
  );
1707
2144
  }
1708
2145
  }
@@ -1773,9 +2210,15 @@ export class PluginRegistry {
1773
2210
 
1774
2211
  private runControl(): RunControl {
1775
2212
  const onCancelRun = this.onCancelRun;
2213
+ const onRunActive = this.onRunActive;
1776
2214
  return {
1777
2215
  cancel: async (runId, flow) => {
1778
- if (onCancelRun !== undefined) await onCancelRun(runId, flow);
2216
+ if (onCancelRun !== undefined) return await onCancelRun(runId, flow);
2217
+ return false;
2218
+ },
2219
+ active: async (runId) => {
2220
+ if (onRunActive !== undefined) return await onRunActive(runId);
2221
+ return undefined;
1779
2222
  },
1780
2223
  };
1781
2224
  }