@kirkchinese/harness-forge 0.0.0-stage → 0.5.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.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/assets/icon.svg +12 -0
- package/cordis.patch.yml +28 -0
- package/docs/DETAIL.zh.md +47 -0
- package/lib/agents/presets.d.ts +98 -0
- package/lib/agents/presets.js +292 -0
- package/lib/agents/profiles.d.ts +58 -0
- package/lib/agents/profiles.js +279 -0
- package/lib/agents/row.d.ts +17 -0
- package/lib/agents/row.js +148 -0
- package/lib/client/paths.d.ts +12 -0
- package/lib/client/paths.js +68 -0
- package/lib/client/styles.d.ts +8 -0
- package/lib/client/styles.js +89 -0
- package/lib/client/typert.d.ts +25 -0
- package/lib/client/typert.js +158 -0
- package/lib/client.js +23823 -0
- package/lib/commands/definition.d.ts +40 -0
- package/lib/commands/definition.js +113 -0
- package/lib/commands/output-styles.d.ts +42 -0
- package/lib/commands/output-styles.js +152 -0
- package/lib/commands/row.d.ts +9 -0
- package/lib/commands/row.js +157 -0
- package/lib/context/instructions.d.ts +32 -0
- package/lib/context/instructions.js +88 -0
- package/lib/context/row.d.ts +16 -0
- package/lib/context/row.js +17 -0
- package/lib/dsh/commands.d.ts +30 -0
- package/lib/dsh/commands.js +61 -0
- package/lib/dsh/host.d.ts +110 -0
- package/lib/dsh/host.js +217 -0
- package/lib/dsh/model-route.d.ts +21 -0
- package/lib/dsh/model-route.js +37 -0
- package/lib/dsh/session-records.d.ts +78 -0
- package/lib/dsh/session-records.js +36 -0
- package/lib/dsh/subagents.d.ts +46 -0
- package/lib/dsh/subagents.js +14 -0
- package/lib/forge/contract.d.ts +271 -0
- package/lib/forge/contract.js +45 -0
- package/lib/forge/follow.d.ts +30 -0
- package/lib/forge/follow.js +73 -0
- package/lib/forge/ledger.d.ts +206 -0
- package/lib/forge/ledger.js +1005 -0
- package/lib/forge/live-mounts.d.ts +45 -0
- package/lib/forge/live-mounts.js +78 -0
- package/lib/forge/npm.d.ts +31 -0
- package/lib/forge/npm.js +60 -0
- package/lib/forge/projects.d.ts +97 -0
- package/lib/forge/projects.js +343 -0
- package/lib/forge/receipts.d.ts +5 -0
- package/lib/forge/receipts.js +31 -0
- package/lib/forge/remote/archive.d.ts +65 -0
- package/lib/forge/remote/archive.js +565 -0
- package/lib/forge/remote/code-parts.d.ts +18 -0
- package/lib/forge/remote/code-parts.js +76 -0
- package/lib/forge/remote/fetch.d.ts +265 -0
- package/lib/forge/remote/fetch.js +1133 -0
- package/lib/forge/remote/service.d.ts +256 -0
- package/lib/forge/remote/service.js +868 -0
- package/lib/forge/row.d.ts +32 -0
- package/lib/forge/row.js +59 -0
- package/lib/forge/service.d.ts +115 -0
- package/lib/forge/service.js +290 -0
- package/lib/forge/settings.d.ts +43 -0
- package/lib/forge/settings.js +122 -0
- package/lib/forge/state.d.ts +129 -0
- package/lib/forge/state.js +266 -0
- package/lib/forge/trust.d.ts +48 -0
- package/lib/forge/trust.js +107 -0
- package/lib/forge/turns.d.ts +13 -0
- package/lib/forge/turns.js +56 -0
- package/lib/hooks/broker/engine.d.ts +112 -0
- package/lib/hooks/broker/engine.js +722 -0
- package/lib/hooks/broker/helpers.d.ts +10 -0
- package/lib/hooks/broker/helpers.js +22 -0
- package/lib/hooks/broker/lifecycle.d.ts +65 -0
- package/lib/hooks/broker/lifecycle.js +342 -0
- package/lib/hooks/broker/session-events.d.ts +27 -0
- package/lib/hooks/broker/session-events.js +205 -0
- package/lib/hooks/broker/tools.d.ts +52 -0
- package/lib/hooks/broker/tools.js +424 -0
- package/lib/hooks/broker/types.d.ts +264 -0
- package/lib/hooks/broker/types.js +1 -0
- package/lib/hooks/broker.d.ts +80 -0
- package/lib/hooks/broker.js +95 -0
- package/lib/hooks/codex-user.d.ts +5 -0
- package/lib/hooks/codex-user.js +109 -0
- package/lib/hooks/condition.d.ts +87 -0
- package/lib/hooks/condition.js +602 -0
- package/lib/hooks/config.d.ts +85 -0
- package/lib/hooks/config.js +154 -0
- package/lib/hooks/glob.d.ts +41 -0
- package/lib/hooks/glob.js +114 -0
- package/lib/hooks/matcher.d.ts +20 -0
- package/lib/hooks/matcher.js +39 -0
- package/lib/hooks/notice.d.ts +17 -0
- package/lib/hooks/notice.js +39 -0
- package/lib/hooks/output.d.ts +56 -0
- package/lib/hooks/output.js +214 -0
- package/lib/hooks/permissions.d.ts +19 -0
- package/lib/hooks/permissions.js +202 -0
- package/lib/hooks/powershell-aliases.d.ts +19 -0
- package/lib/hooks/powershell-aliases.js +58 -0
- package/lib/hooks/process.d.ts +64 -0
- package/lib/hooks/process.js +289 -0
- package/lib/hooks/row.d.ts +17 -0
- package/lib/hooks/row.js +96 -0
- package/lib/hooks/runner.d.ts +98 -0
- package/lib/hooks/runner.js +322 -0
- package/lib/hooks/shell-commands.d.ts +28 -0
- package/lib/hooks/shell-commands.js +241 -0
- package/lib/hooks/shell.d.ts +44 -0
- package/lib/hooks/shell.js +129 -0
- package/lib/hooks/transcript.d.ts +28 -0
- package/lib/hooks/transcript.js +141 -0
- package/lib/hooks/vocabulary.d.ts +57 -0
- package/lib/hooks/vocabulary.js +366 -0
- package/lib/index.d.ts +31 -0
- package/lib/index.js +287 -0
- package/lib/mcp/auth.d.ts +35 -0
- package/lib/mcp/auth.js +178 -0
- package/lib/mcp/catalog.d.ts +39 -0
- package/lib/mcp/catalog.js +69 -0
- package/lib/mcp/mount.d.ts +113 -0
- package/lib/mcp/mount.js +317 -0
- package/lib/mcp/policy.d.ts +42 -0
- package/lib/mcp/policy.js +43 -0
- package/lib/mcp/remote.d.ts +45 -0
- package/lib/mcp/remote.js +133 -0
- package/lib/mcp/row.d.ts +9 -0
- package/lib/mcp/row.js +225 -0
- package/lib/mods/bundler.d.ts +38 -0
- package/lib/mods/bundler.js +157 -0
- package/lib/mods/chain.d.ts +103 -0
- package/lib/mods/chain.js +436 -0
- package/lib/mods/claude.d.ts +27 -0
- package/lib/mods/claude.js +56 -0
- package/lib/mods/engine.d.ts +160 -0
- package/lib/mods/engine.js +701 -0
- package/lib/mods/expect.d.ts +8 -0
- package/lib/mods/expect.js +248 -0
- package/lib/mods/host.d.ts +105 -0
- package/lib/mods/host.js +462 -0
- package/lib/mods/loader.d.ts +53 -0
- package/lib/mods/loader.js +231 -0
- package/lib/mods/ops.d.ts +13 -0
- package/lib/mods/ops.js +117 -0
- package/lib/mods/row.d.ts +9 -0
- package/lib/mods/row.js +77 -0
- package/lib/mods/runtime.d.ts +60 -0
- package/lib/mods/runtime.js +133 -0
- package/lib/mods/service/commands.d.ts +17 -0
- package/lib/mods/service/commands.js +121 -0
- package/lib/mods/service/drawings.d.ts +36 -0
- package/lib/mods/service/drawings.js +64 -0
- package/lib/mods/service/sessions.d.ts +63 -0
- package/lib/mods/service/sessions.js +345 -0
- package/lib/mods/service/tools.d.ts +32 -0
- package/lib/mods/service/tools.js +253 -0
- package/lib/mods/service/turns.d.ts +33 -0
- package/lib/mods/service/turns.js +136 -0
- package/lib/mods/service/types.d.ts +151 -0
- package/lib/mods/service/types.js +1 -0
- package/lib/mods/service.d.ts +72 -0
- package/lib/mods/service.js +104 -0
- package/lib/mods/surfaces.d.ts +93 -0
- package/lib/mods/surfaces.js +309 -0
- package/lib/mods/values.d.ts +30 -0
- package/lib/mods/values.js +95 -0
- package/lib/opencode/bun.d.ts +40 -0
- package/lib/opencode/bun.js +168 -0
- package/lib/opencode/convert.d.ts +53 -0
- package/lib/opencode/convert.js +255 -0
- package/lib/opencode/row.d.ts +22 -0
- package/lib/opencode/row.js +104 -0
- package/lib/opencode/runtime/core.d.ts +74 -0
- package/lib/opencode/runtime/core.js +249 -0
- package/lib/opencode/runtime/events.d.ts +80 -0
- package/lib/opencode/runtime/events.js +281 -0
- package/lib/opencode/runtime/mount.d.ts +27 -0
- package/lib/opencode/runtime/mount.js +283 -0
- package/lib/opencode/runtime/server.d.ts +27 -0
- package/lib/opencode/runtime/server.js +354 -0
- package/lib/opencode/runtime/types.d.ts +109 -0
- package/lib/opencode/runtime/types.js +1 -0
- package/lib/opencode/runtime.d.ts +55 -0
- package/lib/opencode/runtime.js +79 -0
- package/lib/porting/adapter-paths.d.ts +13 -0
- package/lib/porting/adapter-paths.js +120 -0
- package/lib/porting/port-gap.d.ts +36 -0
- package/lib/porting/port-gap.js +158 -0
- package/lib/porting/port-sessions.d.ts +41 -0
- package/lib/porting/port-sessions.js +98 -0
- package/lib/porting/prompt.d.ts +23 -0
- package/lib/porting/prompt.js +51 -0
- package/lib/porting/row.d.ts +16 -0
- package/lib/porting/row.js +27 -0
- package/lib/porting/verify-port.d.ts +46 -0
- package/lib/porting/verify-port.js +82 -0
- package/lib/presets/fs-search.d.ts +25 -0
- package/lib/presets/fs-search.js +17 -0
- package/lib/presets/tool-filter.d.ts +35 -0
- package/lib/presets/tool-filter.js +91 -0
- package/lib/sessions/chat-import.d.ts +48 -0
- package/lib/sessions/chat-import.js +44 -0
- package/lib/sessions/claude.d.ts +35 -0
- package/lib/sessions/claude.js +104 -0
- package/lib/sessions/codex-discover.d.ts +34 -0
- package/lib/sessions/codex-discover.js +205 -0
- package/lib/sessions/codex-meta.d.ts +63 -0
- package/lib/sessions/codex-meta.js +148 -0
- package/lib/sessions/codex-text.d.ts +9 -0
- package/lib/sessions/codex-text.js +44 -0
- package/lib/sessions/codex.d.ts +42 -0
- package/lib/sessions/codex.js +270 -0
- package/lib/sessions/opencode.d.ts +38 -0
- package/lib/sessions/opencode.js +339 -0
- package/lib/sessions/persist.d.ts +162 -0
- package/lib/sessions/persist.js +377 -0
- package/lib/sessions/row.d.ts +15 -0
- package/lib/sessions/row.js +101 -0
- package/lib/sessions/turns.d.ts +31 -0
- package/lib/sessions/turns.js +63 -0
- package/lib/sessions/zstd.d.ts +15 -0
- package/lib/sessions/zstd.js +152 -0
- package/lib/shared/invocation.d.ts +169 -0
- package/lib/shared/invocation.js +325 -0
- package/lib/shared/render.d.ts +101 -0
- package/lib/shared/render.js +1353 -0
- package/lib/shared/util.d.ts +21 -0
- package/lib/shared/util.js +32 -0
- package/lib/skills/bundled.d.ts +3 -0
- package/lib/skills/bundled.js +42 -0
- package/lib/skills/provider.d.ts +74 -0
- package/lib/skills/provider.js +346 -0
- package/lib/skills/row.d.ts +22 -0
- package/lib/skills/row.js +204 -0
- package/lib/workbench/adapter-coverage.d.ts +65 -0
- package/lib/workbench/adapter-coverage.js +141 -0
- package/lib/workbench/model-tools.d.ts +10 -0
- package/lib/workbench/model-tools.js +122 -0
- package/lib/workbench/overview.d.ts +153 -0
- package/lib/workbench/overview.js +246 -0
- package/lib/workbench/remote.d.ts +161 -0
- package/lib/workbench/remote.js +561 -0
- package/lib/workbench/row.d.ts +15 -0
- package/lib/workbench/row.js +16 -0
- package/lib/workbench/settings.d.ts +19 -0
- package/lib/workbench/settings.js +60 -0
- package/lib/workbench/workbench.d.ts +130 -0
- package/lib/workbench/workbench.js +361 -0
- package/locale/agents/en.json +6 -0
- package/locale/agents/zh.json +6 -0
- package/locale/commands/en.json +6 -0
- package/locale/commands/zh.json +6 -0
- package/locale/context/en.json +6 -0
- package/locale/context/zh.json +6 -0
- package/locale/en.json +6 -0
- package/locale/hooks/en.json +6 -0
- package/locale/hooks/zh.json +6 -0
- package/locale/mcp/en.json +6 -0
- package/locale/mcp/zh.json +6 -0
- package/locale/mods/en.json +6 -0
- package/locale/mods/zh.json +6 -0
- package/locale/opencode/en.json +6 -0
- package/locale/opencode/zh.json +6 -0
- package/locale/porter/en.json +6 -0
- package/locale/porter/zh.json +6 -0
- package/locale/sessions/en.json +6 -0
- package/locale/sessions/zh.json +6 -0
- package/locale/skills/en.json +6 -0
- package/locale/skills/zh.json +6 -0
- package/locale/workbench/en.json +6 -0
- package/locale/workbench/zh.json +6 -0
- package/locale/zh.json +7 -0
- package/package.json +247 -3
- package/runtime/opencode-host.mjs +270 -0
- package/skills/harness-forge/SKILL.md +47 -0
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The mods engine of one session: the loaded mods, their hooks, and the `$`
|
|
3
|
+
* each hook receives, as Claude Code defines them (claude-code.d.ts; mods
|
|
4
|
+
* docs). The host supplies core: what the engine does at each event and how
|
|
5
|
+
* each `$` call is served. A session in DSH is one engine, so a mod's module
|
|
6
|
+
* state, `$.state` and timers are the session's own, as in Claude Code.
|
|
7
|
+
* @module @kirkchinese/harness-forge/mods
|
|
8
|
+
*/
|
|
9
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
10
|
+
import { CATCH_BUDGET_MS, chainOrder, dispatch, ENGINE_ORIGIN, HOOK_BUDGET_MS, matches, selects, } from './chain.js';
|
|
11
|
+
import { OPS } from './ops.js';
|
|
12
|
+
import { deepFreeze, errorLine, frozenCopy, isRecord, isThenable, messageOf } from './values.js';
|
|
13
|
+
/** Events whose hooks see another mod's controls, panes and band only under `plugin`. */
|
|
14
|
+
const OWNED_UI_EVENTS = new Set(['ui.press', 'ui.input', 'ui.select', 'ui.focus', 'ui.render', 'ui.message', 'ui.fault', 'ui.scroll']);
|
|
15
|
+
/** Engine events a mod's `$` raises with the event's own result. */
|
|
16
|
+
const EVENT_RESULTS = new Set(Object.values(OPS).filter(op => op.kind === 'event').map(op => op.event));
|
|
17
|
+
/** Plugin noun methods raise `<noun>.<method>` with `{ value } | { deny }` results. */
|
|
18
|
+
function valueOrDeny(result) {
|
|
19
|
+
if (!isRecord(result))
|
|
20
|
+
return 'returned neither { value } nor { deny }';
|
|
21
|
+
if (typeof result['deny'] === 'string')
|
|
22
|
+
return undefined;
|
|
23
|
+
if ('value' in result)
|
|
24
|
+
return undefined;
|
|
25
|
+
return 'returned neither { value } nor { deny }';
|
|
26
|
+
}
|
|
27
|
+
/** Why an engine event's result is the wrong shape, per event. */
|
|
28
|
+
function validateEvent(event, result, called) {
|
|
29
|
+
if (event === 'engine.create' || event === 'turn.step')
|
|
30
|
+
return undefined;
|
|
31
|
+
if (event === 'ui.render')
|
|
32
|
+
return undefined;
|
|
33
|
+
if (!isRecord(result))
|
|
34
|
+
return `returned ${result === null ? 'null' : typeof result}, not the ${event} result`;
|
|
35
|
+
if (event === 'prompt.submit' && typeof result['drop'] === 'string' && called)
|
|
36
|
+
return 'returned a drop after its next() was answered';
|
|
37
|
+
if (event === 'tool.check' && !['allow', 'ask', 'deny'].includes(String(result['decision'])))
|
|
38
|
+
return 'returned no decision of allow, ask or deny';
|
|
39
|
+
if (event === 'plugin.register' && result['allow'] !== true && typeof result['refuse'] !== 'string')
|
|
40
|
+
return 'returned neither { allow: true } nor { refuse }';
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
let hookIds = 0;
|
|
44
|
+
/** A `$` call the chain refused or could not serve, as the calling plugin receives it. */
|
|
45
|
+
export class HooksError extends Error {
|
|
46
|
+
name = 'HooksError';
|
|
47
|
+
}
|
|
48
|
+
/** A `HooksError` of the mod's own environment, so its `instanceof Error` holds. */
|
|
49
|
+
function hooksError(mod, message) {
|
|
50
|
+
const realm = mod.definition.realm;
|
|
51
|
+
if (realm === undefined)
|
|
52
|
+
return new HooksError(message);
|
|
53
|
+
let Realmed = realmErrors.get(realm.Error);
|
|
54
|
+
if (Realmed === undefined) {
|
|
55
|
+
const Base = realm.Error;
|
|
56
|
+
Realmed = class extends Base {
|
|
57
|
+
constructor(text) {
|
|
58
|
+
super(text);
|
|
59
|
+
this.name = 'HooksError';
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
realmErrors.set(realm.Error, Realmed);
|
|
63
|
+
}
|
|
64
|
+
return new Realmed(message);
|
|
65
|
+
}
|
|
66
|
+
const realmErrors = new WeakMap();
|
|
67
|
+
function opError(mod, event, error) {
|
|
68
|
+
if (typeof error === 'object' && error !== null && error.name === 'HooksError')
|
|
69
|
+
return error;
|
|
70
|
+
return hooksError(mod, `${mod.ref.name}: $.${event}: ${messageOf(error)}`);
|
|
71
|
+
}
|
|
72
|
+
/** The mods engine of one session. */
|
|
73
|
+
export class ModsEngine {
|
|
74
|
+
host;
|
|
75
|
+
options;
|
|
76
|
+
mods = [];
|
|
77
|
+
/** `$.state`, keyed `<plugin>\u0000<key>`. */
|
|
78
|
+
state = new Map();
|
|
79
|
+
hooks = [];
|
|
80
|
+
/** Nouns the plugins' `engine.create` steps added: noun → method → its owner's function. */
|
|
81
|
+
nouns = {};
|
|
82
|
+
context = new AsyncLocalStorage();
|
|
83
|
+
rank = 0;
|
|
84
|
+
disposed = false;
|
|
85
|
+
constructor(host, options = {}) {
|
|
86
|
+
this.host = host;
|
|
87
|
+
this.options = options;
|
|
88
|
+
}
|
|
89
|
+
/** The hooks of every loaded mod, in chain order. */
|
|
90
|
+
get registered() {
|
|
91
|
+
return this.hooks;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Load mods: each passes `plugin.register` (the loaded mods may refuse it),
|
|
95
|
+
* runs `register(on, options)`, and the batch's `engine.create` fold adds
|
|
96
|
+
* the nouns they provide.
|
|
97
|
+
* @returns the names refused, with who refused and why, and the ones whose
|
|
98
|
+
* `register` threw.
|
|
99
|
+
*/
|
|
100
|
+
async load(definitions) {
|
|
101
|
+
const refused = [];
|
|
102
|
+
const failed = [];
|
|
103
|
+
// Every module registers first; then each joins only if the others' plugin.register hooks let it.
|
|
104
|
+
const candidates = [];
|
|
105
|
+
for (const definition of definitions) {
|
|
106
|
+
if (this.mods.some(mod => mod.ref.name === definition.name) || candidates.some(mod => mod.ref.name === definition.name)) {
|
|
107
|
+
failed.push({ name: definition.name, error: `${definition.name} is already loaded` });
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (definition.refusal !== undefined) {
|
|
111
|
+
failed.push({ name: definition.name, error: definition.refusal });
|
|
112
|
+
this.host.report(`${definition.name}: hooks module did not load: ${definition.refusal}`);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const mod = { ref: Object.freeze({ name: definition.name, tier: definition.tier ?? 'user', rank: this.rank++ }), definition, hooks: [], timers: new Set() };
|
|
116
|
+
this.pending.add(mod);
|
|
117
|
+
try {
|
|
118
|
+
await this.register(mod);
|
|
119
|
+
candidates.push(mod);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
this.pending.delete(mod);
|
|
123
|
+
failed.push({ name: definition.name, error: messageOf(error) });
|
|
124
|
+
this.host.report(`${definition.name}: hooks module did not load: ${errorLine(error)}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const admitted = new Set(candidates);
|
|
128
|
+
for (const mod of candidates) {
|
|
129
|
+
const others = [...this.hooks, ...[...admitted].filter(other => other !== mod).flatMap(other => other.hooks)].sort(chainOrder);
|
|
130
|
+
let refuser = '';
|
|
131
|
+
const definition = mod.definition;
|
|
132
|
+
const verdict = await this.dispatchEngine('plugin.register', {
|
|
133
|
+
name: definition.name,
|
|
134
|
+
tier: mod.ref.tier,
|
|
135
|
+
root: definition.root ?? '',
|
|
136
|
+
provenance: definition.provenance ?? `${definition.name}@inline`,
|
|
137
|
+
uses: definition.uses ?? { events: [], calls: [] },
|
|
138
|
+
...(definition.version !== undefined ? { version: definition.version } : {}),
|
|
139
|
+
}, ENGINE_ORIGIN, {
|
|
140
|
+
hooks: others,
|
|
141
|
+
observe: (hook, result) => { if (refuser === '' && isRecord(result) && typeof result['refuse'] === 'string')
|
|
142
|
+
refuser = hook.mod.name; },
|
|
143
|
+
}).catch((error) => ({ refuse: messageOf(error) }));
|
|
144
|
+
if (isRecord(verdict) && typeof verdict['refuse'] === 'string') {
|
|
145
|
+
admitted.delete(mod);
|
|
146
|
+
refused.push({ name: definition.name, by: refuser || 'engine', reason: verdict['refuse'] });
|
|
147
|
+
this.host.report(`${definition.name}: refused by ${refuser || 'engine'}: ${verdict['refuse']}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const batch = candidates.filter(mod => admitted.has(mod));
|
|
151
|
+
for (const mod of candidates)
|
|
152
|
+
this.pending.delete(mod);
|
|
153
|
+
for (const mod of batch)
|
|
154
|
+
this.mods.push(mod);
|
|
155
|
+
this.hooks = [...this.hooks, ...batch.flatMap(mod => mod.hooks)].sort(chainOrder);
|
|
156
|
+
if (batch.length > 0)
|
|
157
|
+
await this.create(batch);
|
|
158
|
+
return { refused, failed };
|
|
159
|
+
}
|
|
160
|
+
/** Mods registering in a load, before they join the chain. */
|
|
161
|
+
pending = new Set();
|
|
162
|
+
/** Unload one mod: its hooks leave the chain and its timers stop. */
|
|
163
|
+
async unload(name) {
|
|
164
|
+
const mod = this.mods.find(item => item.ref.name === name);
|
|
165
|
+
if (mod === undefined)
|
|
166
|
+
return;
|
|
167
|
+
for (const timer of mod.timers)
|
|
168
|
+
timer.cancel();
|
|
169
|
+
this.mods.splice(this.mods.indexOf(mod), 1);
|
|
170
|
+
this.hooks = this.hooks.filter(hook => hook.mod !== mod.ref);
|
|
171
|
+
for (const [noun, owner] of Object.entries(this.nounOwners))
|
|
172
|
+
if (owner === name)
|
|
173
|
+
delete this.nouns[noun];
|
|
174
|
+
}
|
|
175
|
+
/** Stop every mod's timers; the engine raises nothing more. */
|
|
176
|
+
dispose() {
|
|
177
|
+
this.disposed = true;
|
|
178
|
+
for (const mod of this.mods)
|
|
179
|
+
for (const timer of mod.timers)
|
|
180
|
+
timer.cancel();
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Raise one of the engine's events through every hook on it, core last.
|
|
184
|
+
* @param origin who raised it: the engine unless a client or test says so.
|
|
185
|
+
*/
|
|
186
|
+
raise(event, input, options = {}) {
|
|
187
|
+
return this.dispatchEngine(event, input, options.origin ?? ENGINE_ORIGIN, options.signal === undefined ? {} : { signal: options.signal });
|
|
188
|
+
}
|
|
189
|
+
/** The `$` a mod's code holds outside any hook (its `register`, timers, buttons). */
|
|
190
|
+
apiOf(name) {
|
|
191
|
+
const mod = this.mods.find(item => item.ref.name === name);
|
|
192
|
+
if (mod === undefined)
|
|
193
|
+
throw new Error(`no mod named ${name} is loaded`);
|
|
194
|
+
return this.api(mod, undefined);
|
|
195
|
+
}
|
|
196
|
+
/** Run `fn` outside any hook's call context: what it schedules is the engine's own, not a re-entry of a hook. */
|
|
197
|
+
outside(fn) {
|
|
198
|
+
this.context.exit(fn);
|
|
199
|
+
}
|
|
200
|
+
/** The current `ui.render` run of a state read, if any. */
|
|
201
|
+
currentRender() {
|
|
202
|
+
return this.context.getStore()?.render;
|
|
203
|
+
}
|
|
204
|
+
// ---------------------------------------------------------------------------
|
|
205
|
+
nounOwners = {};
|
|
206
|
+
async register(mod) {
|
|
207
|
+
let open = true;
|
|
208
|
+
let seq = 0;
|
|
209
|
+
const unmatched = new Set();
|
|
210
|
+
const on = (pattern, second, third) => {
|
|
211
|
+
if (!open)
|
|
212
|
+
throw new Error(`${mod.ref.name}: on("${String(pattern)}") after register() returned`);
|
|
213
|
+
if (typeof pattern !== 'string' || pattern.length === 0)
|
|
214
|
+
throw new Error(`${mod.ref.name}: on() takes an event name or pattern`);
|
|
215
|
+
const hasMatcher = third !== undefined;
|
|
216
|
+
const fn = (hasMatcher ? third : second);
|
|
217
|
+
if (typeof fn !== 'function')
|
|
218
|
+
throw new Error(`${mod.ref.name}: on("${pattern}") takes a hook function`);
|
|
219
|
+
if (hasMatcher && !isRecord(second))
|
|
220
|
+
throw new Error(`${mod.ref.name}: on("${pattern}") takes a matcher object`);
|
|
221
|
+
if (!hasMatcher) {
|
|
222
|
+
if (unmatched.has(pattern))
|
|
223
|
+
throw new Error(`on("${pattern}") is registered twice without a matcher`);
|
|
224
|
+
unmatched.add(pattern);
|
|
225
|
+
}
|
|
226
|
+
const hook = { id: ++hookIds, mod: mod.ref, pattern, matcher: hasMatcher ? deepFreeze(second) : undefined, fn, seq: seq++ };
|
|
227
|
+
mod.hooks.push(hook);
|
|
228
|
+
let caught = false;
|
|
229
|
+
return Object.freeze({
|
|
230
|
+
catch: (handler) => {
|
|
231
|
+
if (!open)
|
|
232
|
+
throw new Error(`${mod.ref.name}: .catch on on("${pattern}") after register() returned`);
|
|
233
|
+
if (caught)
|
|
234
|
+
throw new Error(`${mod.ref.name}: on("${pattern}") takes one .catch`);
|
|
235
|
+
if (pattern === 'engine.create')
|
|
236
|
+
throw new Error(`${mod.ref.name}: an engine.create hook takes no .catch`);
|
|
237
|
+
if (typeof handler !== 'function')
|
|
238
|
+
throw new Error(`${mod.ref.name}: .catch takes a handler function`);
|
|
239
|
+
caught = true;
|
|
240
|
+
hook.catchFn = handler;
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
try {
|
|
245
|
+
const out = this.context.run({ callers: new Set(), outside: new Set([mod.ref.name]) }, () => mod.definition.register(on, deepFreeze({ ...(mod.definition.options ?? {}) })));
|
|
246
|
+
if (isThenable(out))
|
|
247
|
+
await out;
|
|
248
|
+
}
|
|
249
|
+
finally {
|
|
250
|
+
open = false;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* The `engine.create` fold over a batch: the nouns its steps add. Between
|
|
255
|
+
* steps the table crosses as descriptors: each step sees objects whose
|
|
256
|
+
* methods raise their events as that step's plugin, so a step calling a
|
|
257
|
+
* noun off its table is gated as any caller is.
|
|
258
|
+
*/
|
|
259
|
+
async create(batch) {
|
|
260
|
+
const core = this.coreNouns();
|
|
261
|
+
const owners = new Map();
|
|
262
|
+
const seen = new WeakMap();
|
|
263
|
+
const raw = (table) => {
|
|
264
|
+
const out = {};
|
|
265
|
+
if (!isRecord(table))
|
|
266
|
+
return out;
|
|
267
|
+
for (const [noun, value] of Object.entries(table)) {
|
|
268
|
+
if (noun in core || noun === 'plugin' || noun === 'state' || !isRecord(value))
|
|
269
|
+
continue;
|
|
270
|
+
out[noun] = Object.freeze(Object.fromEntries(Object.entries(value).map(([method, fn]) => [method, typeof fn === 'function' ? this.ownerOf.get(fn) ?? fn : fn])));
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
};
|
|
274
|
+
const built = await this.dispatchEngine('engine.create', { plugins: batch.map(mod => mod.ref.name) }, ENGINE_ORIGIN, {
|
|
275
|
+
bottom: () => ({ ...this.nouns }),
|
|
276
|
+
received: (hook, value) => {
|
|
277
|
+
if (!isRecord(value))
|
|
278
|
+
return value;
|
|
279
|
+
const cached = seen.get(value);
|
|
280
|
+
if (cached !== undefined)
|
|
281
|
+
return cached;
|
|
282
|
+
const mod = this.modOf(hook);
|
|
283
|
+
const table = { ...this.api(mod, undefined) };
|
|
284
|
+
for (const [noun, methods] of Object.entries(raw(value))) {
|
|
285
|
+
table[noun] = Object.freeze(Object.fromEntries(Object.entries(methods).map(([method, fn]) => {
|
|
286
|
+
if (typeof fn !== 'function')
|
|
287
|
+
return [method, fn];
|
|
288
|
+
const wrapped = (...args) => this.callNoun(mod, undefined, noun, method, fn, args);
|
|
289
|
+
this.ownerOf.set(wrapped, fn);
|
|
290
|
+
return [method, wrapped];
|
|
291
|
+
})));
|
|
292
|
+
}
|
|
293
|
+
const frozen = Object.freeze(table);
|
|
294
|
+
seen.set(value, frozen);
|
|
295
|
+
return frozen;
|
|
296
|
+
},
|
|
297
|
+
observe: (hook, result) => {
|
|
298
|
+
for (const noun of Object.keys(raw(result)))
|
|
299
|
+
if (!owners.has(noun) && this.nouns[noun] === undefined)
|
|
300
|
+
owners.set(noun, hook.mod.name);
|
|
301
|
+
},
|
|
302
|
+
emptyApi: true,
|
|
303
|
+
});
|
|
304
|
+
for (const [noun, methods] of Object.entries(raw(built))) {
|
|
305
|
+
this.nouns[noun] = methods;
|
|
306
|
+
this.nounOwners[noun] ??= owners.get(noun) ?? '';
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/** The owner's function behind a noun method handed to a step. */
|
|
310
|
+
ownerOf = new WeakMap();
|
|
311
|
+
coreNouns() {
|
|
312
|
+
const nouns = {};
|
|
313
|
+
for (const name of Object.keys(OPS))
|
|
314
|
+
nouns[name.split('.')[0]] = true;
|
|
315
|
+
return nouns;
|
|
316
|
+
}
|
|
317
|
+
/** Hooks selected by an event, in chain order. */
|
|
318
|
+
selected(event) {
|
|
319
|
+
return this.hooks.filter(hook => selects(hook.pattern, event));
|
|
320
|
+
}
|
|
321
|
+
applies(event) {
|
|
322
|
+
return (hook, e) => {
|
|
323
|
+
if (hook.matcher !== undefined && !matches(hook.matcher, e))
|
|
324
|
+
return false;
|
|
325
|
+
// Another mod's controls, panes and band reach a hook only under `plugin`.
|
|
326
|
+
if (OWNED_UI_EVENTS.has(event) && isRecord(e) && typeof e['plugin'] === 'string' && e['plugin'] !== hook.mod.name) {
|
|
327
|
+
const wildcard = hook.pattern === '*' || hook.pattern.endsWith('.*');
|
|
328
|
+
const named = isRecord(hook.matcher) && 'plugin' in hook.matcher;
|
|
329
|
+
if (!named && !(wildcard && hook.matcher === undefined))
|
|
330
|
+
return false;
|
|
331
|
+
if (named && hook.matcher['plugin'] === '*')
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
return true;
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
reentry() {
|
|
338
|
+
const context = this.context.getStore();
|
|
339
|
+
if (context === undefined || (context.callers.size === 0 && context.outside.size === 0))
|
|
340
|
+
return undefined;
|
|
341
|
+
return hook => (context.callers.has(hook.id) || context.outside.has(hook.mod.name) ? true : false);
|
|
342
|
+
}
|
|
343
|
+
dispatchEngine(event, input, origin, extra = {}) {
|
|
344
|
+
if (this.disposed)
|
|
345
|
+
return Promise.reject(new Error(`the mods engine is closed; ${event} was not raised`));
|
|
346
|
+
const signal = extra.signal ?? new AbortController().signal;
|
|
347
|
+
const reentry = this.reentry();
|
|
348
|
+
return dispatch({
|
|
349
|
+
event,
|
|
350
|
+
input,
|
|
351
|
+
origin,
|
|
352
|
+
hooks: extra.hooks === undefined ? this.selected(event) : extra.hooks.filter(hook => selects(hook.pattern, event)),
|
|
353
|
+
bottom: async (e, bottomSignal, above) => (extra.bottom !== undefined
|
|
354
|
+
? extra.bottom(e, bottomSignal, above)
|
|
355
|
+
: this.host.core(event, e, { origin, signal: bottomSignal })),
|
|
356
|
+
api: (frame) => {
|
|
357
|
+
if (extra.emptyApi !== true)
|
|
358
|
+
return this.api(this.modOf(frame.hook), frame);
|
|
359
|
+
this.host.ran?.(frame.hook.mod.name, frame.event);
|
|
360
|
+
return EMPTY_API;
|
|
361
|
+
},
|
|
362
|
+
applies: this.applies(event),
|
|
363
|
+
...(reentry !== undefined ? { reentry } : {}),
|
|
364
|
+
validate: (result, called) => validateEvent(event, result, called),
|
|
365
|
+
report: line => { this.host.report(line); },
|
|
366
|
+
signal,
|
|
367
|
+
budgetMs: this.options.budgetMs ?? HOOK_BUDGET_MS,
|
|
368
|
+
catchMs: this.options.catchMs ?? CATCH_BUDGET_MS,
|
|
369
|
+
...(extra.observe !== undefined ? { observe: extra.observe } : {}),
|
|
370
|
+
...(extra.received !== undefined ? { received: extra.received } : {}),
|
|
371
|
+
passing: passingFor(event),
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
modOf(hook) {
|
|
375
|
+
return this.mods.find(mod => mod.ref === hook.mod) ?? [...this.pending].find(mod => mod.ref === hook.mod);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* A mod's `$` call: the event of its name, raised by that mod; the calling
|
|
379
|
+
* hook (or, outside hooks, the mod) is skipped by everything it raises.
|
|
380
|
+
*/
|
|
381
|
+
callOp(mod, frame, spec, args, signal) {
|
|
382
|
+
const parent = this.context.getStore();
|
|
383
|
+
const callers = new Set(parent?.callers ?? []);
|
|
384
|
+
const outside = new Set(parent?.outside ?? []);
|
|
385
|
+
if (frame !== undefined && frame.active)
|
|
386
|
+
callers.add(frame.hook.id);
|
|
387
|
+
else
|
|
388
|
+
outside.add(mod.ref.name);
|
|
389
|
+
const render = frame?.render ?? parent?.render;
|
|
390
|
+
const context = { callers, outside, ...(render !== undefined ? { render } : {}) };
|
|
391
|
+
const input = filled(spec.event, spec.input(args), mod);
|
|
392
|
+
const origin = { plugin: mod.ref.name, tier: mod.ref.tier };
|
|
393
|
+
const resume = frame?.active === true ? frame.pause() : () => { };
|
|
394
|
+
const run = this.context.run(context, async () => {
|
|
395
|
+
const result = await dispatch({
|
|
396
|
+
event: spec.event,
|
|
397
|
+
input,
|
|
398
|
+
origin,
|
|
399
|
+
hooks: this.selected(spec.event),
|
|
400
|
+
bottom: async (e, bottomSignal) => this.host.core(spec.event, e, { origin, mod, signal: bottomSignal }),
|
|
401
|
+
api: hookFrame => this.api(this.modOf(hookFrame.hook), hookFrame),
|
|
402
|
+
applies: this.applies(spec.event),
|
|
403
|
+
reentry: hook => (callers.has(hook.id) || outside.has(hook.mod.name)),
|
|
404
|
+
passing: passingFor(spec.event),
|
|
405
|
+
validate: (value, called) => (spec.kind === 'event' ? validateEvent(spec.event, value, called) : valueOrDeny(value)),
|
|
406
|
+
report: line => { this.host.report(line); },
|
|
407
|
+
signal: signal ?? frame?.signal ?? new AbortController().signal,
|
|
408
|
+
budgetMs: this.options.budgetMs ?? HOOK_BUDGET_MS,
|
|
409
|
+
catchMs: this.options.catchMs ?? CATCH_BUDGET_MS,
|
|
410
|
+
});
|
|
411
|
+
if (spec.kind === 'event')
|
|
412
|
+
return result;
|
|
413
|
+
if (isRecord(result) && typeof result['deny'] === 'string')
|
|
414
|
+
throw hooksError(mod, `${mod.ref.name}: $.${spec.event}: ${result['deny']}`);
|
|
415
|
+
if (!isRecord(result) || !('value' in result))
|
|
416
|
+
throw hooksError(mod, `${mod.ref.name}: $.${spec.event}: returned neither { value } nor { deny }`);
|
|
417
|
+
return result['value'];
|
|
418
|
+
});
|
|
419
|
+
return run.catch((error) => { throw spec.kind === 'event' ? error : opError(mod, spec.event, error); }).finally(resume);
|
|
420
|
+
}
|
|
421
|
+
/** A plugin noun's method: its event through the hooks, the owner's function as core. */
|
|
422
|
+
callNoun(mod, frame, noun, method, fn, args) {
|
|
423
|
+
const spec = { event: `${noun}.${method}`, kind: 'value', input: () => ({}) };
|
|
424
|
+
const parent = this.context.getStore();
|
|
425
|
+
const callers = new Set(parent?.callers ?? []);
|
|
426
|
+
const outside = new Set(parent?.outside ?? []);
|
|
427
|
+
if (frame !== undefined && frame.active)
|
|
428
|
+
callers.add(frame.hook.id);
|
|
429
|
+
else
|
|
430
|
+
outside.add(mod.ref.name);
|
|
431
|
+
const origin = { plugin: mod.ref.name, tier: mod.ref.tier };
|
|
432
|
+
const resume = frame?.active === true ? frame.pause() : () => { };
|
|
433
|
+
const input = args.length === 0 ? {} : args[0];
|
|
434
|
+
return this.context.run({ callers, outside }, async () => {
|
|
435
|
+
const result = await dispatch({
|
|
436
|
+
event: spec.event,
|
|
437
|
+
input,
|
|
438
|
+
origin,
|
|
439
|
+
hooks: this.selected(spec.event),
|
|
440
|
+
bottom: async (e) => ({ value: await fn(...(args.length === 0 ? [] : [e, ...args.slice(1)])) }),
|
|
441
|
+
api: hookFrame => this.api(this.modOf(hookFrame.hook), hookFrame),
|
|
442
|
+
applies: this.applies(spec.event),
|
|
443
|
+
reentry: hook => (callers.has(hook.id) || outside.has(hook.mod.name)),
|
|
444
|
+
validate: value => valueOrDeny(value),
|
|
445
|
+
report: line => { this.host.report(line); },
|
|
446
|
+
budgetMs: this.options.budgetMs ?? HOOK_BUDGET_MS,
|
|
447
|
+
catchMs: this.options.catchMs ?? CATCH_BUDGET_MS,
|
|
448
|
+
});
|
|
449
|
+
if (isRecord(result) && typeof result['deny'] === 'string')
|
|
450
|
+
throw hooksError(mod, `${mod.ref.name}: $.${spec.event}: ${result['deny']}`);
|
|
451
|
+
return isRecord(result) ? result['value'] : undefined;
|
|
452
|
+
}).catch((error) => { throw opError(mod, spec.event, error); }).finally(resume);
|
|
453
|
+
}
|
|
454
|
+
/** Build the `$` a hook run (or the mod's code outside hooks) receives. */
|
|
455
|
+
api(mod, hookFrame) {
|
|
456
|
+
if (hookFrame !== undefined)
|
|
457
|
+
this.host.ran?.(mod.ref.name, hookFrame.event);
|
|
458
|
+
const frame = hookFrame === undefined ? undefined : liveFrame(hookFrame, this.context.getStore()?.render ?? renderFrameOf(mod, hookFrame));
|
|
459
|
+
const engine = this;
|
|
460
|
+
const nouns = {};
|
|
461
|
+
for (const [name, spec] of Object.entries(OPS)) {
|
|
462
|
+
const [noun, method] = name.split('.');
|
|
463
|
+
nouns[noun] ??= {};
|
|
464
|
+
nouns[noun][method] = spec.kind === 'fire'
|
|
465
|
+
? (...args) => { void engine.callOp(mod, frame, spec, args).catch((error) => { engine.host.report(`${mod.ref.name}: $.${name}: ${messageOf(error)}`); }); }
|
|
466
|
+
: (...args) => engine.callOp(mod, frame, spec, args, signalOption(name, args));
|
|
467
|
+
}
|
|
468
|
+
nouns['clock']['after'] = (ms, fn) => engine.timer(mod, frame, 'clock.after', ms, fn, false);
|
|
469
|
+
nouns['clock']['every'] = (ms, fn) => engine.timer(mod, frame, 'clock.every', ms, fn, true);
|
|
470
|
+
nouns['ui']['resolve'] = (e) => engine.resolveElements(e, mod.ref.name);
|
|
471
|
+
nouns['ui']['ask'] = (question, options) => engine.ask(mod, frame, question, options);
|
|
472
|
+
nouns['state'] = {
|
|
473
|
+
get: (atom) => engine.stateGet(atom, frame),
|
|
474
|
+
set: (atom, value) => engine.stateSet(atom, value),
|
|
475
|
+
};
|
|
476
|
+
// The engine's own events a plugin raises with their own results.
|
|
477
|
+
for (const event of EVENT_RESULTS) {
|
|
478
|
+
const [noun, method] = event.split('.');
|
|
479
|
+
nouns[noun] ??= {};
|
|
480
|
+
nouns[noun][method] ??= (input) => engine.callOp(mod, frame, { event, kind: 'event', input: () => (isRecord(input) ? { ...input } : {}) }, [input]);
|
|
481
|
+
}
|
|
482
|
+
for (const [noun, methods] of Object.entries(this.nouns)) {
|
|
483
|
+
const table = {};
|
|
484
|
+
for (const [method, fn] of Object.entries(methods)) {
|
|
485
|
+
table[method] = typeof fn === 'function'
|
|
486
|
+
? (...args) => engine.callNoun(mod, frame, noun, method, fn, args)
|
|
487
|
+
: fn;
|
|
488
|
+
}
|
|
489
|
+
nouns[noun] = table;
|
|
490
|
+
}
|
|
491
|
+
const $ = { plugin: Object.freeze({ name: mod.ref.name, root: mod.definition.root ?? '' }) };
|
|
492
|
+
for (const [noun, table] of Object.entries(nouns))
|
|
493
|
+
$[noun] = Object.freeze(table);
|
|
494
|
+
return Object.freeze($);
|
|
495
|
+
}
|
|
496
|
+
resolveElements(e, plugin) {
|
|
497
|
+
const surface = isRecord(e) && typeof e['surface'] === 'string' ? e['surface'] : 'terminal';
|
|
498
|
+
const component = isRecord(e) && typeof e['component'] === 'string' ? e['component'] : 'Pane';
|
|
499
|
+
return this.host.elements?.(surface, component, plugin) ?? Object.freeze({});
|
|
500
|
+
}
|
|
501
|
+
/** `$.ui.ask`: a `tool.call` of AskUserQuestion; resolves to the label chosen. */
|
|
502
|
+
async ask(mod, frame, question, options) {
|
|
503
|
+
const labels = Array.isArray(options) ? options : isRecord(options) && Array.isArray(options['options']) ? options['options'] : [];
|
|
504
|
+
const header = isRecord(options) && typeof options['header'] === 'string' ? options['header'] : undefined;
|
|
505
|
+
const multiSelect = isRecord(options) && options['multiSelect'] === true;
|
|
506
|
+
const input = {
|
|
507
|
+
tool: 'AskUserQuestion',
|
|
508
|
+
questions: [{ question, ...(header !== undefined ? { header } : {}), options: labels.map(label => ({ label: String(label), description: '' })), multiSelect }],
|
|
509
|
+
};
|
|
510
|
+
const result = await this.callOp(mod, frame, { event: 'tool.call', kind: 'event', input: () => input }, [input]);
|
|
511
|
+
if (!isRecord(result))
|
|
512
|
+
throw new Error(`${mod.ref.name}: $.ui.ask: no answer`);
|
|
513
|
+
if (typeof result['deny'] === 'string')
|
|
514
|
+
throw new Error(`${mod.ref.name}: $.ui.ask: ${result['deny']}`);
|
|
515
|
+
const answers = isRecord(result['result']) && isRecord(result['result']['answers']) ? result['result']['answers'] : undefined;
|
|
516
|
+
const answer = answers?.[question];
|
|
517
|
+
if (typeof answer !== 'string')
|
|
518
|
+
throw new Error(`${mod.ref.name}: $.ui.ask: the question was dismissed`);
|
|
519
|
+
return answer;
|
|
520
|
+
}
|
|
521
|
+
timer(mod, frame, event, ms, fn, repeat) {
|
|
522
|
+
const controller = new AbortController();
|
|
523
|
+
const timer = Object.freeze({ cancel: () => { controller.abort(); mod.timers.delete(timer); } });
|
|
524
|
+
mod.timers.add(timer);
|
|
525
|
+
const outside = { callers: new Set(), outside: new Set([mod.ref.name]) };
|
|
526
|
+
const spec = { event, kind: 'value', input: () => ({ ms: Math.max(repeat ? 1 : 0, Number(ms) || 0) }) };
|
|
527
|
+
void (async () => {
|
|
528
|
+
do {
|
|
529
|
+
try {
|
|
530
|
+
await this.callOp(mod, frame?.active === true ? undefined : frame, spec, [ms], controller.signal);
|
|
531
|
+
}
|
|
532
|
+
catch (error) {
|
|
533
|
+
if (!controller.signal.aborted)
|
|
534
|
+
this.host.report(`${mod.ref.name}: $.${event}: ${messageOf(error)}`);
|
|
535
|
+
break;
|
|
536
|
+
}
|
|
537
|
+
if (controller.signal.aborted)
|
|
538
|
+
break;
|
|
539
|
+
try {
|
|
540
|
+
const out = this.context.run(outside, fn);
|
|
541
|
+
if (isThenable(out))
|
|
542
|
+
await out;
|
|
543
|
+
}
|
|
544
|
+
catch (error) {
|
|
545
|
+
this.host.report(`${mod.ref.name}: a ${event} callback threw ${errorLine(error)}`);
|
|
546
|
+
}
|
|
547
|
+
} while (repeat && !controller.signal.aborted);
|
|
548
|
+
mod.timers.delete(timer);
|
|
549
|
+
})();
|
|
550
|
+
return timer;
|
|
551
|
+
}
|
|
552
|
+
stateGet(atom, frame) {
|
|
553
|
+
const key = stateKey(atom);
|
|
554
|
+
const render = frame?.render ?? this.context.getStore()?.render;
|
|
555
|
+
if (render !== undefined)
|
|
556
|
+
this.host.stateRead?.(key, render);
|
|
557
|
+
return Promise.resolve(this.state.get(key));
|
|
558
|
+
}
|
|
559
|
+
stateSet(atom, value) {
|
|
560
|
+
const key = stateKey(atom);
|
|
561
|
+
this.state.set(key, frozenCopy(value));
|
|
562
|
+
this.host.stateWritten?.(key);
|
|
563
|
+
return Promise.resolve();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
const EMPTY_API = Object.freeze({});
|
|
567
|
+
function liveFrame(frame, render) {
|
|
568
|
+
return Object.create(frame, render === undefined ? {} : { render: { value: render } });
|
|
569
|
+
}
|
|
570
|
+
function renderFrameOf(mod, frame) {
|
|
571
|
+
if (frame.event !== 'ui.render')
|
|
572
|
+
return undefined;
|
|
573
|
+
return { mod: mod.ref.name };
|
|
574
|
+
}
|
|
575
|
+
function stateKey(atom) {
|
|
576
|
+
if (isRecord(atom) && typeof atom['plugin'] === 'string' && typeof atom['key'] === 'string')
|
|
577
|
+
return `${atom['plugin']}\u0000${atom['key']}`;
|
|
578
|
+
throw new Error('$.state takes an atom ({ plugin, key })');
|
|
579
|
+
}
|
|
580
|
+
function signalOption(name, args) {
|
|
581
|
+
if (name !== 'clock.sleep')
|
|
582
|
+
return undefined;
|
|
583
|
+
const options = args[1];
|
|
584
|
+
return isRecord(options) && typeof options['signal'] === 'object' ? options['signal'] : undefined;
|
|
585
|
+
}
|
|
586
|
+
/** How the engine frames each instruction file's kind in the `claudeMd` block. */
|
|
587
|
+
const KIND_NOTES = {
|
|
588
|
+
managed: ' (managed policy instructions, set by your organization)',
|
|
589
|
+
user: " (user's private global instructions for all projects)",
|
|
590
|
+
project: ' (project instructions, checked into the codebase)',
|
|
591
|
+
local: " (user's private project instructions, not checked in)",
|
|
592
|
+
memory: " (user's auto-memory, persists across conversations)",
|
|
593
|
+
};
|
|
594
|
+
const CLAUDE_MD_PREAMBLE = 'Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.';
|
|
595
|
+
/** The `claudeMd` block text for a list of instruction files, framed as the engine frames them. */
|
|
596
|
+
export function claudeMdText(files) {
|
|
597
|
+
const frames = files.filter(isRecord).map(file => `Contents of ${String(file['path'])}${KIND_NOTES[String(file['kind'])] ?? ''}:\n\n${String(file['content'] ?? '')}`);
|
|
598
|
+
return frames.length === 0 ? '' : `${CLAUDE_MD_PREAMBLE}\n\n${frames.join('\n\n')}`;
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* `prompt.context` keeps the `claudeMd` text and its files in step at every
|
|
602
|
+
* link: a changed list renders the text the next reader gets; a rewritten
|
|
603
|
+
* text makes the files unknown from there on.
|
|
604
|
+
*/
|
|
605
|
+
function keepContextInStep(received, passed) {
|
|
606
|
+
if (!isRecord(received) || !isRecord(passed) || !Array.isArray(passed['blocks']))
|
|
607
|
+
return passed;
|
|
608
|
+
const textOf = (e) => (Array.isArray(e['blocks']) ? e['blocks'].find(block => isRecord(block) && block['name'] === 'claudeMd') : undefined);
|
|
609
|
+
const before = received['instructionFiles'];
|
|
610
|
+
const after = passed['instructionFiles'];
|
|
611
|
+
if (Array.isArray(after) && JSON.stringify(after) !== JSON.stringify(before)) {
|
|
612
|
+
const text = claudeMdText(after);
|
|
613
|
+
const blocks = passed['blocks'];
|
|
614
|
+
const at = blocks.findIndex(block => isRecord(block) && block['name'] === 'claudeMd');
|
|
615
|
+
const next = at === -1 ? (text.length > 0 ? [{ name: 'claudeMd', text }, ...blocks] : blocks) : blocks.map((block, index) => (index === at ? { ...block, text } : block));
|
|
616
|
+
return { ...passed, blocks: next };
|
|
617
|
+
}
|
|
618
|
+
const oldBlock = textOf(received);
|
|
619
|
+
const newBlock = textOf(passed);
|
|
620
|
+
if (JSON.stringify(oldBlock) !== JSON.stringify(newBlock) && JSON.stringify(after) === JSON.stringify(before)) {
|
|
621
|
+
const { instructionFiles: _unknown, ...rest } = passed;
|
|
622
|
+
return rest;
|
|
623
|
+
}
|
|
624
|
+
return passed;
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Fields an event pins (claude-code.d.ts "Pinned"): a hook passing a
|
|
628
|
+
* different value to `next` is refused; one left out is put back.
|
|
629
|
+
* `except` pins every field but those.
|
|
630
|
+
*/
|
|
631
|
+
const PINNED = {
|
|
632
|
+
'tool.call': ['tool', 'tool_use_id', 'agentId'],
|
|
633
|
+
'tool.check': ['tool', 'input', 'tool_use_id', 'agentId'],
|
|
634
|
+
'tool.describe': ['provider'],
|
|
635
|
+
'agent.offer': ['provider'],
|
|
636
|
+
'agent.spawn': ['tool_use_id', 'provider', 'parentModel', 'parentAgentId', 'permissionMode', 'fork', 'name'],
|
|
637
|
+
'command.describe': ['provider'],
|
|
638
|
+
'command.run': ['presentation'],
|
|
639
|
+
'config.describe': ['key', 'provider'],
|
|
640
|
+
'config.set': ['key', 'previous', 'provider', 'origin'],
|
|
641
|
+
'env.get': ['name'],
|
|
642
|
+
'env.set': ['name'],
|
|
643
|
+
'ui.open': ['id'],
|
|
644
|
+
'ui.close': ['id', 'origin'],
|
|
645
|
+
'plugin.register': { except: [] },
|
|
646
|
+
'prompt.attachment': ['type', 'origin', 'agentId', 'kind'],
|
|
647
|
+
'prompt.compose': ['model'],
|
|
648
|
+
'prompt.edit': ['origin', 'key'],
|
|
649
|
+
'prompt.fill': ['origin'],
|
|
650
|
+
'prompt.suggest': ['origin'],
|
|
651
|
+
'session.append': ['door', 'origin', 'uuid', 'agentId'],
|
|
652
|
+
'session.compact': ['trigger', 'agentId'],
|
|
653
|
+
'turn.complete': ['agentId'],
|
|
654
|
+
'turn.step': ['turnId', 'index', 'messageCount', 'agentId'],
|
|
655
|
+
'ui.focus': { except: ['element'] },
|
|
656
|
+
'ui.scroll': { except: ['offset'] },
|
|
657
|
+
'skill.prompt': { except: ['text', 'frontmatter'] },
|
|
658
|
+
};
|
|
659
|
+
/** What a hook's `next(e)` passes on: pinned fields held, `prompt.context` kept in step. */
|
|
660
|
+
function passingFor(event) {
|
|
661
|
+
const pinned = PINNED[event];
|
|
662
|
+
const context = event === 'prompt.context';
|
|
663
|
+
if (pinned === undefined && !context)
|
|
664
|
+
return undefined;
|
|
665
|
+
return (received, passed) => {
|
|
666
|
+
let out = passed;
|
|
667
|
+
if (pinned !== undefined && isRecord(received) && isRecord(passed)) {
|
|
668
|
+
const fields = Array.isArray(pinned) ? pinned : Object.keys(received).filter(key => !pinned.except.includes(key));
|
|
669
|
+
const restored = { ...passed };
|
|
670
|
+
for (const field of fields) {
|
|
671
|
+
if (!(field in received))
|
|
672
|
+
continue;
|
|
673
|
+
if (!(field in passed) || passed[field] === undefined) {
|
|
674
|
+
restored[field] = received[field];
|
|
675
|
+
continue;
|
|
676
|
+
}
|
|
677
|
+
if (JSON.stringify(passed[field]) !== JSON.stringify(received[field]))
|
|
678
|
+
throw new Error(`${event}: ${field} is pinned; a rewrite is refused`);
|
|
679
|
+
}
|
|
680
|
+
out = restored;
|
|
681
|
+
}
|
|
682
|
+
return context ? keepContextInStep(received, out) : out;
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
let callIds = 0;
|
|
686
|
+
/** What the engine fills in a plugin's call: a note's door, origin and id; a tool call's id. */
|
|
687
|
+
function filled(event, input, mod) {
|
|
688
|
+
if (event === 'session.append') {
|
|
689
|
+
const message = isRecord(input['message']) ? input['message'] : {};
|
|
690
|
+
return {
|
|
691
|
+
...input,
|
|
692
|
+
message: { ...message, ...(message['type'] === 'user' ? { role: 'user', isMeta: true } : {}) },
|
|
693
|
+
door: 'note',
|
|
694
|
+
origin: { kind: 'plugin', plugin: mod.ref.name },
|
|
695
|
+
uuid: crypto.randomUUID(),
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
if (event === 'tool.call' && input['tool_use_id'] === undefined)
|
|
699
|
+
return { ...input, tool_use_id: `toolu_mod_${String(++callIds)}` };
|
|
700
|
+
return input;
|
|
701
|
+
}
|