@operad-io/engine 0.0.0-stage → 0.0.1
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.
- package/LICENSE +21 -0
- package/config.schema.json +188 -0
- package/keys.schema.json +12 -0
- package/package.json +22 -4
- package/src/config/config.ts +627 -0
- package/src/config/index.ts +1 -0
- package/src/flow/define-flow.ts +57 -0
- package/src/flow/index.ts +5 -0
- package/src/flow/load.ts +41 -0
- package/src/flow/types.ts +107 -0
- package/src/flow/validate.ts +296 -0
- package/src/http/address.ts +142 -0
- package/src/http/index.ts +25 -0
- package/src/http/link.ts +20 -0
- package/src/http/server.ts +920 -0
- package/src/http/token.ts +85 -0
- package/src/index.ts +16 -0
- package/src/kernel/decide.ts +689 -0
- package/src/kernel/index.ts +3 -0
- package/src/kernel/state.ts +275 -0
- package/src/kernel/types.ts +366 -0
- package/src/log/errors.ts +77 -0
- package/src/log/facts.ts +50 -0
- package/src/log/index.ts +6 -0
- package/src/log/json-value.ts +67 -0
- package/src/log/open-log.ts +17 -0
- package/src/log/schema.ts +5 -0
- package/src/log/secret.ts +30 -0
- package/src/log/sqlite.ts +1011 -0
- package/src/log/types.ts +230 -0
- package/src/loop/code-watch.ts +486 -0
- package/src/loop/index.ts +3 -0
- package/src/loop/older-code.ts +58 -0
- package/src/loop/serve.ts +483 -0
- package/src/markdown.ts +451 -0
- package/src/notify/index.ts +10 -0
- package/src/notify/notify.ts +256 -0
- package/src/platform/file-lock.ts +385 -0
- package/src/platform/index.ts +13 -0
- package/src/platform/load.ts +18 -0
- package/src/platform/process-group.ts +635 -0
- package/src/platform/process-watch.ts +152 -0
- package/src/platform/sqlite-open.ts +104 -0
- package/src/platform/step-reap.ts +668 -0
- package/src/platform/watch.ts +158 -0
- package/src/platform/worker-reports.ts +34 -0
- package/src/plugin/action-schema.ts +550 -0
- package/src/plugin/declared-flows.ts +74 -0
- package/src/plugin/define-plugin.ts +12 -0
- package/src/plugin/errors.ts +73 -0
- package/src/plugin/filters.ts +46 -0
- package/src/plugin/harness.ts +50 -0
- package/src/plugin/home.ts +13 -0
- package/src/plugin/index.ts +65 -0
- package/src/plugin/install.ts +268 -0
- package/src/plugin/keys.ts +63 -0
- package/src/plugin/load.ts +256 -0
- package/src/plugin/logger.ts +30 -0
- package/src/plugin/object-facts.ts +132 -0
- package/src/plugin/open-store.ts +32 -0
- package/src/plugin/paging.ts +133 -0
- package/src/plugin/registry.ts +1783 -0
- package/src/plugin/secrets.ts +141 -0
- package/src/plugin/semver.ts +110 -0
- package/src/plugin/settings.ts +64 -0
- package/src/plugin/sqlite-store.ts +756 -0
- package/src/plugin/store.ts +318 -0
- package/src/plugin/types.ts +1236 -0
- package/src/plugin/usage.ts +157 -0
- package/src/plugin/validate.ts +1028 -0
- package/src/runner/answer.ts +156 -0
- package/src/runner/ask.ts +483 -0
- package/src/runner/cancel.ts +51 -0
- package/src/runner/errors.ts +20 -0
- package/src/runner/grants.ts +92 -0
- package/src/runner/index.ts +33 -0
- package/src/runner/limits.ts +403 -0
- package/src/runner/lock.ts +140 -0
- package/src/runner/runner.ts +1175 -0
- package/src/runner/service.ts +184 -0
- package/src/runner/step-worker.ts +303 -0
- package/src/testing/clock.ts +67 -0
- package/src/testing/index.ts +90 -0
- package/src/testing/types.ts +116 -0
- package/src/testing/world.ts +369 -0
- package/src/trigger/cron.ts +193 -0
- package/src/trigger/index.ts +32 -0
- package/src/trigger/kernel.ts +1212 -0
- package/src/trigger/rules.ts +300 -0
- package/src/trigger/store.ts +233 -0
- package/src/trigger/types.ts +156 -0
- package/src/util.ts +50 -0
- package/src/views/history.ts +634 -0
- package/src/views/index.ts +7 -0
- package/src/views/pending.ts +209 -0
- package/src/views/presentation.ts +2551 -0
- package/src/views/running.ts +255 -0
- package/src/views/settings.ts +452 -0
- package/src/views/types.ts +72 -0
- package/src/views/uploads.ts +228 -0
- package/triggers.schema.json +48 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1783 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import type { FlowDefinition, StepType } from "../flow/types.ts";
|
|
3
|
+
import { loadFlow as loadFlowFile } from "../flow/load.ts";
|
|
4
|
+
import { FlowError, validateFlow } from "../flow/validate.ts";
|
|
5
|
+
import type { JsonValue } from "../log/types.ts";
|
|
6
|
+
import { validateActionArgs } from "./action-schema.ts";
|
|
7
|
+
import { readDeclaredFlows, writeDeclaredFlow } from "./declared-flows.ts";
|
|
8
|
+
import { AccessError, AskTimeoutError, messageOf, PluginError, StepNotLoadedError } from "./errors.ts";
|
|
9
|
+
import { defaultOperadHome } from "./home.ts";
|
|
10
|
+
import { createPluginLogger } from "./logger.ts";
|
|
11
|
+
import { FileSecretStore } from "./secrets.ts";
|
|
12
|
+
import { satisfiesRange } from "./semver.ts";
|
|
13
|
+
import { enterStep, reapStep, withStepMarker, type StepMarker } from "../platform/step-reap.ts";
|
|
14
|
+
import { prepareSettings } from "./settings.ts";
|
|
15
|
+
import { MemoryPluginStore } from "./store.ts";
|
|
16
|
+
import {
|
|
17
|
+
PLUGIN_API_VERSION,
|
|
18
|
+
type ActionArgsSchema,
|
|
19
|
+
type ProjectSettingsDeclaration,
|
|
20
|
+
type ActionContext,
|
|
21
|
+
type ActionEnv,
|
|
22
|
+
type HarnessEfforts,
|
|
23
|
+
type HarnessModels,
|
|
24
|
+
type ActionEvent,
|
|
25
|
+
type ActionRun,
|
|
26
|
+
isActionOutcome,
|
|
27
|
+
type ActionRunOptions,
|
|
28
|
+
type ActionTypeDefinition,
|
|
29
|
+
type ObjectData,
|
|
30
|
+
type Actor,
|
|
31
|
+
type Answer,
|
|
32
|
+
type CommandContext,
|
|
33
|
+
type CommandDefinition,
|
|
34
|
+
type CommandRun,
|
|
35
|
+
type CommandRunOptions,
|
|
36
|
+
type FactInput,
|
|
37
|
+
type FactWriter,
|
|
38
|
+
type MaybePromise,
|
|
39
|
+
type ObjectRef,
|
|
40
|
+
type StoredObject,
|
|
41
|
+
type ObjectTypeDefinition,
|
|
42
|
+
type RunLookup,
|
|
43
|
+
type ObjectViews,
|
|
44
|
+
type KeyBindings,
|
|
45
|
+
type PendingActionView,
|
|
46
|
+
type PendingEntry,
|
|
47
|
+
type StandingContext,
|
|
48
|
+
type StandingItem,
|
|
49
|
+
type PluginBaseContext,
|
|
50
|
+
type PluginCheck,
|
|
51
|
+
type PluginKind,
|
|
52
|
+
type PluginRequires,
|
|
53
|
+
type PluginStepResult,
|
|
54
|
+
type PluginStore,
|
|
55
|
+
type ResolvedCommand,
|
|
56
|
+
type RunControl,
|
|
57
|
+
type SecretStore,
|
|
58
|
+
type SourceContext,
|
|
59
|
+
type SourceHandle,
|
|
60
|
+
type StartRunRequest,
|
|
61
|
+
MAX_ASK_GRACE_SECS,
|
|
62
|
+
type AskAnswer,
|
|
63
|
+
type AskRequest,
|
|
64
|
+
type StepContext,
|
|
65
|
+
type StepRunOptions,
|
|
66
|
+
type StepTypeDefinition,
|
|
67
|
+
type TickContext,
|
|
68
|
+
type WaitingRun,
|
|
69
|
+
} from "./types.ts";
|
|
70
|
+
import type {
|
|
71
|
+
SourceEvent,
|
|
72
|
+
StepEvent,
|
|
73
|
+
TriggerEvent,
|
|
74
|
+
TriggerRule,
|
|
75
|
+
} from "../trigger/types.ts";
|
|
76
|
+
import { askGraceOf, collectStepTypes, grantRequestProblem, narrowerOf, noteInfo, normalizePlugin, parseObjectKeyMaybe, splitActionName, validateFlows, validatePluginSet, validateRuleFlows, type LoadedPlugin } from "./validate.ts";
|
|
77
|
+
import { isRecord } from "../util.ts";
|
|
78
|
+
|
|
79
|
+
export { splitActionName };
|
|
80
|
+
|
|
81
|
+
/** An action's rank for an object's data; a failing `rank` counts as 0. */
|
|
82
|
+
export function rankOf(action: ActionTypeDefinition, data: ObjectData): number {
|
|
83
|
+
if (action.rank === undefined) return 0;
|
|
84
|
+
try {
|
|
85
|
+
const rank = action.rank(data);
|
|
86
|
+
return Number.isFinite(rank) ? rank : 0;
|
|
87
|
+
} catch {
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Orders by rank, lower first; equal ranks keep their order. */
|
|
93
|
+
export function sortByRank<T extends { readonly rank: number }>(items: readonly T[]): T[] {
|
|
94
|
+
return items
|
|
95
|
+
.map((item, at) => ({ item, at }))
|
|
96
|
+
.sort((a, b) => a.item.rank - b.item.rank || a.at - b.at)
|
|
97
|
+
.map(({ item }) => item);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Options for building a registry from plugin definitions. */
|
|
101
|
+
export interface PluginRegistryOptions {
|
|
102
|
+
readonly home?: string | undefined;
|
|
103
|
+
readonly cwd?: string | undefined;
|
|
104
|
+
readonly store?: PluginStore | undefined;
|
|
105
|
+
readonly storeRoot?: string | undefined;
|
|
106
|
+
readonly clock?: (() => number) | undefined;
|
|
107
|
+
/** The person's key overrides; a key here wins over every plugin default. */
|
|
108
|
+
readonly keys?: KeyBindings | undefined;
|
|
109
|
+
/** Verbs the kernel itself owns; a plugin cannot take them as a short form. */
|
|
110
|
+
readonly kernelVerbs?: readonly string[] | undefined;
|
|
111
|
+
/** Where load-time and runtime plugin errors go. Defaults to stderr. */
|
|
112
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
113
|
+
/** Called when a plugin's `onTick` asks the kernel to start a run. */
|
|
114
|
+
readonly onStartRun?:
|
|
115
|
+
| ((request: StartRunRequest) => MaybePromise<void>)
|
|
116
|
+
| undefined;
|
|
117
|
+
/** Answers a person wait for an action; the action calls `ctx.answer`. */
|
|
118
|
+
readonly onAnswer?:
|
|
119
|
+
| ((
|
|
120
|
+
runId: string,
|
|
121
|
+
choice: string,
|
|
122
|
+
note: string | undefined,
|
|
123
|
+
actor: Actor,
|
|
124
|
+
) => MaybePromise<void>)
|
|
125
|
+
| undefined;
|
|
126
|
+
/** Cancels one run when a plugin action asks; the kernel writes the input. */
|
|
127
|
+
readonly onCancelRun?:
|
|
128
|
+
| ((runId: string, flow?: FlowDefinition) => MaybePromise<void>)
|
|
129
|
+
| undefined;
|
|
130
|
+
/** The specifier each definition was loaded from, aligned with it. */
|
|
131
|
+
readonly sources?: readonly (string | undefined)[] | undefined;
|
|
132
|
+
/** The raw config section of each plugin, keyed by plugin name. */
|
|
133
|
+
readonly settings?: Readonly<Record<string, unknown>> | undefined;
|
|
134
|
+
/** Plugins the config switched off; a dependent is refused with the reason. */
|
|
135
|
+
readonly disabled?: readonly string[] | undefined;
|
|
136
|
+
/** Whether to resolve `requires` against the loaded plugins. */
|
|
137
|
+
readonly requireDependencies?: boolean | undefined;
|
|
138
|
+
/** Whether to validate each plugin's settings section. */
|
|
139
|
+
readonly validateSettings?: boolean | undefined;
|
|
140
|
+
/** The routing rules, given to source plugins. */
|
|
141
|
+
readonly rules?: readonly TriggerRule[] | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* Called when an action sends an event with `ctx.emit`: the kernel routes it
|
|
144
|
+
* through the rules. Without it an action has no `emit`.
|
|
145
|
+
*/
|
|
146
|
+
readonly onEvent?: ((event: TriggerEvent) => MaybePromise<void>) | undefined;
|
|
147
|
+
/** Called when a source plugin sends an event. */
|
|
148
|
+
readonly onSourceEvent?:
|
|
149
|
+
| ((event: TriggerEvent, plugin: string) => MaybePromise<void>)
|
|
150
|
+
| undefined;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A plugin the registry left out, and the line that says why. */
|
|
154
|
+
export interface PluginRefusal {
|
|
155
|
+
readonly plugin: string;
|
|
156
|
+
readonly message: string;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** One action a client may offer, with what it needs from the person. */
|
|
160
|
+
export interface ActionInfo {
|
|
161
|
+
readonly plugin: string;
|
|
162
|
+
readonly action: string;
|
|
163
|
+
/** The object type the action works on. */
|
|
164
|
+
readonly on: string;
|
|
165
|
+
/** Addressed as `<plugin>:<action>`. */
|
|
166
|
+
readonly name: string;
|
|
167
|
+
/** The person's input, as a JSON Schema object. */
|
|
168
|
+
readonly args?: ActionArgsSchema | undefined;
|
|
169
|
+
/** The name of the note property, when the schema declares one. */
|
|
170
|
+
readonly note?: string | undefined;
|
|
171
|
+
readonly noteRequired: boolean;
|
|
172
|
+
readonly confirm: boolean;
|
|
173
|
+
/** The action ends the object, so a main key or button never runs it. */
|
|
174
|
+
readonly ends?: boolean | undefined;
|
|
175
|
+
/** The object type the action creates; a client lists it where that type is created. */
|
|
176
|
+
readonly creates?: string | undefined;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Where a key binding came from. */
|
|
180
|
+
export interface KeyBinding {
|
|
181
|
+
readonly key: string;
|
|
182
|
+
readonly plugin: string;
|
|
183
|
+
readonly action: string;
|
|
184
|
+
readonly name: string;
|
|
185
|
+
readonly source: "plugin" | "user";
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** One standing item with the plugin that gave it, and the actions that hold for its object. */
|
|
189
|
+
export interface StandingEntry {
|
|
190
|
+
readonly plugin: string;
|
|
191
|
+
readonly id: string;
|
|
192
|
+
readonly prompt: string;
|
|
193
|
+
readonly object?: ObjectRef;
|
|
194
|
+
readonly actions: readonly PendingActionView[];
|
|
195
|
+
readonly announce?: false;
|
|
196
|
+
/** Object keys (`type:id`) the item stands for besides its own. */
|
|
197
|
+
readonly covers?: readonly string[];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Holds the loaded plugins and gives the kernel the three entry points it
|
|
202
|
+
* needs: run a step, dispatch a command, and compute the pending view. The
|
|
203
|
+
* registry validates every plugin before the first one can be used.
|
|
204
|
+
*/
|
|
205
|
+
export class PluginRegistry {
|
|
206
|
+
readonly home: string;
|
|
207
|
+
readonly store: PluginStore;
|
|
208
|
+
|
|
209
|
+
private readonly cwd: string;
|
|
210
|
+
/** Runs whose missing object was already logged, so a poll does not repeat it. */
|
|
211
|
+
private readonly reportedMissing = new Set<string>();
|
|
212
|
+
private readonly kernelVerbs: ReadonlySet<string>;
|
|
213
|
+
private shortCommands: ReadonlyMap<
|
|
214
|
+
string,
|
|
215
|
+
{ readonly plugin: LoadedPlugin; readonly command: CommandDefinition }
|
|
216
|
+
> = new Map();
|
|
217
|
+
private readonly onLog: (message: string) => void;
|
|
218
|
+
private readonly onStartRun:
|
|
219
|
+
| ((request: StartRunRequest) => MaybePromise<void>)
|
|
220
|
+
| undefined;
|
|
221
|
+
private readonly onAnswer:
|
|
222
|
+
| ((
|
|
223
|
+
runId: string,
|
|
224
|
+
choice: string,
|
|
225
|
+
note: string | undefined,
|
|
226
|
+
actor: Actor,
|
|
227
|
+
) => MaybePromise<void>)
|
|
228
|
+
| undefined;
|
|
229
|
+
private readonly onCancelRun:
|
|
230
|
+
| ((runId: string, flow?: FlowDefinition) => MaybePromise<void>)
|
|
231
|
+
| undefined;
|
|
232
|
+
private readonly rules: readonly TriggerRule[];
|
|
233
|
+
private readonly onEvent: ((event: TriggerEvent) => MaybePromise<void>) | undefined;
|
|
234
|
+
private readonly onSourceEvent:
|
|
235
|
+
| ((event: TriggerEvent, plugin: string) => MaybePromise<void>)
|
|
236
|
+
| undefined;
|
|
237
|
+
private readonly plugins: readonly LoadedPlugin[];
|
|
238
|
+
private readonly byName: ReadonlyMap<string, LoadedPlugin>;
|
|
239
|
+
private readonly viewByType: ReadonlyMap<string, { readonly plugin: LoadedPlugin; readonly views: ObjectViews }>;
|
|
240
|
+
private readonly actionInfos: readonly ActionInfo[];
|
|
241
|
+
private readonly bindingByKey: ReadonlyMap<string, KeyBinding>;
|
|
242
|
+
private readonly sourceByPlugin: ReadonlyMap<string, string>;
|
|
243
|
+
private readonly stepIndex: ReadonlyMap<
|
|
244
|
+
string,
|
|
245
|
+
{ readonly plugin: LoadedPlugin; readonly step: StepTypeDefinition }
|
|
246
|
+
>;
|
|
247
|
+
private readonly starts: StartRunRequest[] = [];
|
|
248
|
+
/** Flows a plugin generated while the process ran, by name. */
|
|
249
|
+
private readonly declaredFlows = new Map<
|
|
250
|
+
string,
|
|
251
|
+
{ readonly plugin: string; readonly flow: FlowDefinition }
|
|
252
|
+
>();
|
|
253
|
+
private readonly refusalList: PluginRefusal[] = [];
|
|
254
|
+
private readonly settingsByPlugin: ReadonlyMap<
|
|
255
|
+
string,
|
|
256
|
+
Readonly<Record<string, JsonValue>>
|
|
257
|
+
>;
|
|
258
|
+
private readonly disabledNames: ReadonlySet<string>;
|
|
259
|
+
|
|
260
|
+
constructor(
|
|
261
|
+
definitions: readonly unknown[],
|
|
262
|
+
options: PluginRegistryOptions = {},
|
|
263
|
+
) {
|
|
264
|
+
this.home = options.home ?? defaultOperadHome();
|
|
265
|
+
this.cwd = options.cwd ?? process.cwd();
|
|
266
|
+
this.kernelVerbs = new Set(options.kernelVerbs ?? []);
|
|
267
|
+
this.onLog = options.onLog ?? ((message) => console.error(message));
|
|
268
|
+
this.onStartRun = options.onStartRun;
|
|
269
|
+
this.onAnswer = options.onAnswer;
|
|
270
|
+
this.onCancelRun = options.onCancelRun;
|
|
271
|
+
this.rules = options.rules ?? [];
|
|
272
|
+
this.onSourceEvent = options.onSourceEvent;
|
|
273
|
+
this.onEvent = options.onEvent;
|
|
274
|
+
|
|
275
|
+
const clock = options.clock ?? (() => Date.now());
|
|
276
|
+
this.store =
|
|
277
|
+
options.store ??
|
|
278
|
+
new MemoryPluginStore({
|
|
279
|
+
root: options.storeRoot ?? join(this.home, "store"),
|
|
280
|
+
clock,
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
const normalized = definitions.map((definition, index) =>
|
|
284
|
+
normalizePlugin(definition, index),
|
|
285
|
+
);
|
|
286
|
+
const sourceMap = new Map<string, string>();
|
|
287
|
+
for (const [index, plugin] of normalized.entries()) {
|
|
288
|
+
const source = options.sources?.[index];
|
|
289
|
+
if (source !== undefined) sourceMap.set(plugin.name, source);
|
|
290
|
+
}
|
|
291
|
+
this.sourceByPlugin = sourceMap;
|
|
292
|
+
this.disabledNames = new Set(options.disabled ?? []);
|
|
293
|
+
|
|
294
|
+
const settingsByPlugin = new Map<
|
|
295
|
+
string,
|
|
296
|
+
Readonly<Record<string, JsonValue>>
|
|
297
|
+
>();
|
|
298
|
+
const refused = new Set<string>();
|
|
299
|
+
const refuse = (plugin: string, message: string): void => {
|
|
300
|
+
if (refused.has(plugin)) return;
|
|
301
|
+
refused.add(plugin);
|
|
302
|
+
const line = message.startsWith(`plugin "${plugin}":`)
|
|
303
|
+
? message
|
|
304
|
+
: `plugin "${plugin}": ${message}`;
|
|
305
|
+
this.refusalList.push({ plugin, message: line });
|
|
306
|
+
this.log(line);
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
for (const plugin of normalized) {
|
|
310
|
+
if (plugin.settingsSchema === undefined || options.validateSettings === false) {
|
|
311
|
+
settingsByPlugin.set(plugin.name, Object.freeze({}));
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
settingsByPlugin.set(
|
|
316
|
+
plugin.name,
|
|
317
|
+
prepareSettings(
|
|
318
|
+
plugin.settingsSchema,
|
|
319
|
+
options.settings?.[plugin.name],
|
|
320
|
+
plugin.name,
|
|
321
|
+
),
|
|
322
|
+
);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
refuse(plugin.name, messageOf(error));
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (options.requireDependencies !== false) {
|
|
329
|
+
const versions = new Map(normalized.map((plugin) => [plugin.name, plugin.version]));
|
|
330
|
+
for (const plugin of normalized) {
|
|
331
|
+
if (refused.has(plugin.name)) continue;
|
|
332
|
+
const api = plugin.requires?.api;
|
|
333
|
+
if (api === undefined) continue;
|
|
334
|
+
let ok: boolean;
|
|
335
|
+
try {
|
|
336
|
+
ok = satisfiesRange(PLUGIN_API_VERSION, api);
|
|
337
|
+
} catch (error) {
|
|
338
|
+
refuse(plugin.name, `requires api "${api}": ${messageOf(error)}`);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (!ok) {
|
|
342
|
+
refuse(
|
|
343
|
+
plugin.name,
|
|
344
|
+
`requires api "${api}", but this engine provides ${PLUGIN_API_VERSION}`,
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
let changed = true;
|
|
350
|
+
while (changed) {
|
|
351
|
+
changed = false;
|
|
352
|
+
for (const plugin of normalized) {
|
|
353
|
+
if (refused.has(plugin.name)) continue;
|
|
354
|
+
for (const [dependency, range] of Object.entries(
|
|
355
|
+
plugin.requires?.plugins ?? {},
|
|
356
|
+
)) {
|
|
357
|
+
let reason: string | undefined;
|
|
358
|
+
if (refused.has(dependency)) {
|
|
359
|
+
reason = `requires plugin "${dependency}" "${range}", but "${dependency}" was refused`;
|
|
360
|
+
} else if (this.disabledNames.has(dependency)) {
|
|
361
|
+
reason = `requires plugin "${dependency}" "${range}", but "${dependency}" is disabled`;
|
|
362
|
+
} else {
|
|
363
|
+
const version = versions.get(dependency);
|
|
364
|
+
if (version === undefined) {
|
|
365
|
+
reason = `requires plugin "${dependency}" "${range}", but "${dependency}" is not loaded`;
|
|
366
|
+
} else {
|
|
367
|
+
let ok: boolean;
|
|
368
|
+
try {
|
|
369
|
+
ok = satisfiesRange(version, range);
|
|
370
|
+
} catch {
|
|
371
|
+
ok = false;
|
|
372
|
+
}
|
|
373
|
+
if (!ok) {
|
|
374
|
+
reason = `requires plugin "${dependency}" "${range}", but "${dependency}" is ${version}`;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (reason !== undefined) {
|
|
379
|
+
refuse(plugin.name, reason);
|
|
380
|
+
changed = true;
|
|
381
|
+
break;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
this.settingsByPlugin = settingsByPlugin;
|
|
389
|
+
const kept = normalized.filter((plugin) => !refused.has(plugin.name));
|
|
390
|
+
validatePluginSet(kept);
|
|
391
|
+
if (typeof this.store.declare === "function") {
|
|
392
|
+
for (const plugin of kept) {
|
|
393
|
+
for (const object of plugin.objects) {
|
|
394
|
+
this.store.declare(object.name, object.index ?? []);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const stepTypes = collectStepTypes(kept);
|
|
399
|
+
this.plugins = validateFlows(kept, stepTypes);
|
|
400
|
+
validateRuleFlows(this.plugins);
|
|
401
|
+
|
|
402
|
+
this.byName = new Map(this.plugins.map((plugin) => [plugin.name, plugin]));
|
|
403
|
+
this.shortCommands = this.resolveShortCommands();
|
|
404
|
+
|
|
405
|
+
const viewByType = new Map<
|
|
406
|
+
string,
|
|
407
|
+
{ readonly plugin: LoadedPlugin; readonly views: ObjectViews }
|
|
408
|
+
>();
|
|
409
|
+
const actionInfos: ActionInfo[] = [];
|
|
410
|
+
for (const plugin of this.plugins) {
|
|
411
|
+
for (const [type, views] of Object.entries(plugin.views)) {
|
|
412
|
+
viewByType.set(type, { plugin, views });
|
|
413
|
+
}
|
|
414
|
+
for (const action of plugin.actions) {
|
|
415
|
+
const note = noteInfo(action.args);
|
|
416
|
+
actionInfos.push({
|
|
417
|
+
plugin: plugin.name,
|
|
418
|
+
action: action.name,
|
|
419
|
+
on: action.on,
|
|
420
|
+
name: `${plugin.name}:${action.name}`,
|
|
421
|
+
...(action.args === undefined ? {} : { args: action.args }),
|
|
422
|
+
...(note.name === undefined ? {} : { note: note.name }),
|
|
423
|
+
noteRequired: note.required,
|
|
424
|
+
confirm: action.confirm === true,
|
|
425
|
+
...(action.ends === true ? { ends: true } : {}),
|
|
426
|
+
...(action.creates === undefined ? {} : { creates: action.creates }),
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
this.viewByType = viewByType;
|
|
431
|
+
this.actionInfos = actionInfos;
|
|
432
|
+
this.bindingByKey = this.resolveKeys(options.keys ?? {});
|
|
433
|
+
|
|
434
|
+
const stepIndex = new Map<
|
|
435
|
+
string,
|
|
436
|
+
{ readonly plugin: LoadedPlugin; readonly step: StepTypeDefinition }
|
|
437
|
+
>();
|
|
438
|
+
for (const plugin of this.plugins) {
|
|
439
|
+
for (const step of plugin.steps) {
|
|
440
|
+
stepIndex.set(`${plugin.name}/${step.name}`, { plugin, step });
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
this.stepIndex = stepIndex;
|
|
444
|
+
this.loadDeclaredFlows();
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Loads flows an earlier process declared, so a run can find its graph. */
|
|
448
|
+
private loadDeclaredFlows(): void {
|
|
449
|
+
if (this.store.kind !== "file") return;
|
|
450
|
+
for (const stored of readDeclaredFlows(this.store.root)) {
|
|
451
|
+
let flow: FlowDefinition;
|
|
452
|
+
try {
|
|
453
|
+
flow = validateFlow(stored.flow, this.stepTypes());
|
|
454
|
+
} catch {
|
|
455
|
+
// A flow whose steps this process cannot load is left for the loop to
|
|
456
|
+
// report when it tries to start a run of it.
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (this.flow(flow.name) !== undefined) continue;
|
|
460
|
+
this.declaredFlows.set(flow.name, { plugin: stored.plugin, flow });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Every action the loaded plugins declare, addressed as `plugin:action`. */
|
|
465
|
+
actions(): readonly ActionInfo[] {
|
|
466
|
+
return this.actionInfos;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** The default and user key bindings in force, by key. */
|
|
470
|
+
keyBindings(): readonly KeyBinding[] {
|
|
471
|
+
return [...this.bindingByKey.values()];
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** The views a plugin gives an object type, or undefined. */
|
|
475
|
+
viewsFor(
|
|
476
|
+
type: string,
|
|
477
|
+
): { readonly plugin: string; readonly views: ObjectViews } | undefined {
|
|
478
|
+
const found = this.viewByType.get(type);
|
|
479
|
+
return found === undefined
|
|
480
|
+
? undefined
|
|
481
|
+
: { plugin: found.plugin.name, views: found.views };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** The definition of one action, or undefined when it is not loaded. */
|
|
485
|
+
actionDefinition(
|
|
486
|
+
plugin: string,
|
|
487
|
+
action: string,
|
|
488
|
+
objectType?: string | undefined,
|
|
489
|
+
): ActionTypeDefinition | undefined {
|
|
490
|
+
return this.byName
|
|
491
|
+
.get(plugin)
|
|
492
|
+
?.actions.find(
|
|
493
|
+
(item) =>
|
|
494
|
+
item.name === action &&
|
|
495
|
+
(objectType === undefined || item.on === objectType),
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** The plugin names in load order. */
|
|
500
|
+
names(): readonly string[] {
|
|
501
|
+
return this.plugins.map((plugin) => plugin.name);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** True when the plugin's objects belong under a client's settings view. */
|
|
505
|
+
objectsUnderSettings(plugin: string): boolean {
|
|
506
|
+
return this.byName.get(plugin)?.objectsUnderSettings === true;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** The trigger rules plugins ship, in load order, with their plugin. */
|
|
510
|
+
triggerRules(): readonly {
|
|
511
|
+
readonly plugin: string;
|
|
512
|
+
readonly rule: TriggerRule;
|
|
513
|
+
}[] {
|
|
514
|
+
return this.plugins.flatMap((plugin) =>
|
|
515
|
+
plugin.rules.map((rule) => ({ plugin: plugin.name, rule })),
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** The plugins left out at load, with the line that says why. */
|
|
520
|
+
refusals(): readonly PluginRefusal[] {
|
|
521
|
+
return this.refusalList;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** What each loaded plugin declares for settings, in load order. */
|
|
525
|
+
settingsDeclarations(): readonly {
|
|
526
|
+
readonly plugin: string;
|
|
527
|
+
readonly schema: ActionArgsSchema | undefined;
|
|
528
|
+
readonly project: ProjectSettingsDeclaration | undefined;
|
|
529
|
+
}[] {
|
|
530
|
+
return this.plugins.map((plugin) => ({
|
|
531
|
+
plugin: plugin.name,
|
|
532
|
+
schema: plugin.settingsSchema,
|
|
533
|
+
project: plugin.projectSettings,
|
|
534
|
+
}));
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** The validated settings of one loaded plugin. */
|
|
538
|
+
settingsFor(plugin: string): Readonly<Record<string, JsonValue>> {
|
|
539
|
+
return this.settingsByPlugin.get(plugin) ?? Object.freeze({});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** Every loaded plugin's settings, as a worker reloads them. */
|
|
543
|
+
pluginSettings(): Readonly<Record<string, Readonly<Record<string, JsonValue>>>> {
|
|
544
|
+
const settings: Record<string, Readonly<Record<string, JsonValue>>> = {};
|
|
545
|
+
for (const [name, value] of this.settingsByPlugin) settings[name] = value;
|
|
546
|
+
return settings;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Refuses a profile that sets a field no step of the flow enforces. The
|
|
551
|
+
* kernel never interprets a field; it only makes sure one step applies it.
|
|
552
|
+
*/
|
|
553
|
+
checkAccess(flowName: string, access: JsonValue | undefined): void {
|
|
554
|
+
if (access === undefined) return;
|
|
555
|
+
if (!isRecord(access)) {
|
|
556
|
+
throw new PluginError(`access: must be an object`);
|
|
557
|
+
}
|
|
558
|
+
const fields = Object.keys(access).filter((field) => access[field] !== undefined);
|
|
559
|
+
if (fields.length === 0) return;
|
|
560
|
+
const found = this.flow(flowName);
|
|
561
|
+
if (found === undefined) {
|
|
562
|
+
throw new PluginError(`flow "${flowName}": not loaded`);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const enforced = new Set<string>();
|
|
566
|
+
const steps: string[] = [];
|
|
567
|
+
for (const step of found.flow.steps) {
|
|
568
|
+
if (step.kind !== "plugin") continue;
|
|
569
|
+
const use = (step.params as { readonly use?: unknown }).use;
|
|
570
|
+
if (typeof use !== "string") continue;
|
|
571
|
+
steps.push(`${step.id} (${use})`);
|
|
572
|
+
const type = this.stepIndex.get(use);
|
|
573
|
+
for (const field of type?.step.enforces ?? []) enforced.add(field);
|
|
574
|
+
for (const field of type?.plugin.enforces ?? []) enforced.add(field);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
for (const field of fields) {
|
|
578
|
+
if (enforced.has(field)) continue;
|
|
579
|
+
const named = steps.length === 0 ? "none" : steps.join(", ");
|
|
580
|
+
throw new AccessError(
|
|
581
|
+
field,
|
|
582
|
+
`access.${field}: no step of flow "${flowName}" enforces it (steps: ${named})`,
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Why a run of this flow cannot start, or undefined when it can: a step the
|
|
589
|
+
* flow uses, or a step one of those calls, is not loaded.
|
|
590
|
+
*/
|
|
591
|
+
startProblem(flowName: string): string | undefined {
|
|
592
|
+
const found = this.flow(flowName);
|
|
593
|
+
if (found === undefined) return undefined;
|
|
594
|
+
const seen = new Set<string>();
|
|
595
|
+
const queue: string[] = [];
|
|
596
|
+
for (const step of found.flow.steps) {
|
|
597
|
+
if (step.kind !== "plugin") continue;
|
|
598
|
+
const use = (step.params as { readonly use?: unknown }).use;
|
|
599
|
+
if (typeof use === "string") queue.push(use);
|
|
600
|
+
}
|
|
601
|
+
while (queue.length > 0) {
|
|
602
|
+
const use = queue.shift() as string;
|
|
603
|
+
if (seen.has(use)) continue;
|
|
604
|
+
seen.add(use);
|
|
605
|
+
const loaded = this.stepIndex.get(use);
|
|
606
|
+
if (loaded === undefined) return this.missingStep(use);
|
|
607
|
+
queue.push(...(loaded.step.calls ?? []));
|
|
608
|
+
}
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
private missingStep(use: string): string {
|
|
613
|
+
const plugin = use.split("/")[0] ?? use;
|
|
614
|
+
const needs = `cannot start: needs "${use}" from plugin ${plugin}`;
|
|
615
|
+
if (this.disabledNames.has(plugin)) {
|
|
616
|
+
return `${needs}, which is disabled (operad plugin enable ${plugin})`;
|
|
617
|
+
}
|
|
618
|
+
const refusal = this.refusalList.find((item) => item.plugin === plugin);
|
|
619
|
+
if (refusal !== undefined) {
|
|
620
|
+
const reason = refusal.message.replace(`plugin "${plugin}": `, "");
|
|
621
|
+
return `${needs}, which was refused: ${reason}`;
|
|
622
|
+
}
|
|
623
|
+
if (this.byName.has(plugin)) {
|
|
624
|
+
return `${needs}, which has no step "${use.slice(plugin.length + 1)}"`;
|
|
625
|
+
}
|
|
626
|
+
return `${needs}, which is not loaded`;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** The step type registry the flow loader and validator receive. */
|
|
630
|
+
stepTypes(): readonly StepType[] {
|
|
631
|
+
return collectStepTypes(this.plugins);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** Every flow a loaded plugin declares, with its plugin name and source. */
|
|
635
|
+
flows(): readonly {
|
|
636
|
+
readonly plugin: string;
|
|
637
|
+
readonly flow: FlowDefinition;
|
|
638
|
+
readonly source: string | undefined;
|
|
639
|
+
}[] {
|
|
640
|
+
const staticFlows = this.plugins.flatMap((plugin) =>
|
|
641
|
+
plugin.flows.map((flow) => ({
|
|
642
|
+
plugin: plugin.name,
|
|
643
|
+
flow,
|
|
644
|
+
source: this.sourceByPlugin.get(plugin.name),
|
|
645
|
+
})),
|
|
646
|
+
);
|
|
647
|
+
const names = new Set(staticFlows.map((item) => item.flow.name));
|
|
648
|
+
const generated = [...this.declaredFlows.values()]
|
|
649
|
+
.filter((item) => !names.has(item.flow.name))
|
|
650
|
+
.map((item) => ({
|
|
651
|
+
plugin: item.plugin,
|
|
652
|
+
flow: item.flow,
|
|
653
|
+
source: this.sourceByPlugin.get(item.plugin),
|
|
654
|
+
}));
|
|
655
|
+
return [...staticFlows, ...generated];
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* Adds a flow a plugin generated. A name already in use keeps the definition
|
|
660
|
+
* it got first, so a run that started with it keeps its graph when the
|
|
661
|
+
* repository's settings change.
|
|
662
|
+
*/
|
|
663
|
+
private declareFlow(pluginName: string, raw: FlowDefinition): void {
|
|
664
|
+
let flow: FlowDefinition;
|
|
665
|
+
try {
|
|
666
|
+
flow = validateFlow(raw, this.stepTypes());
|
|
667
|
+
} catch (error) {
|
|
668
|
+
if (error instanceof FlowError) {
|
|
669
|
+
throw new PluginError(`plugin "${pluginName}": ${error.message}`, {
|
|
670
|
+
cause: error,
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
throw error;
|
|
674
|
+
}
|
|
675
|
+
const existing = this.flow(flow.name);
|
|
676
|
+
if (existing !== undefined) {
|
|
677
|
+
if (
|
|
678
|
+
existing.plugin === pluginName &&
|
|
679
|
+
JSON.stringify(existing.flow) === JSON.stringify(flow)
|
|
680
|
+
) {
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
throw new PluginError(
|
|
684
|
+
`plugin "${pluginName}": flow "${flow.name}": already declared`,
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
if (this.store.kind === "file") {
|
|
688
|
+
try {
|
|
689
|
+
writeDeclaredFlow(this.store.root, pluginName, flow);
|
|
690
|
+
} catch (error) {
|
|
691
|
+
throw new PluginError(
|
|
692
|
+
`plugin "${pluginName}": flow "${flow.name}": could not be saved: ${messageOf(error)}`,
|
|
693
|
+
{ cause: error },
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
this.declaredFlows.set(flow.name, { plugin: pluginName, flow });
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** The flow with this name, whichever plugin declares it. */
|
|
701
|
+
flow(name: string):
|
|
702
|
+
| { readonly plugin: string; readonly flow: FlowDefinition }
|
|
703
|
+
| undefined {
|
|
704
|
+
const declared = this.declaredFlows.get(name);
|
|
705
|
+
if (declared !== undefined) return declared;
|
|
706
|
+
for (const plugin of this.plugins) {
|
|
707
|
+
const flow = plugin.flows.find((item) => item.name === name);
|
|
708
|
+
if (flow !== undefined) return { plugin: plugin.name, flow };
|
|
709
|
+
}
|
|
710
|
+
return undefined;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** The result names a step type declares, or undefined when it is unknown. */
|
|
714
|
+
stepResults(use: string): readonly string[] | undefined {
|
|
715
|
+
return this.stepIndex.get(use)?.step.results;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** The specifier each loaded plugin came from, aligned with `names()`. */
|
|
719
|
+
pluginSources(): readonly (string | undefined)[] {
|
|
720
|
+
return this.plugins.map((plugin) => this.sourceByPlugin.get(plugin.name));
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/** Every object type the loaded plugins declare, with its plugin and definition. */
|
|
724
|
+
objectTypes(): readonly {
|
|
725
|
+
readonly plugin: string;
|
|
726
|
+
readonly type: string;
|
|
727
|
+
readonly definition: ObjectTypeDefinition;
|
|
728
|
+
}[] {
|
|
729
|
+
return this.plugins.flatMap((plugin) =>
|
|
730
|
+
plugin.objects.map((object) => ({
|
|
731
|
+
plugin: plugin.name,
|
|
732
|
+
type: object.name,
|
|
733
|
+
definition: object,
|
|
734
|
+
})),
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Whether the object's plugin answers its wait automatically. A hook that
|
|
740
|
+
* throws is logged and counts as no.
|
|
741
|
+
*/
|
|
742
|
+
async answeredAutomatically(object: ObjectRef): Promise<boolean> {
|
|
743
|
+
const hook = this.objectType(object.type)?.answeredAutomatically;
|
|
744
|
+
if (hook === undefined) return false;
|
|
745
|
+
try {
|
|
746
|
+
const stored = await this.store.get(object.type, object.id);
|
|
747
|
+
if (stored === undefined) return false;
|
|
748
|
+
return (await hook(stored.data, this.actionEnv())) === true;
|
|
749
|
+
} catch (error) {
|
|
750
|
+
this.log(
|
|
751
|
+
`answeredAutomatically failed for ${object.type} "${object.id}": ${messageOf(error)}`,
|
|
752
|
+
);
|
|
753
|
+
return false;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/** The object type definitions of one type, or undefined. */
|
|
758
|
+
objectType(type: string): ObjectTypeDefinition | undefined {
|
|
759
|
+
for (const plugin of this.plugins) {
|
|
760
|
+
const found = plugin.objects.find((object) => object.name === type);
|
|
761
|
+
if (found !== undefined) return found;
|
|
762
|
+
}
|
|
763
|
+
return undefined;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/** The fields `where` may filter on for one type. */
|
|
767
|
+
indexFor(type: string): readonly string[] | undefined {
|
|
768
|
+
return this.objectType(type)?.index;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** The directory plugin steps run in when a caller names none. */
|
|
772
|
+
get workdir(): string {
|
|
773
|
+
return this.cwd;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/** Loads and validates a flow file against the loaded step types. */
|
|
777
|
+
async loadFlow(path: string): Promise<FlowDefinition> {
|
|
778
|
+
return loadFlowFile(path, this.stepTypes());
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* The limit one call of a step type falls under, or undefined when the type
|
|
783
|
+
* declares none or its key function returns none for these params. A key or
|
|
784
|
+
* count that is not usable is an error naming the step type.
|
|
785
|
+
*/
|
|
786
|
+
stepLimit(
|
|
787
|
+
use: string,
|
|
788
|
+
params: unknown,
|
|
789
|
+
): { readonly key: string; readonly concurrent: number } | undefined {
|
|
790
|
+
const found = this.stepIndex.get(use);
|
|
791
|
+
if (found === undefined) {
|
|
792
|
+
throw new StepNotLoadedError(use);
|
|
793
|
+
}
|
|
794
|
+
const limit = found.step.limit;
|
|
795
|
+
if (limit === undefined) return undefined;
|
|
796
|
+
const settings = this.settingsFor(found.plugin.name);
|
|
797
|
+
let key: unknown;
|
|
798
|
+
let concurrent: unknown;
|
|
799
|
+
try {
|
|
800
|
+
key = limit.key(params, settings);
|
|
801
|
+
if (key === undefined) return undefined;
|
|
802
|
+
concurrent = limit.concurrent(params, settings);
|
|
803
|
+
} catch (error) {
|
|
804
|
+
throw new PluginError(`step "${use}": limit: ${messageOf(error)}`);
|
|
805
|
+
}
|
|
806
|
+
if (typeof key !== "string" || key.length === 0) {
|
|
807
|
+
throw new PluginError(
|
|
808
|
+
`step "${use}": limit: key must return a non-empty string or undefined`,
|
|
809
|
+
);
|
|
810
|
+
}
|
|
811
|
+
if (
|
|
812
|
+
typeof concurrent !== "number" ||
|
|
813
|
+
!Number.isInteger(concurrent) ||
|
|
814
|
+
concurrent < 1
|
|
815
|
+
) {
|
|
816
|
+
throw new PluginError(
|
|
817
|
+
`step "${use}": limit: concurrent must return a positive integer`,
|
|
818
|
+
);
|
|
819
|
+
}
|
|
820
|
+
return { key, concurrent };
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** Runs a step type by its full use name. */
|
|
824
|
+
async runStep(
|
|
825
|
+
use: string,
|
|
826
|
+
params: unknown,
|
|
827
|
+
options: StepRunOptions,
|
|
828
|
+
): Promise<PluginStepResult> {
|
|
829
|
+
return this.runStepInner(use, params, options, false);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* `nested` is a call a step made through `ctx.runStep`: it takes a place
|
|
834
|
+
* under its limit key from the run's limiter first. The runner takes the
|
|
835
|
+
* place of the step it starts itself, before the step is marked started.
|
|
836
|
+
*/
|
|
837
|
+
private async runStepInner(
|
|
838
|
+
use: string,
|
|
839
|
+
params: unknown,
|
|
840
|
+
options: StepRunOptions,
|
|
841
|
+
nested: boolean,
|
|
842
|
+
): Promise<PluginStepResult> {
|
|
843
|
+
if (nested && options.limits !== undefined) {
|
|
844
|
+
const limit = this.stepLimit(use, params);
|
|
845
|
+
if (limit !== undefined) {
|
|
846
|
+
const release = await options.limits.acquire({
|
|
847
|
+
use,
|
|
848
|
+
key: limit.key,
|
|
849
|
+
concurrent: limit.concurrent,
|
|
850
|
+
signal: options.signal,
|
|
851
|
+
});
|
|
852
|
+
try {
|
|
853
|
+
return await this.runStepInner(use, params, options, false);
|
|
854
|
+
} finally {
|
|
855
|
+
await release();
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
const found = this.stepIndex.get(use);
|
|
860
|
+
if (found === undefined) {
|
|
861
|
+
throw new StepNotLoadedError(use);
|
|
862
|
+
}
|
|
863
|
+
if (options.runId.trim().length === 0) {
|
|
864
|
+
throw new PluginError(`step "${use}": runId: must be a non-empty string`);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
const cause = `step:${use}`;
|
|
868
|
+
const limiter = options.limits;
|
|
869
|
+
const emit = async (event: StepEvent): Promise<void> => {
|
|
870
|
+
if (!event.type.startsWith(`${found.plugin.name}.`)) {
|
|
871
|
+
throw new PluginError(
|
|
872
|
+
`step "${use}": emit: type "${event.type}" must begin with "${found.plugin.name}."`,
|
|
873
|
+
);
|
|
874
|
+
}
|
|
875
|
+
// The step that started this one may watch its events; it does not
|
|
876
|
+
// replace the destination.
|
|
877
|
+
await options.observe?.(found.plugin.name, event);
|
|
878
|
+
if (options.emit === undefined) {
|
|
879
|
+
throw new PluginError(
|
|
880
|
+
`step "${use}": emit: no event destination is configured`,
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
await options.emit(found.plugin.name, event);
|
|
884
|
+
};
|
|
885
|
+
const ask = async (request: AskRequest): Promise<AskAnswer> => {
|
|
886
|
+
if (options.asker === undefined) {
|
|
887
|
+
throw new PluginError(
|
|
888
|
+
`step "${use}": ask: no one is configured to take questions`,
|
|
889
|
+
);
|
|
890
|
+
}
|
|
891
|
+
if (
|
|
892
|
+
!isRecord(request) ||
|
|
893
|
+
typeof request.prompt !== "string" ||
|
|
894
|
+
request.prompt.trim().length === 0
|
|
895
|
+
) {
|
|
896
|
+
throw new PluginError(
|
|
897
|
+
`step "${use}": ask: prompt: must be a non-empty string`,
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
if (
|
|
901
|
+
request.choices !== undefined &&
|
|
902
|
+
(!Array.isArray(request.choices) ||
|
|
903
|
+
request.choices.some((choice) => typeof choice !== "string"))
|
|
904
|
+
) {
|
|
905
|
+
throw new PluginError(
|
|
906
|
+
`step "${use}": ask: choices: must be a list of strings`,
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
if (
|
|
910
|
+
request.onTimeout !== undefined &&
|
|
911
|
+
request.onTimeout !== "waiting" &&
|
|
912
|
+
request.onTimeout !== "reject_once"
|
|
913
|
+
) {
|
|
914
|
+
throw new PluginError(
|
|
915
|
+
`step "${use}": ask: onTimeout: must be "waiting" or "reject_once"`,
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
for (const [name, value] of [
|
|
919
|
+
["graceSecs", request.graceSecs],
|
|
920
|
+
["askGraceSecs", askGraceOf(params)],
|
|
921
|
+
] as const) {
|
|
922
|
+
if (
|
|
923
|
+
value !== undefined &&
|
|
924
|
+
(typeof value !== "number" ||
|
|
925
|
+
!Number.isFinite(value) ||
|
|
926
|
+
value < 0 ||
|
|
927
|
+
value > MAX_ASK_GRACE_SECS)
|
|
928
|
+
) {
|
|
929
|
+
throw new PluginError(
|
|
930
|
+
`step "${use}": ask: ${name}: must be a number of seconds from 0 to ${MAX_ASK_GRACE_SECS}`,
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
// A step that cannot resume has nothing to come back to: its question
|
|
935
|
+
// gets one answer or a refusal, whatever the call said.
|
|
936
|
+
const onTimeout =
|
|
937
|
+
found.step.resumable === false ? "reject_once" : request.onTimeout;
|
|
938
|
+
if (
|
|
939
|
+
onTimeout !== "reject_once" &&
|
|
940
|
+
!found.step.results.includes("waiting")
|
|
941
|
+
) {
|
|
942
|
+
throw new PluginError(
|
|
943
|
+
`step "${use}": ask: onTimeout "waiting" ends the step with the result "waiting", so the step must declare it in results (or ask with onTimeout "reject_once")`,
|
|
944
|
+
);
|
|
945
|
+
}
|
|
946
|
+
const grantProblem = grantRequestProblem(request, found.step.grants);
|
|
947
|
+
if (grantProblem !== undefined) {
|
|
948
|
+
throw new PluginError(`step "${use}": ask: ${grantProblem}`);
|
|
949
|
+
}
|
|
950
|
+
const graceSecs = narrowerOf(request.graceSecs, askGraceOf(params));
|
|
951
|
+
const outcome = await options.asker.ask(
|
|
952
|
+
{ ...request, ...(graceSecs === undefined ? {} : { graceSecs }) },
|
|
953
|
+
options.signal,
|
|
954
|
+
);
|
|
955
|
+
if (outcome.kind === "answered") return outcome.answer;
|
|
956
|
+
if (onTimeout === "reject_once") {
|
|
957
|
+
return { choice: undefined, rejected: true };
|
|
958
|
+
}
|
|
959
|
+
throw new AskTimeoutError({
|
|
960
|
+
waitId: outcome.waitId,
|
|
961
|
+
prompt: outcome.prompt,
|
|
962
|
+
choices: outcome.choices,
|
|
963
|
+
resume: request.resume ?? null,
|
|
964
|
+
});
|
|
965
|
+
};
|
|
966
|
+
const useGrant = async (waitId: string): Promise<boolean> => {
|
|
967
|
+
if (options.asker === undefined) return false;
|
|
968
|
+
return options.asker.useGrant(waitId);
|
|
969
|
+
};
|
|
970
|
+
const ctx: StepContext = {
|
|
971
|
+
useGrant,
|
|
972
|
+
...(options.receiver === undefined ? {} : { receiver: options.receiver }),
|
|
973
|
+
plugin: found.plugin.name,
|
|
974
|
+
home: this.home,
|
|
975
|
+
cwd: options.cwd ?? this.cwd,
|
|
976
|
+
store: this.store,
|
|
977
|
+
facts: this.factsFor(cause),
|
|
978
|
+
logger: createPluginLogger(
|
|
979
|
+
this.store.root,
|
|
980
|
+
found.plugin.name,
|
|
981
|
+
"runs",
|
|
982
|
+
options.runId,
|
|
983
|
+
found.step.name,
|
|
984
|
+
),
|
|
985
|
+
signal: options.signal ?? new AbortController().signal,
|
|
986
|
+
settings: this.settingsFor(found.plugin.name),
|
|
987
|
+
secrets: this.secretsFor(found.plugin.name),
|
|
988
|
+
runId: options.runId,
|
|
989
|
+
object: options.object,
|
|
990
|
+
params: options.params ?? null,
|
|
991
|
+
access: options.access ?? null,
|
|
992
|
+
trigger: options.trigger,
|
|
993
|
+
emit,
|
|
994
|
+
ask,
|
|
995
|
+
queued:
|
|
996
|
+
limiter === undefined
|
|
997
|
+
? undefined
|
|
998
|
+
: (key, ahead) =>
|
|
999
|
+
limiter.report({ key, ...(ahead === undefined ? {} : { ahead }) }),
|
|
1000
|
+
stepLoaded: (name) => this.stepIndex.has(name),
|
|
1001
|
+
harnessModels: (name) => this.loadedModels()[name],
|
|
1002
|
+
harnessEfforts: (name) => this.loadedEfforts()[name],
|
|
1003
|
+
runStep: (nestedUse, nestedParams, nestedOptions) => {
|
|
1004
|
+
// Declarations must not drift: tests fail on a call the step did not
|
|
1005
|
+
// declare; production still runs it.
|
|
1006
|
+
if (
|
|
1007
|
+
process.env.NODE_ENV === "test" &&
|
|
1008
|
+
!(found.step.calls ?? []).includes(nestedUse) &&
|
|
1009
|
+
found.step.callsNamedByData !== true &&
|
|
1010
|
+
// A harness step is named by settings (a worker, a reviewer), so a
|
|
1011
|
+
// caller cannot list it.
|
|
1012
|
+
this.stepIndex.get(nestedUse)?.plugin.kind !== "harness"
|
|
1013
|
+
) {
|
|
1014
|
+
return Promise.reject(
|
|
1015
|
+
new PluginError(
|
|
1016
|
+
`step "${use}": calls "${nestedUse}" without declaring it in calls`,
|
|
1017
|
+
),
|
|
1018
|
+
);
|
|
1019
|
+
}
|
|
1020
|
+
return this.runStepInner(nestedUse, nestedParams, {
|
|
1021
|
+
...nestedOptions,
|
|
1022
|
+
limits: nestedOptions.limits ?? options.limits,
|
|
1023
|
+
asker: nestedOptions.asker ?? options.asker,
|
|
1024
|
+
// A nested step reports its events to the same destination.
|
|
1025
|
+
emit: nestedOptions.emit ?? options.emit,
|
|
1026
|
+
}, true);
|
|
1027
|
+
},
|
|
1028
|
+
};
|
|
1029
|
+
|
|
1030
|
+
let outcome: unknown;
|
|
1031
|
+
const marker: StepMarker = { runId: options.runId, step: use, home: this.home };
|
|
1032
|
+
const leave = enterStep(marker);
|
|
1033
|
+
try {
|
|
1034
|
+
outcome = await withStepMarker(marker, () => found.step.run(ctx, params));
|
|
1035
|
+
} catch (error) {
|
|
1036
|
+
if (!(error instanceof AskTimeoutError)) throw error;
|
|
1037
|
+
// The grace passed: the step ends, and the flow's wait carries on.
|
|
1038
|
+
outcome = {
|
|
1039
|
+
result: "waiting",
|
|
1040
|
+
data: {
|
|
1041
|
+
waitId: error.waitId,
|
|
1042
|
+
prompt: error.prompt,
|
|
1043
|
+
choices: [...error.choices],
|
|
1044
|
+
resume: error.resume ?? null,
|
|
1045
|
+
},
|
|
1046
|
+
};
|
|
1047
|
+
} finally {
|
|
1048
|
+
// However the step ended, what it left running goes with it.
|
|
1049
|
+
if (leave()) await reapStep(marker, ctx.logger);
|
|
1050
|
+
}
|
|
1051
|
+
if (!isRecord(outcome) || typeof outcome.result !== "string") {
|
|
1052
|
+
throw new PluginError(
|
|
1053
|
+
`step "${use}": run: must return { result, data? }`,
|
|
1054
|
+
);
|
|
1055
|
+
}
|
|
1056
|
+
if (!found.step.results.includes(outcome.result)) {
|
|
1057
|
+
throw new PluginError(
|
|
1058
|
+
`step "${use}": result "${outcome.result}" is not one of ${found.step.results.map((result) => `"${result}"`).join(", ")}`,
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
const data = outcome.data;
|
|
1062
|
+
if (data === undefined) {
|
|
1063
|
+
return { result: outcome.result };
|
|
1064
|
+
}
|
|
1065
|
+
if (!isRecord(data)) {
|
|
1066
|
+
throw new PluginError(`step "${use}": data: must be an object`);
|
|
1067
|
+
}
|
|
1068
|
+
return { result: outcome.result, data };
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/** The names of the harness plugins loaded now. */
|
|
1072
|
+
loadedHarnesses(): readonly string[] {
|
|
1073
|
+
return this.plugins.filter((item) => item.kind === "harness").map((item) => item.name);
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/** The models the loaded harness plugins declare, by plugin name. */
|
|
1077
|
+
loadedModels(): Readonly<Record<string, HarnessModels>> {
|
|
1078
|
+
const found: Record<string, HarnessModels> = {};
|
|
1079
|
+
for (const item of this.plugins) {
|
|
1080
|
+
if (item.kind !== "harness" || item.models === undefined) continue;
|
|
1081
|
+
found[item.name] =
|
|
1082
|
+
typeof item.models === "function" ? item.models(this.settingsFor(item.name)) : item.models;
|
|
1083
|
+
}
|
|
1084
|
+
return found;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/** The efforts the loaded harness plugins declare, by plugin name. */
|
|
1088
|
+
loadedEfforts(): Readonly<Record<string, HarnessEfforts>> {
|
|
1089
|
+
const found: Record<string, HarnessEfforts> = {};
|
|
1090
|
+
for (const item of this.plugins) {
|
|
1091
|
+
if (item.kind === "harness" && item.efforts !== undefined) found[item.name] = item.efforts;
|
|
1092
|
+
}
|
|
1093
|
+
return found;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/** What an action's checks may read. */
|
|
1097
|
+
actionEnv(): ActionEnv {
|
|
1098
|
+
return {
|
|
1099
|
+
store: this.store,
|
|
1100
|
+
harnesses: this.loadedHarnesses(),
|
|
1101
|
+
models: this.loadedModels(),
|
|
1102
|
+
efforts: this.loadedEfforts(),
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/** Runs an action on an object, by `plugin/action` or a unique plain name. */
|
|
1107
|
+
async runAction(
|
|
1108
|
+
name: string,
|
|
1109
|
+
args: unknown,
|
|
1110
|
+
options: ActionRunOptions,
|
|
1111
|
+
): Promise<ActionRun> {
|
|
1112
|
+
const found = this.findAction(name, options.object.type);
|
|
1113
|
+
const label = `action "${found.plugin.name}:${found.action.name}"`;
|
|
1114
|
+
const personArgs = validateActionArgs(
|
|
1115
|
+
found.action.argsFor?.(options.object, this.actionEnv()) ?? found.action.args,
|
|
1116
|
+
args,
|
|
1117
|
+
label,
|
|
1118
|
+
);
|
|
1119
|
+
const cause = `action:${found.plugin.name}/${found.action.name}`;
|
|
1120
|
+
const runId = options.runId;
|
|
1121
|
+
const onAnswer = this.onAnswer;
|
|
1122
|
+
const actor = options.actor;
|
|
1123
|
+
const answer: Answer | undefined =
|
|
1124
|
+
runId === undefined || onAnswer === undefined
|
|
1125
|
+
? undefined
|
|
1126
|
+
: (choice, note) => onAnswer(runId, choice, note, actor);
|
|
1127
|
+
|
|
1128
|
+
// The action's own fact records who asked. It is not the object's type, so
|
|
1129
|
+
// it never changes the object's data.
|
|
1130
|
+
await this.store.append({
|
|
1131
|
+
type: "action_invoked",
|
|
1132
|
+
object: { type: options.object.type, id: options.object.id },
|
|
1133
|
+
cause,
|
|
1134
|
+
data: {
|
|
1135
|
+
action: `${found.plugin.name}/${found.action.name}`,
|
|
1136
|
+
actor: { via: actor.via, id: actor.id },
|
|
1137
|
+
},
|
|
1138
|
+
});
|
|
1139
|
+
|
|
1140
|
+
const ctx: ActionContext = {
|
|
1141
|
+
plugin: found.plugin.name,
|
|
1142
|
+
home: this.home,
|
|
1143
|
+
cwd: options.cwd ?? this.cwd,
|
|
1144
|
+
store: this.store,
|
|
1145
|
+
facts: this.factsFor(cause),
|
|
1146
|
+
logger: createPluginLogger(
|
|
1147
|
+
this.store.root,
|
|
1148
|
+
found.plugin.name,
|
|
1149
|
+
"actions",
|
|
1150
|
+
found.action.name,
|
|
1151
|
+
),
|
|
1152
|
+
signal: options.signal ?? new AbortController().signal,
|
|
1153
|
+
settings: this.settingsFor(found.plugin.name),
|
|
1154
|
+
secrets: this.secretsFor(found.plugin.name),
|
|
1155
|
+
runId,
|
|
1156
|
+
object: options.object,
|
|
1157
|
+
actor,
|
|
1158
|
+
answer,
|
|
1159
|
+
harnesses: this.loadedHarnesses(),
|
|
1160
|
+
models: this.loadedModels(),
|
|
1161
|
+
efforts: this.loadedEfforts(),
|
|
1162
|
+
...(this.onEvent === undefined
|
|
1163
|
+
? {}
|
|
1164
|
+
: { emit: this.actionEmitter(found.plugin.name) }),
|
|
1165
|
+
...(this.onCancelRun === undefined
|
|
1166
|
+
? {}
|
|
1167
|
+
: { runs: this.runControl() }),
|
|
1168
|
+
};
|
|
1169
|
+
const value = await found.action.run(ctx, personArgs);
|
|
1170
|
+
if (isActionOutcome(value)) {
|
|
1171
|
+
return {
|
|
1172
|
+
plugin: found.plugin.name,
|
|
1173
|
+
action: found.action.name,
|
|
1174
|
+
value: value.text,
|
|
1175
|
+
opens: value.opens,
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
return {
|
|
1179
|
+
plugin: found.plugin.name,
|
|
1180
|
+
action: found.action.name,
|
|
1181
|
+
value,
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/** The `ctx.emit` of an action: an outside event, never one from `operad`. */
|
|
1186
|
+
private actionEmitter(plugin: string): (event: ActionEvent) => Promise<void> {
|
|
1187
|
+
const onEvent = this.onEvent;
|
|
1188
|
+
return async (event) => {
|
|
1189
|
+
if (onEvent === undefined) {
|
|
1190
|
+
throw new PluginError(`plugin "${plugin}": emit: no event destination is configured`);
|
|
1191
|
+
}
|
|
1192
|
+
if (event.source === "operad" || event.source.trim().length === 0) {
|
|
1193
|
+
throw new PluginError(
|
|
1194
|
+
`plugin "${plugin}": emit: source must be a name other than "operad"`,
|
|
1195
|
+
);
|
|
1196
|
+
}
|
|
1197
|
+
await onEvent({
|
|
1198
|
+
source: event.source,
|
|
1199
|
+
type: event.type,
|
|
1200
|
+
key: event.key,
|
|
1201
|
+
hops: 0,
|
|
1202
|
+
...(event.object === undefined ? {} : { object: event.object }),
|
|
1203
|
+
...(event.summary === undefined ? {} : { summary: event.summary }),
|
|
1204
|
+
...(event.data === undefined ? {} : { data: event.data }),
|
|
1205
|
+
});
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
/** Runs each plugin's optional `check`; a throw is a failed check, not an error. */
|
|
1210
|
+
async checks(): Promise<readonly PluginCheck[]> {
|
|
1211
|
+
const checks: PluginCheck[] = [];
|
|
1212
|
+
for (const plugin of this.plugins) {
|
|
1213
|
+
if (plugin.check === undefined) continue;
|
|
1214
|
+
const ctx: PluginBaseContext = {
|
|
1215
|
+
plugin: plugin.name,
|
|
1216
|
+
home: this.home,
|
|
1217
|
+
cwd: this.cwd,
|
|
1218
|
+
store: this.store,
|
|
1219
|
+
facts: this.factsFor(`check:${plugin.name}`),
|
|
1220
|
+
logger: createPluginLogger(this.store.root, plugin.name, "check"),
|
|
1221
|
+
signal: new AbortController().signal,
|
|
1222
|
+
settings: this.settingsFor(plugin.name),
|
|
1223
|
+
secrets: this.secretsFor(plugin.name),
|
|
1224
|
+
};
|
|
1225
|
+
try {
|
|
1226
|
+
const note = await plugin.check(ctx);
|
|
1227
|
+
checks.push({
|
|
1228
|
+
plugin: plugin.name,
|
|
1229
|
+
ok: true,
|
|
1230
|
+
message: typeof note === "string" ? note : "ok",
|
|
1231
|
+
});
|
|
1232
|
+
} catch (error) {
|
|
1233
|
+
checks.push({
|
|
1234
|
+
plugin: plugin.name,
|
|
1235
|
+
ok: false,
|
|
1236
|
+
message: messageOf(error),
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
return checks;
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* The short form `<command>`: offered only when exactly one plugin declares
|
|
1245
|
+
* the name and it is not a kernel verb. A command left without a short form
|
|
1246
|
+
* logs nothing; `<plugin> <command>` still reaches it.
|
|
1247
|
+
*/
|
|
1248
|
+
private resolveShortCommands(): ReadonlyMap<
|
|
1249
|
+
string,
|
|
1250
|
+
{ readonly plugin: LoadedPlugin; readonly command: CommandDefinition }
|
|
1251
|
+
> {
|
|
1252
|
+
const owners = new Map<string, LoadedPlugin[]>();
|
|
1253
|
+
for (const plugin of this.plugins) {
|
|
1254
|
+
for (const command of plugin.commands) {
|
|
1255
|
+
const list = owners.get(command.name);
|
|
1256
|
+
if (list === undefined) owners.set(command.name, [plugin]);
|
|
1257
|
+
else list.push(plugin);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
const result = new Map<
|
|
1261
|
+
string,
|
|
1262
|
+
{ readonly plugin: LoadedPlugin; readonly command: CommandDefinition }
|
|
1263
|
+
>();
|
|
1264
|
+
for (const [name, list] of owners) {
|
|
1265
|
+
const [only] = list;
|
|
1266
|
+
// A name a kernel verb or another plugin also has gets no short form and
|
|
1267
|
+
// no log line: every command and serve's reload probe load the plugins,
|
|
1268
|
+
// and a line printed there reads as a load problem (serve then refuses
|
|
1269
|
+
// the new code). `<plugin> <command>` still reaches it.
|
|
1270
|
+
if (this.kernelVerbs.has(name) || list.length > 1 || only === undefined) {
|
|
1271
|
+
continue;
|
|
1272
|
+
} else {
|
|
1273
|
+
const command = only.commands.find((item) => item.name === name);
|
|
1274
|
+
if (command !== undefined) result.set(name, { plugin: only, command });
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
return result;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* Resolves a CLI verb. `<plugin> <verb>` always wins; `<verb>` works when
|
|
1282
|
+
* exactly one plugin declares the name and it is not a kernel verb.
|
|
1283
|
+
*/
|
|
1284
|
+
resolveCommand(argv: readonly string[]): ResolvedCommand | undefined {
|
|
1285
|
+
const first = argv[0];
|
|
1286
|
+
if (first === undefined) return undefined;
|
|
1287
|
+
|
|
1288
|
+
const second = argv[1];
|
|
1289
|
+
const named = this.byName.get(first);
|
|
1290
|
+
if (named !== undefined && second !== undefined) {
|
|
1291
|
+
const command = named.commands.find((item) => item.name === second);
|
|
1292
|
+
if (command !== undefined) {
|
|
1293
|
+
return {
|
|
1294
|
+
plugin: named.name,
|
|
1295
|
+
command: command.name,
|
|
1296
|
+
argv: argv.slice(2),
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
const owner = this.shortCommands.get(first);
|
|
1302
|
+
if (owner === undefined) return undefined;
|
|
1303
|
+
return {
|
|
1304
|
+
plugin: owner.plugin.name,
|
|
1305
|
+
command: owner.command.name,
|
|
1306
|
+
argv: argv.slice(1),
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
/** Resolves and runs a CLI verb. Returns undefined when none matches. */
|
|
1311
|
+
async runCommand(
|
|
1312
|
+
argv: readonly string[],
|
|
1313
|
+
options: CommandRunOptions = {},
|
|
1314
|
+
): Promise<CommandRun | undefined> {
|
|
1315
|
+
const resolved = this.resolveCommand(argv);
|
|
1316
|
+
if (resolved === undefined) return undefined;
|
|
1317
|
+
|
|
1318
|
+
const plugin = this.byName.get(resolved.plugin);
|
|
1319
|
+
if (plugin === undefined) {
|
|
1320
|
+
throw new PluginError(`plugin "${resolved.plugin}": not loaded`);
|
|
1321
|
+
}
|
|
1322
|
+
const command = plugin.commands.find(
|
|
1323
|
+
(item) => item.name === resolved.command,
|
|
1324
|
+
);
|
|
1325
|
+
if (command === undefined) {
|
|
1326
|
+
throw new PluginError(
|
|
1327
|
+
`plugin "${plugin.name}": command "${resolved.command}": not declared`,
|
|
1328
|
+
);
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
const ctx: CommandContext = {
|
|
1332
|
+
plugin: plugin.name,
|
|
1333
|
+
home: this.home,
|
|
1334
|
+
cwd: options.cwd ?? this.cwd,
|
|
1335
|
+
store: this.store,
|
|
1336
|
+
facts: this.factsFor(`command:${plugin.name}/${command.name}`),
|
|
1337
|
+
logger: createPluginLogger(
|
|
1338
|
+
this.store.root,
|
|
1339
|
+
plugin.name,
|
|
1340
|
+
"commands",
|
|
1341
|
+
command.name,
|
|
1342
|
+
),
|
|
1343
|
+
signal: options.signal ?? new AbortController().signal,
|
|
1344
|
+
settings: this.settingsFor(plugin.name),
|
|
1345
|
+
secrets: this.secretsFor(plugin.name),
|
|
1346
|
+
...(options.input === undefined ? {} : { input: options.input }),
|
|
1347
|
+
...(this.onCancelRun === undefined ? {} : { runs: this.runControl() }),
|
|
1348
|
+
};
|
|
1349
|
+
const value = await command.run(ctx, resolved.argv);
|
|
1350
|
+
return { ...resolved, value };
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
/**
|
|
1354
|
+
* The items plugins ask a person to know about. A hook that throws is
|
|
1355
|
+
* logged and shows nothing, so one plugin cannot hide the others.
|
|
1356
|
+
*/
|
|
1357
|
+
async standing(): Promise<readonly StandingEntry[]> {
|
|
1358
|
+
const items: StandingEntry[] = [];
|
|
1359
|
+
for (const plugin of this.plugins) {
|
|
1360
|
+
if (plugin.standing === undefined) continue;
|
|
1361
|
+
try {
|
|
1362
|
+
const found = await plugin.standing({
|
|
1363
|
+
plugin: plugin.name,
|
|
1364
|
+
home: this.home,
|
|
1365
|
+
cwd: this.cwd,
|
|
1366
|
+
store: this.store,
|
|
1367
|
+
facts: this.factsFor(`standing:${plugin.name}`),
|
|
1368
|
+
logger: createPluginLogger(this.store.root, plugin.name, "standing"),
|
|
1369
|
+
signal: new AbortController().signal,
|
|
1370
|
+
settings: this.settingsFor(plugin.name),
|
|
1371
|
+
secrets: this.secretsFor(plugin.name),
|
|
1372
|
+
loaded: this.plugins.map((item) => item.name),
|
|
1373
|
+
});
|
|
1374
|
+
for (const item of found) {
|
|
1375
|
+
const object =
|
|
1376
|
+
item.object === undefined
|
|
1377
|
+
? undefined
|
|
1378
|
+
: await this.store.get(item.object.type, item.object.id);
|
|
1379
|
+
// An item about an object that is gone says nothing.
|
|
1380
|
+
if (item.object !== undefined && object === undefined) continue;
|
|
1381
|
+
items.push({
|
|
1382
|
+
plugin: plugin.name,
|
|
1383
|
+
id: item.id,
|
|
1384
|
+
prompt: item.prompt,
|
|
1385
|
+
actions: object === undefined ? [] : await this.actionsHolding(object),
|
|
1386
|
+
...(item.object === undefined ? {} : { object: item.object }),
|
|
1387
|
+
...(item.announce === false ? { announce: false as const } : {}),
|
|
1388
|
+
...(item.covers === undefined || item.covers.length === 0
|
|
1389
|
+
? {}
|
|
1390
|
+
: { covers: item.covers.map((ref) => `${ref.type}:${ref.id}`) }),
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
this.log(`plugin "${plugin.name}": standing failed: ${messageOf(error)}`);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
return items;
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
/** The actions whose `when` holds for the object; a throwing `when` is logged and hidden. */
|
|
1401
|
+
private async actionsHolding(object: StoredObject): Promise<readonly PendingActionView[]> {
|
|
1402
|
+
const held: { plugin: string; action: string; rank: number }[] = [];
|
|
1403
|
+
for (const { plugin, action } of this.actionsFor(object.type)) {
|
|
1404
|
+
let holds: unknown;
|
|
1405
|
+
try {
|
|
1406
|
+
holds = await action.when(object.data, this.actionEnv());
|
|
1407
|
+
} catch (error) {
|
|
1408
|
+
this.log(
|
|
1409
|
+
`plugin "${plugin.name}": action "${action.name}": when failed: ${messageOf(error)}`,
|
|
1410
|
+
);
|
|
1411
|
+
continue;
|
|
1412
|
+
}
|
|
1413
|
+
if (holds === true) {
|
|
1414
|
+
held.push({ plugin: plugin.name, action: action.name, rank: rankOf(action, object.data) });
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
return sortByRank(held).map(({ plugin, action }) => ({ plugin, action }));
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
/**
|
|
1421
|
+
* Computes the pending view: for each waiting run, the object's state and
|
|
1422
|
+
* the actions whose `when` holds. A throwing `when` is logged and hidden.
|
|
1423
|
+
*/
|
|
1424
|
+
async pending(runs: readonly WaitingRun[]): Promise<readonly PendingEntry[]> {
|
|
1425
|
+
const entries: PendingEntry[] = [];
|
|
1426
|
+
for (const run of runs) {
|
|
1427
|
+
const object = await this.store.get(run.object.type, run.object.id);
|
|
1428
|
+
if (object === undefined) {
|
|
1429
|
+
// The run still waits; show it without actions instead of hiding it.
|
|
1430
|
+
if (!this.reportedMissing.has(run.runId)) {
|
|
1431
|
+
this.reportedMissing.add(run.runId);
|
|
1432
|
+
this.log(
|
|
1433
|
+
`pending: run "${run.runId}" waits on ${run.object.type} "${run.object.id}", which is not in the store`,
|
|
1434
|
+
);
|
|
1435
|
+
}
|
|
1436
|
+
entries.push({
|
|
1437
|
+
runId: run.runId,
|
|
1438
|
+
prompt: run.prompt,
|
|
1439
|
+
choices: run.choices,
|
|
1440
|
+
object: {
|
|
1441
|
+
type: run.object.type,
|
|
1442
|
+
id: run.object.id,
|
|
1443
|
+
data: {},
|
|
1444
|
+
version: 0,
|
|
1445
|
+
cause: "missing",
|
|
1446
|
+
at: run.lastFactAt ?? 0,
|
|
1447
|
+
},
|
|
1448
|
+
actions: [],
|
|
1449
|
+
});
|
|
1450
|
+
continue;
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
const actions = await this.actionsHolding(object);
|
|
1454
|
+
entries.push({
|
|
1455
|
+
runId: run.runId,
|
|
1456
|
+
prompt: run.prompt,
|
|
1457
|
+
choices: run.choices,
|
|
1458
|
+
object,
|
|
1459
|
+
actions,
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
return entries;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
/** Runs each plugin's `onTick` once; a failure is logged, not raised. */
|
|
1466
|
+
async tick(runs?: RunLookup): Promise<void> {
|
|
1467
|
+
for (const plugin of this.plugins) {
|
|
1468
|
+
if (plugin.onTick === undefined) continue;
|
|
1469
|
+
const ctx: TickContext = {
|
|
1470
|
+
plugin: plugin.name,
|
|
1471
|
+
home: this.home,
|
|
1472
|
+
cwd: this.cwd,
|
|
1473
|
+
store: this.store,
|
|
1474
|
+
facts: this.factsFor(`tick:${plugin.name}`),
|
|
1475
|
+
logger: createPluginLogger(this.store.root, plugin.name, "tick"),
|
|
1476
|
+
signal: new AbortController().signal,
|
|
1477
|
+
settings: this.settingsFor(plugin.name),
|
|
1478
|
+
secrets: this.secretsFor(plugin.name),
|
|
1479
|
+
...(runs === undefined ? {} : { runLookup: runs }),
|
|
1480
|
+
...(this.onCancelRun === undefined ? {} : { runs: this.runControl() }),
|
|
1481
|
+
loaded: this.plugins.map((item) => item.name),
|
|
1482
|
+
start: async (flowOrRequest, objectArg, accessArg) => {
|
|
1483
|
+
const request: StartRunRequest =
|
|
1484
|
+
typeof flowOrRequest === "string"
|
|
1485
|
+
? {
|
|
1486
|
+
plugin: plugin.name,
|
|
1487
|
+
flow: flowOrRequest,
|
|
1488
|
+
...(objectArg === undefined ? {} : { object: objectArg }),
|
|
1489
|
+
...(accessArg === undefined ? {} : { access: accessArg }),
|
|
1490
|
+
}
|
|
1491
|
+
: {
|
|
1492
|
+
plugin: plugin.name,
|
|
1493
|
+
flow: flowOrRequest.flow,
|
|
1494
|
+
...(flowOrRequest.params === undefined
|
|
1495
|
+
? {}
|
|
1496
|
+
: { params: flowOrRequest.params }),
|
|
1497
|
+
...(flowOrRequest.object === undefined
|
|
1498
|
+
? {}
|
|
1499
|
+
: {
|
|
1500
|
+
object:
|
|
1501
|
+
typeof flowOrRequest.object === "string"
|
|
1502
|
+
? parseObjectKeyMaybe(flowOrRequest.object)
|
|
1503
|
+
: flowOrRequest.object,
|
|
1504
|
+
}),
|
|
1505
|
+
...(flowOrRequest.trigger === undefined
|
|
1506
|
+
? {}
|
|
1507
|
+
: { trigger: flowOrRequest.trigger }),
|
|
1508
|
+
...(flowOrRequest.access === undefined
|
|
1509
|
+
? {}
|
|
1510
|
+
: { access: flowOrRequest.access }),
|
|
1511
|
+
};
|
|
1512
|
+
const found = this.flow(request.flow);
|
|
1513
|
+
if (found === undefined || found.plugin !== plugin.name) {
|
|
1514
|
+
throw new PluginError(
|
|
1515
|
+
`plugin "${plugin.name}": flow "${request.flow}": not declared`,
|
|
1516
|
+
);
|
|
1517
|
+
}
|
|
1518
|
+
this.checkAccess(request.flow, request.access);
|
|
1519
|
+
this.starts.push(request);
|
|
1520
|
+
if (this.onStartRun !== undefined) {
|
|
1521
|
+
await this.onStartRun(request);
|
|
1522
|
+
}
|
|
1523
|
+
},
|
|
1524
|
+
declareFlow: (flow) => {
|
|
1525
|
+
this.declareFlow(plugin.name, flow);
|
|
1526
|
+
},
|
|
1527
|
+
answer: async (runId, choice, note) => {
|
|
1528
|
+
if (this.onAnswer === undefined) {
|
|
1529
|
+
throw new PluginError(
|
|
1530
|
+
`plugin "${plugin.name}": answer: no answer handler is installed`,
|
|
1531
|
+
);
|
|
1532
|
+
}
|
|
1533
|
+
await this.onAnswer(runId, choice, note, {
|
|
1534
|
+
via: "plugin",
|
|
1535
|
+
id: plugin.name,
|
|
1536
|
+
});
|
|
1537
|
+
},
|
|
1538
|
+
};
|
|
1539
|
+
try {
|
|
1540
|
+
await plugin.onTick(ctx);
|
|
1541
|
+
} catch (error) {
|
|
1542
|
+
this.log(`plugin "${plugin.name}": onTick failed: ${messageOf(error)}`);
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
/**
|
|
1548
|
+
* The run starts plugins asked for that nobody took yet. Reading does not
|
|
1549
|
+
* drain; a loop that ticks each pass calls `takeStartedRuns()` instead.
|
|
1550
|
+
*/
|
|
1551
|
+
get startedRuns(): readonly StartRunRequest[] {
|
|
1552
|
+
return [...this.starts];
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
/** The loaded source plugins, with the function that starts each one. */
|
|
1556
|
+
sourcePlugins(): readonly {
|
|
1557
|
+
readonly plugin: string;
|
|
1558
|
+
readonly start: (ctx: SourceContext) => MaybePromise<SourceHandle> | SourceHandle;
|
|
1559
|
+
}[] {
|
|
1560
|
+
return this.plugins.flatMap((plugin) =>
|
|
1561
|
+
plugin.kind !== "source" || plugin.start === undefined
|
|
1562
|
+
? []
|
|
1563
|
+
: [{ plugin: plugin.name, start: plugin.start }],
|
|
1564
|
+
);
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
/**
|
|
1568
|
+
* Starts each source plugin. A source that throws is logged and skipped, so
|
|
1569
|
+
* one broken source cannot stop the others or the loop.
|
|
1570
|
+
*/
|
|
1571
|
+
async startSources(options: {
|
|
1572
|
+
readonly rules: readonly TriggerRule[];
|
|
1573
|
+
readonly clock: () => number;
|
|
1574
|
+
readonly emit: (event: TriggerEvent) => MaybePromise<void>;
|
|
1575
|
+
readonly signal?: AbortSignal | undefined;
|
|
1576
|
+
}): Promise<readonly { readonly plugin: string; readonly handle: SourceHandle }[]> {
|
|
1577
|
+
const running: { plugin: string; handle: SourceHandle }[] = [];
|
|
1578
|
+
for (const plugin of this.plugins) {
|
|
1579
|
+
if (plugin.kind !== "source" || plugin.start === undefined) continue;
|
|
1580
|
+
const emit = async (event: SourceEvent): Promise<void> => {
|
|
1581
|
+
const trigger: TriggerEvent = {
|
|
1582
|
+
source: event.source ?? plugin.name,
|
|
1583
|
+
key: event.key,
|
|
1584
|
+
type: event.type,
|
|
1585
|
+
...(event.object === undefined ? {} : { object: event.object }),
|
|
1586
|
+
...(event.summary === undefined ? {} : { summary: event.summary }),
|
|
1587
|
+
...(event.data === undefined ? {} : { data: event.data }),
|
|
1588
|
+
...(event.link === undefined ? {} : { link: event.link }),
|
|
1589
|
+
hops: 0,
|
|
1590
|
+
};
|
|
1591
|
+
try {
|
|
1592
|
+
await options.emit(trigger);
|
|
1593
|
+
} catch (error) {
|
|
1594
|
+
this.log(
|
|
1595
|
+
`plugin "${plugin.name}": emit failed: ${messageOf(error)}`,
|
|
1596
|
+
);
|
|
1597
|
+
}
|
|
1598
|
+
};
|
|
1599
|
+
const ctx: SourceContext = {
|
|
1600
|
+
plugin: plugin.name,
|
|
1601
|
+
home: this.home,
|
|
1602
|
+
cwd: this.cwd,
|
|
1603
|
+
store: this.store,
|
|
1604
|
+
facts: this.factsFor(`source:${plugin.name}`),
|
|
1605
|
+
logger: createPluginLogger(this.store.root, plugin.name, "source"),
|
|
1606
|
+
signal: options.signal ?? new AbortController().signal,
|
|
1607
|
+
rules: options.rules,
|
|
1608
|
+
clock: options.clock,
|
|
1609
|
+
settings: this.settingsFor(plugin.name),
|
|
1610
|
+
secrets: this.secretsFor(plugin.name),
|
|
1611
|
+
emit,
|
|
1612
|
+
};
|
|
1613
|
+
try {
|
|
1614
|
+
const handle = await plugin.start(ctx);
|
|
1615
|
+
running.push({ plugin: plugin.name, handle });
|
|
1616
|
+
} catch (error) {
|
|
1617
|
+
this.log(`plugin "${plugin.name}": start failed: ${messageOf(error)}`);
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
return running;
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
/** Removes and returns the start requests collected so far. */
|
|
1624
|
+
takeStartedRuns(): StartRunRequest[] {
|
|
1625
|
+
return this.starts.splice(0);
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
private actionsFor(
|
|
1629
|
+
type: string,
|
|
1630
|
+
): readonly {
|
|
1631
|
+
readonly plugin: LoadedPlugin;
|
|
1632
|
+
readonly action: ActionTypeDefinition;
|
|
1633
|
+
}[] {
|
|
1634
|
+
const found: {
|
|
1635
|
+
readonly plugin: LoadedPlugin;
|
|
1636
|
+
readonly action: ActionTypeDefinition;
|
|
1637
|
+
}[] = [];
|
|
1638
|
+
for (const plugin of this.plugins) {
|
|
1639
|
+
for (const action of plugin.actions) {
|
|
1640
|
+
if (action.on === type) found.push({ plugin, action });
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
return found;
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
private findAction(
|
|
1647
|
+
name: string,
|
|
1648
|
+
objectType: string,
|
|
1649
|
+
): { readonly plugin: LoadedPlugin; readonly action: ActionTypeDefinition } {
|
|
1650
|
+
const named = splitActionName(name);
|
|
1651
|
+
if (named !== undefined) {
|
|
1652
|
+
const pluginName = named.plugin;
|
|
1653
|
+
const actionName = named.action;
|
|
1654
|
+
const plugin = this.byName.get(pluginName);
|
|
1655
|
+
if (plugin !== undefined) {
|
|
1656
|
+
const action = plugin.actions.find(
|
|
1657
|
+
(item) => item.name === actionName && item.on === objectType,
|
|
1658
|
+
);
|
|
1659
|
+
if (action !== undefined) return { plugin, action };
|
|
1660
|
+
const other = plugin.actions.find((item) => item.name === actionName);
|
|
1661
|
+
if (other !== undefined) {
|
|
1662
|
+
this.requireActionObject(plugin, other, objectType);
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
let found:
|
|
1668
|
+
| {
|
|
1669
|
+
readonly plugin: LoadedPlugin;
|
|
1670
|
+
readonly actions: readonly ActionTypeDefinition[];
|
|
1671
|
+
}
|
|
1672
|
+
| undefined;
|
|
1673
|
+
for (const plugin of this.plugins) {
|
|
1674
|
+
const matches = plugin.actions.filter((action) => action.name === name);
|
|
1675
|
+
if (matches.length === 0) continue;
|
|
1676
|
+
if (found !== undefined) {
|
|
1677
|
+
throw new PluginError(
|
|
1678
|
+
`action "${name}": declared by plugins "${found.plugin.name}" and "${plugin.name}", use "<plugin>/<action>"`,
|
|
1679
|
+
);
|
|
1680
|
+
}
|
|
1681
|
+
found = { plugin, actions: matches };
|
|
1682
|
+
}
|
|
1683
|
+
if (found === undefined) {
|
|
1684
|
+
throw new PluginError(`action "${name}": no loaded plugin declares it`);
|
|
1685
|
+
}
|
|
1686
|
+
const action =
|
|
1687
|
+
found.actions.find((item) => item.on === objectType) ?? found.actions[0];
|
|
1688
|
+
if (action === undefined) {
|
|
1689
|
+
throw new PluginError(`action "${name}": no loaded plugin declares it`);
|
|
1690
|
+
}
|
|
1691
|
+
this.requireActionObject(found.plugin, action, objectType);
|
|
1692
|
+
return { plugin: found.plugin, action };
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
private requireActionObject(
|
|
1696
|
+
plugin: LoadedPlugin,
|
|
1697
|
+
action: ActionTypeDefinition,
|
|
1698
|
+
objectType: string,
|
|
1699
|
+
): void {
|
|
1700
|
+
if (action.on !== objectType) {
|
|
1701
|
+
throw new PluginError(
|
|
1702
|
+
`plugin "${plugin.name}": action "${action.name}": on: expected object type "${action.on}", got "${objectType}"`,
|
|
1703
|
+
);
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
private resolveKeys(
|
|
1708
|
+
userKeys: KeyBindings,
|
|
1709
|
+
): ReadonlyMap<string, KeyBinding> {
|
|
1710
|
+
const known = new Map(
|
|
1711
|
+
this.actionInfos.map((info) => [info.name, info] as const),
|
|
1712
|
+
);
|
|
1713
|
+
const bindings = new Map<string, KeyBinding>();
|
|
1714
|
+
|
|
1715
|
+
for (const plugin of this.plugins) {
|
|
1716
|
+
for (const [key, target] of Object.entries(plugin.keys)) {
|
|
1717
|
+
const info = known.get(target);
|
|
1718
|
+
if (info === undefined) {
|
|
1719
|
+
throw new PluginError(
|
|
1720
|
+
`plugin "${plugin.name}": keys.${key}: "${target}" is not a loaded action`,
|
|
1721
|
+
);
|
|
1722
|
+
}
|
|
1723
|
+
const existing = bindings.get(key);
|
|
1724
|
+
if (existing !== undefined) {
|
|
1725
|
+
this.log(
|
|
1726
|
+
`key "${key}": plugin "${plugin.name}" would bind "${target}", but "${existing.name}" already uses it; keeping "${existing.name}"`,
|
|
1727
|
+
);
|
|
1728
|
+
continue;
|
|
1729
|
+
}
|
|
1730
|
+
bindings.set(key, {
|
|
1731
|
+
key,
|
|
1732
|
+
plugin: info.plugin,
|
|
1733
|
+
action: info.action,
|
|
1734
|
+
name: info.name,
|
|
1735
|
+
source: "plugin",
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
for (const [key, target] of Object.entries(userKeys)) {
|
|
1741
|
+
const info = known.get(target);
|
|
1742
|
+
if (info === undefined) {
|
|
1743
|
+
this.log(
|
|
1744
|
+
`key "${key}": "${target}" is not a loaded action; the key is ignored`,
|
|
1745
|
+
);
|
|
1746
|
+
continue;
|
|
1747
|
+
}
|
|
1748
|
+
bindings.set(key, {
|
|
1749
|
+
key,
|
|
1750
|
+
plugin: info.plugin,
|
|
1751
|
+
action: info.action,
|
|
1752
|
+
name: info.name,
|
|
1753
|
+
source: "user",
|
|
1754
|
+
});
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
return bindings;
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1760
|
+
private factsFor(cause: string): FactWriter {
|
|
1761
|
+
return {
|
|
1762
|
+
append: (input: FactInput) =>
|
|
1763
|
+
this.store.append({ ...input, cause: input.cause ?? cause }),
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
private secretsFor(plugin: string): SecretStore {
|
|
1768
|
+
return new FileSecretStore({ home: this.home, plugin });
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
private runControl(): RunControl {
|
|
1772
|
+
const onCancelRun = this.onCancelRun;
|
|
1773
|
+
return {
|
|
1774
|
+
cancel: async (runId, flow) => {
|
|
1775
|
+
if (onCancelRun !== undefined) await onCancelRun(runId, flow);
|
|
1776
|
+
},
|
|
1777
|
+
};
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
private log(message: string): void {
|
|
1781
|
+
this.onLog(message);
|
|
1782
|
+
}
|
|
1783
|
+
}
|