@operad-io/engine 0.0.0-stage → 0.1.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 (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/config.schema.json +188 -0
  4. package/keys.schema.json +12 -0
  5. package/package.json +22 -4
  6. package/src/config/config.ts +627 -0
  7. package/src/config/index.ts +1 -0
  8. package/src/flow/define-flow.ts +57 -0
  9. package/src/flow/index.ts +5 -0
  10. package/src/flow/load.ts +41 -0
  11. package/src/flow/types.ts +107 -0
  12. package/src/flow/validate.ts +296 -0
  13. package/src/http/address.ts +142 -0
  14. package/src/http/index.ts +25 -0
  15. package/src/http/link.ts +20 -0
  16. package/src/http/server.ts +920 -0
  17. package/src/http/token.ts +90 -0
  18. package/src/index.ts +18 -0
  19. package/src/kernel/decide.ts +689 -0
  20. package/src/kernel/index.ts +3 -0
  21. package/src/kernel/state.ts +275 -0
  22. package/src/kernel/types.ts +366 -0
  23. package/src/log/errors.ts +77 -0
  24. package/src/log/facts.ts +50 -0
  25. package/src/log/index.ts +6 -0
  26. package/src/log/json-value.ts +67 -0
  27. package/src/log/open-log.ts +17 -0
  28. package/src/log/schema.ts +5 -0
  29. package/src/log/secret.ts +30 -0
  30. package/src/log/sqlite.ts +1011 -0
  31. package/src/log/types.ts +230 -0
  32. package/src/loop/code-watch.ts +486 -0
  33. package/src/loop/index.ts +3 -0
  34. package/src/loop/older-code.ts +58 -0
  35. package/src/loop/serve.ts +483 -0
  36. package/src/markdown.ts +451 -0
  37. package/src/notify/index.ts +10 -0
  38. package/src/notify/notify.ts +256 -0
  39. package/src/platform/file-lock.ts +385 -0
  40. package/src/platform/index.ts +13 -0
  41. package/src/platform/load.ts +18 -0
  42. package/src/platform/process-group.ts +675 -0
  43. package/src/platform/process-watch.ts +152 -0
  44. package/src/platform/sqlite-open.ts +104 -0
  45. package/src/platform/step-reap.ts +668 -0
  46. package/src/platform/watch.ts +158 -0
  47. package/src/platform/worker-reports.ts +34 -0
  48. package/src/plugin/action-schema.ts +550 -0
  49. package/src/plugin/declared-flows.ts +74 -0
  50. package/src/plugin/define-plugin.ts +12 -0
  51. package/src/plugin/errors.ts +73 -0
  52. package/src/plugin/filters.ts +46 -0
  53. package/src/plugin/harness.ts +50 -0
  54. package/src/plugin/home.ts +13 -0
  55. package/src/plugin/index.ts +65 -0
  56. package/src/plugin/install.ts +268 -0
  57. package/src/plugin/keys.ts +63 -0
  58. package/src/plugin/load.ts +256 -0
  59. package/src/plugin/logger.ts +30 -0
  60. package/src/plugin/object-facts.ts +132 -0
  61. package/src/plugin/open-store.ts +32 -0
  62. package/src/plugin/paging.ts +133 -0
  63. package/src/plugin/registry.ts +1786 -0
  64. package/src/plugin/secrets.ts +141 -0
  65. package/src/plugin/semver.ts +110 -0
  66. package/src/plugin/settings.ts +64 -0
  67. package/src/plugin/sqlite-store.ts +756 -0
  68. package/src/plugin/store.ts +318 -0
  69. package/src/plugin/types.ts +1243 -0
  70. package/src/plugin/usage.ts +157 -0
  71. package/src/plugin/validate.ts +1028 -0
  72. package/src/runner/answer.ts +156 -0
  73. package/src/runner/ask.ts +483 -0
  74. package/src/runner/cancel.ts +51 -0
  75. package/src/runner/errors.ts +20 -0
  76. package/src/runner/grants.ts +92 -0
  77. package/src/runner/index.ts +33 -0
  78. package/src/runner/limits.ts +403 -0
  79. package/src/runner/lock.ts +140 -0
  80. package/src/runner/runner.ts +1175 -0
  81. package/src/runner/service.ts +184 -0
  82. package/src/runner/step-worker.ts +303 -0
  83. package/src/testing/clock.ts +67 -0
  84. package/src/testing/index.ts +90 -0
  85. package/src/testing/types.ts +116 -0
  86. package/src/testing/world.ts +369 -0
  87. package/src/trigger/cron.ts +193 -0
  88. package/src/trigger/index.ts +32 -0
  89. package/src/trigger/kernel.ts +1221 -0
  90. package/src/trigger/rules.ts +300 -0
  91. package/src/trigger/store.ts +233 -0
  92. package/src/trigger/types.ts +156 -0
  93. package/src/util.ts +50 -0
  94. package/src/views/history.ts +634 -0
  95. package/src/views/index.ts +7 -0
  96. package/src/views/pending.ts +209 -0
  97. package/src/views/presentation.ts +2609 -0
  98. package/src/views/running.ts +255 -0
  99. package/src/views/settings.ts +452 -0
  100. package/src/views/types.ts +72 -0
  101. package/src/views/uploads.ts +228 -0
  102. package/triggers.schema.json +48 -0
@@ -0,0 +1,46 @@
1
+ /** The row filters of an object type, with the kernel's implicit `all`. */
2
+
3
+ import type { ObjectFilterDefinition, ObjectTypeDefinition } from "./types.ts";
4
+
5
+ /** The name of the filter the kernel adds to every type that declares filters. */
6
+ export const ALL_FILTER = "all";
7
+
8
+ /** One filter as a client sees it; `all` has no states. */
9
+ export interface TypeFilter {
10
+ readonly name: string;
11
+ readonly states?: readonly string[] | undefined;
12
+ }
13
+
14
+ /** A type's filters in display order and the name of its default. */
15
+ export interface TypeFilters {
16
+ readonly filters: readonly TypeFilter[];
17
+ readonly default: string;
18
+ }
19
+
20
+ /**
21
+ * The filters of a type: the declared order, with `all` right after the
22
+ * default. Undefined when the type declares none.
23
+ */
24
+ export function typeFilters(
25
+ definition: ObjectTypeDefinition | undefined,
26
+ ): TypeFilters | undefined {
27
+ const declared: readonly ObjectFilterDefinition[] = definition?.filters ?? [];
28
+ if (declared.length === 0) return undefined;
29
+ const marked = declared.find((filter) => filter.default === true);
30
+ const defaultName = (marked ?? declared[0])?.name ?? ALL_FILTER;
31
+ const filters: TypeFilter[] = [];
32
+ for (const filter of declared) {
33
+ filters.push({ name: filter.name, states: filter.states });
34
+ if (filter.name === defaultName) filters.push({ name: ALL_FILTER });
35
+ }
36
+ return { filters, default: defaultName };
37
+ }
38
+
39
+ /** True when a row in this state is shown by the filter. An error row always is. */
40
+ export function filterShows(
41
+ filter: TypeFilter,
42
+ state: string,
43
+ ): boolean {
44
+ if (filter.states === undefined) return true;
45
+ return state === "error" || filter.states.includes(state);
46
+ }
@@ -0,0 +1,50 @@
1
+ import type { EndResult } from "./usage.ts";
2
+ import type { Usage } from "./usage.ts";
3
+
4
+ /**
5
+ * The harness-agnostic shape of an `agent` step and a `<harness>:prompt` flow.
6
+ * Every harness plugin (radian, Claude Code, Codex) offers these params and
7
+ * records these facts, so a flow written against one harness works with the
8
+ * next. Types only: the kernel never runs a harness itself.
9
+ */
10
+
11
+ /** The params every harness `agent` step accepts. */
12
+ export interface AgentStepParams {
13
+ readonly prompt: string;
14
+ readonly cwd: string;
15
+ readonly args?: readonly string[] | undefined;
16
+ /** The wall time the agent may run, in seconds. */
17
+ readonly wallTimeSecs?: number | undefined;
18
+ /** How long the agent may go without a new output line, in seconds. */
19
+ readonly stallSecs?: number | undefined;
20
+ /** Continue an earlier harness session instead of starting a new one. */
21
+ readonly resumeSession?: string | undefined;
22
+ }
23
+
24
+ /** The fixed params of every `<harness>:prompt` flow. */
25
+ export interface PromptFlowParams {
26
+ readonly prompt: string;
27
+ readonly cwd: string;
28
+ readonly args?: readonly string[] | undefined;
29
+ }
30
+
31
+ /** The result names a harness `agent` step declares: a subset of `EndResult`. */
32
+ export type AgentResultName = Extract<EndResult, "done" | "failed" | "interrupted">;
33
+
34
+ /** What every harness `agent` step records as its facts. */
35
+ export interface AgentResultData {
36
+ readonly exitCode: number | null;
37
+ readonly signal: string | null;
38
+ readonly sessionId: string | null;
39
+ readonly finalMessage: string | null;
40
+ /** The standard usage; unknown cost is `costMicros: null`, a free run is `0`. */
41
+ readonly usage: Usage;
42
+ /** The path of the JSONL file the harness wrote. */
43
+ readonly log: string;
44
+ readonly durationMs: number;
45
+ /** Set on `failed`: which limit or condition ended the run. */
46
+ readonly reason?: string | undefined;
47
+ readonly message?: string | undefined;
48
+ /** The last lines of the harness's own error output. */
49
+ readonly stderr: readonly string[];
50
+ }
@@ -0,0 +1,13 @@
1
+ import { homedir } from "node:os";
2
+ import { resolve } from "node:path";
3
+
4
+ /**
5
+ * The operad home: `$OPERAD_HOME`, or `~/.operad`. The kernel keeps its
6
+ * config, store and loop here and assumes no repository.
7
+ */
8
+ export function defaultOperadHome(): string {
9
+ const fromEnv = process.env.OPERAD_HOME;
10
+ return fromEnv !== undefined && fromEnv.trim().length > 0
11
+ ? resolve(fromEnv)
12
+ : resolve(homedir(), ".operad");
13
+ }
@@ -0,0 +1,65 @@
1
+ export { definePlugin } from "./define-plugin.ts";
2
+ export { AccessError, AskTimeoutError, messageOf, PluginError, StartRefusedError, StepNotLoadedError } from "./errors.ts";
3
+ export { defaultOperadHome } from "./home.ts";
4
+ export {
5
+ ensureInstalledPackage,
6
+ installedPackageFile,
7
+ pluginProjectManifestPath,
8
+ pluginProjectPath,
9
+ PLUGIN_PROJECT_DIRECTORY,
10
+ runningFromWorkspace,
11
+ } from "./install.ts";
12
+ export type { EnsureInstalledOptions, InstallRun, InstallRunner } from "./install.ts";
13
+ export { keysPathFor, readKeysFile } from "./keys.ts";
14
+ export {
15
+ loadConfiguredPlugins,
16
+ loadPlugin,
17
+ loadPluginRegistry,
18
+ type ConfiguredPlugin,
19
+ type ConfiguredPlugins,
20
+ } from "./load.ts";
21
+ export type { LoadPluginRegistryOptions } from "./load.ts";
22
+ export { createPluginLogger } from "./logger.ts";
23
+ export { PluginRegistry, splitActionName } from "./registry.ts";
24
+ export type {
25
+ ActionInfo,
26
+ KeyBinding,
27
+ PluginRefusal,
28
+ PluginRegistryOptions,
29
+ } from "./registry.ts";
30
+ export { FileSecretStore, secretsDirectory, secretsPathFor } from "./secrets.ts";
31
+ export { prepareSettings } from "./settings.ts";
32
+ export { isRangeSyntax, satisfiesRange } from "./semver.ts";
33
+ export { MemoryPluginStore } from "./store.ts";
34
+ export type { MemoryPluginStoreOptions } from "./store.ts";
35
+ export { PLUGIN_STORE_SCHEMA_VERSION, SqlitePluginStore } from "./sqlite-store.ts";
36
+ export type { SqlitePluginStoreOptions } from "./sqlite-store.ts";
37
+ export { openPluginStore } from "./open-store.ts";
38
+ export type {
39
+ OpenPluginStoreOptions,
40
+ PluginStoreBackend,
41
+ } from "./open-store.ts";
42
+ export {
43
+ ActionArgsError,
44
+ fileProperties,
45
+ normalizeActionArgs,
46
+ noteProperty,
47
+ validateActionArgs,
48
+ } from "./action-schema.ts";
49
+ export {
50
+ assertWhere,
51
+ canonical,
52
+ CursorError,
53
+ DEFAULT_PAGE_LIMIT,
54
+ decodeCursor,
55
+ encodeCursor,
56
+ MAX_PAGE_LIMIT,
57
+ pageLimit,
58
+ WhereError,
59
+ whereFingerprint,
60
+ } from "./paging.ts";
61
+ export * from "./types.ts";
62
+ export * from "./object-facts.ts";
63
+ export * from "./harness.ts";
64
+ export * from "./usage.ts";
65
+ export * from "./filters.ts";
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Packages that are not part of the CLI's own dependencies are installed into
3
+ * one Bun project under the operad home when the person enables them
4
+ * (ADR 0012 D4). The project keeps its own
5
+ * `package.json` and lockfile; nothing is installed into the CLI's tree.
6
+ *
7
+ * The claude harness needs `@anthropic-ai/claude-agent-sdk`, whose optional
8
+ * per-platform packages carry a Claude Code binary operad does not use, so the
9
+ * install skips optional dependencies.
10
+ */
11
+
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { basename, dirname, join } from "node:path";
14
+ import { isRecord } from "../util.ts";
15
+
16
+ /** The directory under the operad home that holds the Bun project. */
17
+ export const PLUGIN_PROJECT_DIRECTORY = "plugins";
18
+
19
+ /** The package name the generated project manifests use. */
20
+ const PROJECT_NAME = "operad-plugins";
21
+
22
+ /** Where the home's plugin project lives. */
23
+ export function pluginProjectPath(home: string): string {
24
+ return join(home, PLUGIN_PROJECT_DIRECTORY);
25
+ }
26
+
27
+ /** The project manifest, when the home has one. */
28
+ export function pluginProjectManifestPath(home: string): string {
29
+ return join(pluginProjectPath(home), "package.json");
30
+ }
31
+
32
+ /**
33
+ * True in a checkout of the operad workspace, where packages load from the
34
+ * workspace links instead of the home project.
35
+ */
36
+ export function runningFromWorkspace(): boolean {
37
+ // This file is under src/plugin; walk to the package that holds it.
38
+ let packageDirectory = import.meta.dir;
39
+ for (;;) {
40
+ const parent = dirname(packageDirectory);
41
+ if (parent === packageDirectory) return false;
42
+ try {
43
+ const manifest: unknown = JSON.parse(readFileSync(join(parent, "package.json"), "utf8"));
44
+ if (isRecord(manifest) && manifest.name === "@operad-io/engine") {
45
+ packageDirectory = parent;
46
+ break;
47
+ }
48
+ } catch {
49
+ // Not a package directory; keep walking.
50
+ }
51
+ packageDirectory = parent;
52
+ }
53
+ if (basename(packageDirectory) !== "engine") return false;
54
+ const packagesDirectory = dirname(packageDirectory);
55
+ if (basename(packagesDirectory) !== "packages") return false;
56
+ const root = dirname(packagesDirectory);
57
+ try {
58
+ const manifest: unknown = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
59
+ return isRecord(manifest) && manifest.name === "operad-workspace" && Array.isArray(manifest.workspaces);
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ /** The package name of a specifier: `@scope/name` or `name`. */
66
+ function packageNameOf(specifier: string): string {
67
+ const parts = specifier.split("/");
68
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : (parts[0] ?? specifier);
69
+ }
70
+
71
+ /** The subpath of a specifier below its package name; empty for the package itself. */
72
+ function subpathOf(specifier: string): string {
73
+ return specifier.slice(packageNameOf(specifier).length).replace(/^\//, "");
74
+ }
75
+
76
+ /** The file an `exports` target names, following the conditions Bun imports first. */
77
+ function targetFile(value: unknown): string | undefined {
78
+ if (typeof value === "string") return value;
79
+ if (Array.isArray(value)) {
80
+ for (const item of value) {
81
+ const found = targetFile(item);
82
+ if (found !== undefined) return found;
83
+ }
84
+ return undefined;
85
+ }
86
+ if (isRecord(value)) {
87
+ for (const key of ["import", "bun", "default"]) {
88
+ if (key in value) {
89
+ const found = targetFile(value[key]);
90
+ if (found !== undefined) return found;
91
+ }
92
+ }
93
+ }
94
+ return undefined;
95
+ }
96
+
97
+ /**
98
+ * The file a specifier names in an installed package, read from the package's
99
+ * own `exports`. This is deliberately not `Bun.resolveSync`: Bun caches the
100
+ * miss from the check before the install, so the same process would not see the
101
+ * package it has just installed.
102
+ */
103
+ function packageEntry(packageDirectory: string, subpath: string): string | undefined {
104
+ let manifest: Record<string, unknown>;
105
+ try {
106
+ const value: unknown = JSON.parse(readFileSync(join(packageDirectory, "package.json"), "utf8"));
107
+ if (!isRecord(value)) return undefined;
108
+ manifest = value;
109
+ } catch {
110
+ return undefined;
111
+ }
112
+ const key = subpath === "" ? "." : `./${subpath}`;
113
+ const exportsField = manifest.exports;
114
+ let relative: string | undefined;
115
+ if (typeof exportsField === "string" || Array.isArray(exportsField)) {
116
+ if (subpath === "") relative = targetFile(exportsField);
117
+ } else if (isRecord(exportsField)) {
118
+ if (key in exportsField) relative = targetFile(exportsField[key]);
119
+ else if (subpath === "" && !Object.keys(exportsField).some((name) => name.startsWith("."))) {
120
+ relative = targetFile(exportsField);
121
+ }
122
+ } else if (subpath === "") {
123
+ relative = typeof manifest.main === "string" ? manifest.main : "index.js";
124
+ }
125
+ if (relative === undefined) return undefined;
126
+ const file = join(packageDirectory, relative);
127
+ return existsSync(file) ? file : undefined;
128
+ }
129
+
130
+ /**
131
+ * The file a specifier resolves to in the home's plugin project, or undefined
132
+ * when the project does not hold it.
133
+ */
134
+ export function installedPackageFile(home: string, specifier: string): string | undefined {
135
+ const manifest = pluginProjectManifestPath(home);
136
+ if (!existsSync(manifest)) return undefined;
137
+ const packageDirectory = join(pluginProjectPath(home), "node_modules", packageNameOf(specifier));
138
+ return packageEntry(packageDirectory, subpathOf(specifier));
139
+ }
140
+
141
+ /** What a command a test replaces returned. */
142
+ export interface InstallRun {
143
+ readonly exitCode: number | null;
144
+ readonly stdout: string;
145
+ readonly stderr: string;
146
+ }
147
+
148
+ /** Runs one command; a test replaces the real Bun process. */
149
+ export type InstallRunner = (cwd: string, args: readonly string[]) => InstallRun;
150
+
151
+ function runWithBun(cwd: string, args: readonly string[]): InstallRun {
152
+ const ran = Bun.spawnSync({
153
+ cmd: [process.execPath, ...args],
154
+ cwd,
155
+ stdin: "ignore",
156
+ stdout: "pipe",
157
+ stderr: "pipe",
158
+ });
159
+ return {
160
+ exitCode: ran.exitCode,
161
+ stdout: ran.stdout.toString(),
162
+ stderr: ran.stderr.toString(),
163
+ };
164
+ }
165
+
166
+ function readManifest(path: string): Record<string, unknown> | undefined {
167
+ let text: string;
168
+ try {
169
+ text = readFileSync(path, "utf8");
170
+ } catch (error) {
171
+ if (
172
+ typeof error === "object" &&
173
+ error !== null &&
174
+ "code" in error &&
175
+ (error as { code?: unknown }).code === "ENOENT"
176
+ ) {
177
+ return undefined;
178
+ }
179
+ throw error;
180
+ }
181
+ let value: unknown;
182
+ try {
183
+ value = JSON.parse(text);
184
+ } catch (error) {
185
+ throw new Error(`${path}: invalid JSON: ${String(error)}`, { cause: error });
186
+ }
187
+ if (!isRecord(value)) throw new Error(`${path}: must be a JSON object`);
188
+ return value;
189
+ }
190
+
191
+ /** A short spelling of what a failed install printed, for the refusal. */
192
+ function outputTail(run: InstallRun): string {
193
+ const text = `${run.stdout}\n${run.stderr}`.trim();
194
+ if (text.length === 0) return "it printed nothing";
195
+ const lines = text.split("\n").slice(-8).join("\n");
196
+ return lines.length > 2000 ? lines.slice(-2000) : lines;
197
+ }
198
+
199
+ /** Options for installing one package into the home project. */
200
+ export interface EnsureInstalledOptions {
201
+ readonly home: string;
202
+ /** The package to install, such as `@operad-io/harness-claude`. */
203
+ readonly specifier: string;
204
+ /** The version the CLI was published as. */
205
+ readonly version: string;
206
+ /** Where the CLI itself lives; used to recognise the workspace checkout. */
207
+ readonly from?: string | undefined;
208
+ /** Skip optional dependencies; the claude SDK's platform binaries are optional. */
209
+ readonly omitOptional?: boolean | undefined;
210
+ /** A test replaces the command; defaults to Bun. */
211
+ readonly run?: InstallRunner | undefined;
212
+ }
213
+
214
+ /**
215
+ * Makes sure `specifier` is available from the home project and returns its
216
+ * file. In a workspace checkout, where the package already resolves from the
217
+ * CLI, it returns undefined and installs nothing.
218
+ */
219
+ export async function ensureInstalledPackage(options: EnsureInstalledOptions): Promise<string | undefined> {
220
+ const { home, specifier, version } = options;
221
+ if (runningFromWorkspace() && options.from !== undefined) {
222
+ try {
223
+ Bun.resolveSync(specifier, join(options.from, "package.json"));
224
+ return undefined;
225
+ } catch {
226
+ // Not linked in this checkout: fall through to the home project.
227
+ }
228
+ }
229
+
230
+ const directory = pluginProjectPath(home);
231
+ const path = join(directory, "package.json");
232
+ const manifest = readManifest(path) ?? {
233
+ name: PROJECT_NAME,
234
+ private: true,
235
+ type: "module",
236
+ };
237
+ const rawDependencies = manifest.dependencies;
238
+ if (rawDependencies !== undefined && !isRecord(rawDependencies)) {
239
+ throw new Error(`${path}: dependencies must be an object`);
240
+ }
241
+ const dependencies: Record<string, unknown> = { ...(rawDependencies ?? {}) };
242
+ const existing = dependencies[specifier];
243
+ // A test (or a person pinning a local build) may name a tarball; keep it.
244
+ const wanted =
245
+ typeof existing === "string" && (existing === version || existing.startsWith("file:"))
246
+ ? existing
247
+ : version;
248
+ const found = installedPackageFile(home, specifier);
249
+ if (existing === wanted && found !== undefined) return found;
250
+
251
+ dependencies[specifier] = wanted;
252
+ manifest.dependencies = dependencies;
253
+ mkdirSync(directory, { recursive: true });
254
+ writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`);
255
+
256
+ const args = ["install", ...(options.omitOptional === true ? ["--omit=optional"] : []), "--no-summary"];
257
+ const run = (options.run ?? runWithBun)(directory, args);
258
+ if (run.exitCode !== 0) {
259
+ throw new Error(
260
+ `${specifier}: \`bun ${args.join(" ")}\` in ${directory} failed with exit code ${String(run.exitCode)}; ${outputTail(run)}`,
261
+ );
262
+ }
263
+ const installed = installedPackageFile(home, specifier);
264
+ if (installed === undefined) {
265
+ throw new Error(`${specifier}: was installed into ${directory}, but its entry does not resolve`);
266
+ }
267
+ return installed;
268
+ }
@@ -0,0 +1,63 @@
1
+ /** The person's key overrides: `$OPERAD_HOME/keys.json`, same shape as a plugin's `keys`. */
2
+
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { messageOf, PluginError } from "./errors.ts";
6
+ import type { KeyBindings } from "./types.ts";
7
+ import { isRecord } from "../util.ts";
8
+
9
+ function isMissing(error: unknown): boolean {
10
+ return (
11
+ typeof error === "object" &&
12
+ error !== null &&
13
+ "code" in error &&
14
+ error.code === "ENOENT"
15
+ );
16
+ }
17
+
18
+ /** The path of the key overrides for an operad home. */
19
+ export function keysPathFor(home: string): string {
20
+ return join(home, "keys.json");
21
+ }
22
+
23
+ /** Reads `~/.operad/keys.json`; a missing file means no overrides. */
24
+ export async function readKeysFile(path: string): Promise<KeyBindings> {
25
+ let text: string;
26
+ try {
27
+ text = await readFile(path, "utf8");
28
+ } catch (error) {
29
+ if (isMissing(error)) return {};
30
+ throw new PluginError(`key bindings "${path}": ${messageOf(error)}`, {
31
+ cause: error,
32
+ });
33
+ }
34
+
35
+ let raw: unknown;
36
+ try {
37
+ raw = JSON.parse(text);
38
+ } catch (error) {
39
+ throw new PluginError(
40
+ `key bindings "${path}": invalid JSON: ${messageOf(error)}`,
41
+ { cause: error },
42
+ );
43
+ }
44
+ if (!isRecord(raw)) {
45
+ throw new PluginError(`key bindings "${path}": must be a JSON object`);
46
+ }
47
+
48
+ const keys: Record<string, string> = {};
49
+ for (const [key, target] of Object.entries(raw)) {
50
+ if (key.trim().length === 0) {
51
+ throw new PluginError(
52
+ `key bindings "${path}": a key must be a non-empty string`,
53
+ );
54
+ }
55
+ if (typeof target !== "string" || target.trim().length === 0) {
56
+ throw new PluginError(
57
+ `key bindings "${path}": ${key}: must name an action as "<plugin>:<action>"`,
58
+ );
59
+ }
60
+ keys[key] = target;
61
+ }
62
+ return keys;
63
+ }