@matatbread/matbot-plugin-api 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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Mat Woolf
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # @matatbread/matbot-plugin-api
2
+
3
+ The plugin API for [matbot](https://github.com/MatAtBread/matbot) — a thin, composable
4
+ TypeScript AI harness.
5
+
6
+ This is the **singleton contract** every matbot plugin builds against: the `MatbotPlugin`
7
+ type, the `MatbotServices`/`MatbotRuntime`/`MatbotMachine` registry, the hook channels, the
8
+ ambient principal carrier, the `Vault`/`Store` interfaces, and the shared error types.
9
+
10
+ Plugins should declare it as a **peer dependency** (the host provides the single shared copy
11
+ — two copies would break `instanceof` checks, the principal carrier, and module
12
+ augmentation). It ships as raw TypeScript and requires **Node 24+** (native type stripping)
13
+ or a bundler.
14
+
15
+ See the [main repository](https://github.com/MatAtBread/matbot) for the full design guide and
16
+ plugin-authoring docs.
17
+
18
+ ## License
19
+
20
+ Apache-2.0
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@matatbread/matbot-plugin-api",
3
+ "matbotRuntime": [
4
+ "node",
5
+ "browser"
6
+ ],
7
+ "version": "0.1.0",
8
+ "engines": {
9
+ "node": ">=24.0.0"
10
+ },
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "description": "matbot plugin API: the singleton contract every matbot plugin builds against — MatbotPlugin, the service registry, hooks, principal carrier, and shared types.",
15
+ "license": "Apache-2.0",
16
+ "type": "module",
17
+ "exports": {
18
+ ".": "./src/index.ts"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/MatAtBread/matbot.git",
23
+ "directory": "plugin-api"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "devDependencies": {
29
+ "typescript": "^5.8.0"
30
+ },
31
+ "scripts": {
32
+ "typecheck": "tsc --noEmit"
33
+ }
34
+ }
@@ -0,0 +1,73 @@
1
+ // A minimal multi-subscriber fan-out for AsyncIterable observation streams (tool/plugin/skill watch,
2
+ // and any future plugin-owned CRUD stream). Each subscriber gets its own unbounded queue, so a slow
3
+ // consumer never blocks emit() or its peers. Acceptable because these events are rare and small
4
+ // (registry/document CRUD); this is not a high-throughput data path. emit() is synchronous and never throws.
5
+
6
+ interface Subscriber<T> {
7
+ queue: T[];
8
+ wake: (() => void) | undefined;
9
+ done: boolean;
10
+ }
11
+
12
+ // The consumer facet — what a stream hands out. `emit` is the producer's, kept off this so a
13
+ // surface that only exposes observation (e.g. services.mounted) cannot forge events.
14
+ export interface Subscribable<T> {
15
+ subscribe(signal?: AbortSignal): AsyncIterable<T>;
16
+ // Detached observation loop: awaits each handler before pulling the next (no overlapping runs),
17
+ // isolates a throwing handler (logged, never propagated — a bad observer must not kill the stream),
18
+ // and ends when the source ends or `signal` aborts. The fire-and-forget form of the for-await loop
19
+ // every watch call site otherwise hand-writes.
20
+ consume(handler: (value: T) => void | Promise<void>, signal?: AbortSignal): void;
21
+ }
22
+
23
+ export interface Broadcaster<T> extends Subscribable<T> {
24
+ emit(value: T): void;
25
+ }
26
+
27
+ /**
28
+ * Wrap a bare subscribe generator into a full {@link Subscribable}, supplying the standard detached
29
+ * `consume` loop. Use for a *derived* stream — e.g. a per-plugin scoped view of a shared broadcaster —
30
+ * that owns its own subscribe generator but wants the same consume ergonomics as a real broadcaster.
31
+ */
32
+ export function subscribable<T>(subscribe: (signal?: AbortSignal) => AsyncIterable<T>): Subscribable<T> {
33
+ const consume = (handler: (value: T) => void | Promise<void>, signal?: AbortSignal): void => {
34
+ void (async () => {
35
+ for await (const v of subscribe(signal)) {
36
+ try { await handler(v); }
37
+ catch (e) { console.error('[matbot] consume handler threw:', e instanceof Error ? e.message : e); }
38
+ }
39
+ })();
40
+ };
41
+ return { subscribe, consume };
42
+ }
43
+
44
+ export function createBroadcaster<T>(): Broadcaster<T> {
45
+ const subs = new Set<Subscriber<T>>();
46
+
47
+ const emit = (value: T): void => {
48
+ for (const sub of subs) {
49
+ sub.queue.push(value);
50
+ sub.wake?.();
51
+ }
52
+ };
53
+
54
+ async function* subscribe(signal?: AbortSignal): AsyncIterable<T> {
55
+ const sub: Subscriber<T> = { queue: [], wake: undefined, done: false };
56
+ subs.add(sub);
57
+ const onAbort = () => { sub.done = true; sub.wake?.(); };
58
+ signal?.addEventListener('abort', onAbort, { once: true });
59
+ try {
60
+ while (true) {
61
+ while (sub.queue.length > 0) yield sub.queue.shift()!;
62
+ if (sub.done || signal?.aborted) return;
63
+ await new Promise<void>(resolve => { sub.wake = resolve; });
64
+ sub.wake = undefined;
65
+ }
66
+ } finally {
67
+ subs.delete(sub);
68
+ signal?.removeEventListener('abort', onAbort);
69
+ }
70
+ }
71
+
72
+ return { emit, ...subscribable(subscribe) };
73
+ }
@@ -0,0 +1,73 @@
1
+ import type { Principal } from './types.js';
2
+ import { runAs } from './principal-context.js';
3
+
4
+ /**
5
+ * A context switch is the machine analogue of an OS one: it pages in any pending machine state and
6
+ * sets the owner. {@link runAs} is the bare "set the owner" instruction (the principal carrier);
7
+ * {@link contextSwitch} is the scheduler operation layered on top — it also lands any machine
8
+ * mutation that was deferred while the machine was busy.
9
+ *
10
+ * Why deferral exists: a service like the `StorageBackend` is the system of record, and swapping it
11
+ * under a running operation would split a compare-and-swap (or a turn) across two backends. So a
12
+ * swap is queued and applied only at the *quiescent edge* — the instant no context is active — which
13
+ * is exactly a context-switch boundary. The principal carrier stays a pure identity primitive; this
14
+ * module owns the machine-update half, so the two concerns share call sites without sharing code.
15
+ *
16
+ * The host registers what to flush ({@link onContextQuiesce}); the three entry points (a web
17
+ * request, a telegram message, a turn) switch context through {@link contextSwitch} instead of
18
+ * calling {@link runAs} directly. The boot principal (an `enter`, not a `run`) is the depth-0
19
+ * baseline and is never counted.
20
+ */
21
+
22
+ const quiescers = new Set<() => void>();
23
+ let depth = 0;
24
+ let flushing = false;
25
+
26
+ /**
27
+ * Register a machine-update flush, run at every quiescent edge (no context active). Flushers MUST be
28
+ * idempotent: a no-op when nothing is pending, since the edge is reached after every operation.
29
+ * Returns an unregister fn. A throwing flusher is isolated — one must not block the others or escape
30
+ * into the operation that triggered the edge.
31
+ */
32
+ export function onContextQuiesce(flush: () => void): () => void {
33
+ quiescers.add(flush);
34
+ return () => { quiescers.delete(flush); };
35
+ }
36
+
37
+ /**
38
+ * Run the registered flushers iff no context is currently active — the quiescent edge. Called by
39
+ * {@link contextSwitch} at both edges, and by the host right after it *queues* a deferred mutation:
40
+ * queued while busy (depth > 0) this no-ops and the exit edge lands it; queued while idle (depth 0)
41
+ * it applies immediately, so an idle-time swap doesn't wait for the next request to take effect.
42
+ */
43
+ export function flushIfQuiescent(): void {
44
+ if (depth !== 0 || flushing) return;
45
+ flushing = true;
46
+ try {
47
+ for (const q of quiescers) {
48
+ try { q(); }
49
+ catch (e) { console.error('[matbot] context-quiesce flush threw:', e instanceof Error ? e.message : e); }
50
+ }
51
+ } finally {
52
+ flushing = false;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Switch into the machine as `principal`: land any pending machine mutation (only safe while idle),
58
+ * then run `fn` under the principal. Mirrors {@link runAs}'s sync/async return — when `fn` is async,
59
+ * the context stays open until its promise settles, so the depth count tracks the real operation.
60
+ */
61
+ export function contextSwitch<T>(principal: Principal, fn: () => T): T {
62
+ flushIfQuiescent();
63
+ depth++;
64
+ const settle = (): void => { depth--; flushIfQuiescent(); };
65
+ let result: T;
66
+ try {
67
+ result = runAs(principal, fn);
68
+ } catch (e) {
69
+ settle();
70
+ throw e;
71
+ }
72
+ return result instanceof Promise ? (result.finally(settle) as T) : (settle(), result);
73
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Thrown by Vault.resolve() when one or more ${NAME} placeholders cannot be resolved.
3
+ * `missingKeys` carries the unresolved key names (e.g. `ANTHROPIC_API_KEY`) so callers
4
+ * can prompt for and store them.
5
+ */
6
+ export class MissingSecretError extends Error {
7
+ readonly missingKeys: readonly string[];
8
+
9
+ constructor(missingKeys: readonly string[]) {
10
+ super(`Vault: secret(s) not found: ${missingKeys.join(', ')}`);
11
+ this.name = 'MissingSecretError';
12
+ this.missingKeys = missingKeys;
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Thrown by the loader when an explicit, single, user-initiated load (the `plugin`/`provider`
18
+ * tools via `services.loadPlugin`) targets a plugin whose `matbotRuntime` excludes this host.
19
+ * Unlike a setup() failure — which may be transient (a missing secret) and is left in config to
20
+ * fix — this is permanent for the host, so the `add` flow catches it specifically and rolls the
21
+ * specifier back out of matbot.yaml rather than persisting a plugin that can never activate here.
22
+ */
23
+ export class IncompatibleRuntimeError extends Error {
24
+ readonly specifier: string;
25
+ readonly declared: readonly string[];
26
+ readonly hostRuntime: string;
27
+
28
+ constructor(specifier: string, declared: readonly string[], hostRuntime: string) {
29
+ super(`Cannot load plugin "${specifier}": declares matbotRuntime [${declared.join(', ')}], host runtime is "${hostRuntime}".`);
30
+ this.name = 'IncompatibleRuntimeError';
31
+ this.specifier = specifier;
32
+ this.declared = declared;
33
+ this.hostRuntime = hostRuntime;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Thrown by the loader when an explicit, single, user-initiated load targets a module that imports
39
+ * cleanly but is not plugin-shaped — no `plugin` export, a `plugin` without `apiVersion`, or a
40
+ * non-function lifecycle member. Like {@link IncompatibleRuntimeError} this is *permanent* for the
41
+ * specifier (the code is a library, not a plugin), so the `add` flow catches it specifically and
42
+ * rolls the specifier back out of matbot.yaml — distinct from a transient setup() failure (a missing
43
+ * secret), which is left in config to fix. `reason` is the precise shape defect for logs; callers
44
+ * surfacing this to an LLM should prefer a terminal "not a plugin" message over echoing `reason`,
45
+ * which is phrased as a code-fix instruction the model may try to act on.
46
+ */
47
+ export class NotAPluginError extends Error {
48
+ readonly specifier: string;
49
+ readonly reason: string;
50
+
51
+ constructor(specifier: string, reason: string) {
52
+ super(reason);
53
+ this.name = 'NotAPluginError';
54
+ this.specifier = specifier;
55
+ this.reason = reason;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Thrown by a `PromptFn` implementation when the user cancels — the "give up" path, not a graceful
61
+ * decline. Callers awaiting `ctx.prompt()` need not branch on it: the surrounding try/catch turns
62
+ * it into a tool error that closes the tool call, while the host separately abandons the turn.
63
+ */
64
+ export class PromptCancelledError extends Error {
65
+ constructor(message = 'User cancelled — cannot proceed.') {
66
+ super(message);
67
+ this.name = 'PromptCancelledError';
68
+ }
69
+ }
package/src/hooks.ts ADDED
@@ -0,0 +1,185 @@
1
+ import type {
2
+ Hook, HookPoint, Message, MessageContent, Session,
3
+ ScreenContext, ContributeContext, ToolCallContext, ToolCallResult, ToolResultContext, FollowupContext,
4
+ } from './types.js';
5
+
6
+ const HOOK_ERROR_CREATOR = 'matbot-hooks';
7
+
8
+ export class HookRegistry {
9
+ private readonly hooks = new Map<HookPoint, Hook[]>();
10
+
11
+ // A hook handler that *throws* is a failure, not an intentional stop (which is a return value:
12
+ // `abort` / `rejectTool`). A throw must never propagate out of a run* method — that is what bricked
13
+ // the turn loop: one misconfigured screen hook (e.g. a provider with an unresolved secret) threw at
14
+ // the top of every turn, so the model never ran and the user couldn't even invoke a tool to fix it.
15
+ // So every handler call goes through `invoke`, which catches, logs, and treats the throw as "the
16
+ // hook returned nothing" (skipped). The failure is recorded once per hook (`markedFailures`) and
17
+ // drained into a marker by the next `runScreen`, so it degrades *visibly* rather than silently.
18
+ private readonly markedFailures = new Set<Hook>();
19
+ private pendingFailureMarkers: { channel: HookPoint; pluginName?: string; message: string }[] = [];
20
+
21
+ register(hook: Hook): void {
22
+ const list = this.hooks.get(hook.on) ?? [];
23
+ list.push(hook);
24
+ list.sort((a, b) => (a.priority ?? 50) - (b.priority ?? 50));
25
+ this.hooks.set(hook.on, list);
26
+ }
27
+
28
+ removeByPlugin(pluginName: string): void {
29
+ for (const [point, list] of this.hooks) {
30
+ this.hooks.set(point, list.filter(h => h.pluginName !== pluginName));
31
+ }
32
+ }
33
+
34
+ // Backing for the per-call `ctx.removeHook()`: drop one hook by identity. Filtering into a fresh
35
+ // array (rather than splicing) leaves any in-flight run loop — which iterates the array reference
36
+ // it captured before the mutation — to finish over the old list; the next run sees the new one.
37
+ // Idempotent: removing an already-absent hook is a no-op, so calling removeHook() twice is safe.
38
+ private removeOne(point: HookPoint, hook: Hook): void {
39
+ const list = this.hooks.get(point);
40
+ if (list) this.hooks.set(point, list.filter(h => h !== hook));
41
+ }
42
+
43
+ // Run one handler, isolating a throw: log it, record it for a one-time marker, and return undefined
44
+ // — which every run* method already treats as "no contribution from this hook".
45
+ private async invoke<R>(hook: Hook, run: () => R | Promise<R>): Promise<R | undefined> {
46
+ try {
47
+ return await run();
48
+ } catch (err) {
49
+ const message = err instanceof Error ? err.message : String(err);
50
+ const owner = hook.pluginName !== undefined ? ` from "${hook.pluginName}"` : '';
51
+ console.error(`[matbot] ${hook.on} hook${owner} threw; skipping it for this turn:`, message);
52
+ if (!this.markedFailures.has(hook)) {
53
+ this.markedFailures.add(hook);
54
+ this.pendingFailureMarkers.push({
55
+ channel: hook.on,
56
+ ...(hook.pluginName !== undefined ? { pluginName: hook.pluginName } : {}),
57
+ message,
58
+ });
59
+ }
60
+ return undefined;
61
+ }
62
+ }
63
+
64
+ // Append a `marker` message for each not-yet-marked hook failure (from any channel) to the session,
65
+ // then clear the queue. Called from runScreen — the once-per-turn, session-owning channel whose
66
+ // returned session the runner persists — so failures surface durably and exactly once. Returns the
67
+ // appended marker content blocks too, so the runner can carry them live (a session reload is the
68
+ // fallback path, not the only one).
69
+ private drainFailureMarkers(session: Session): { session: Session; markers: MessageContent[] } {
70
+ if (this.pendingFailureMarkers.length === 0) return { session, markers: [] };
71
+ const messages: Message[] = this.pendingFailureMarkers.map(f => ({
72
+ id: crypto.randomUUID(),
73
+ role: 'marker',
74
+ createdAt: new Date().toISOString(),
75
+ traceId: '',
76
+ content: [{
77
+ type: 'marker',
78
+ creator: HOOK_ERROR_CREATOR,
79
+ data: { channel: f.channel, ...(f.pluginName !== undefined ? { pluginName: f.pluginName } : {}), message: f.message },
80
+ }],
81
+ }));
82
+ this.pendingFailureMarkers = [];
83
+ return {
84
+ session: { ...session, messages: [...session.messages, ...messages] },
85
+ markers: messages.flatMap(m => m.content),
86
+ };
87
+ }
88
+
89
+ // screen folds across hooks: each sees the session as shaped so far, accumulates ephemeral, and
90
+ // the first `abort` short-circuits (the partial session is returned so the caller can persist it).
91
+ async runScreen(ctx: Omit<ScreenContext, 'removeHook'>): Promise<{ session: Session; ephemeral: MessageContent[]; durable: MessageContent[]; markers: MessageContent[]; abort?: string }> {
92
+ let session = ctx.session;
93
+ const ephemeral: MessageContent[] = [];
94
+ // Handler-returned markers: appended to the session here (so they persist) and accumulated so the
95
+ // runner can also emit them live — keeping a live draw and a reload identical.
96
+ const handlerMarkers: MessageContent[] = [];
97
+ const appendMarkers = (blocks: MessageContent[]): void => {
98
+ handlerMarkers.push(...blocks);
99
+ session = { ...session, messages: [...session.messages, {
100
+ id: crypto.randomUUID(), role: 'marker', createdAt: new Date().toISOString(), traceId: '', content: blocks,
101
+ }] };
102
+ };
103
+ // Handler-returned durable context: folded onto the running turn's user message (the last one
104
+ // with role 'user'), so it persists into history AND rides every subsequent provider call — the
105
+ // persisted twin of `ephemeral`. Accumulated too, so the runner emits it live as a `robo-user`
106
+ // event (keeping live draw and reload identical). No user message ⇒ nothing to fold onto, so the
107
+ // blocks are dropped rather than orphaned (a screen hook only runs when a turn is being submitted,
108
+ // so a user message is present in practice; this is defensive).
109
+ const durable: MessageContent[] = [];
110
+ const foldDurable = (blocks: MessageContent[]): void => {
111
+ const idx = session.messages.findLastIndex(m => m.role === 'user');
112
+ if (idx < 0) return;
113
+ durable.push(...blocks);
114
+ session = { ...session, messages: session.messages.map((m, i) =>
115
+ i === idx ? { ...m, content: [...m.content, ...blocks] } : m) };
116
+ };
117
+ for (const hook of this.hooks.get('screen') ?? []) {
118
+ if (hook.on !== 'screen') continue;
119
+ const r = await this.invoke(hook, () => hook.handler({ ...ctx, session, removeHook: () => this.removeOne('screen', hook) }));
120
+ if (!r) continue;
121
+ if (r.session) session = r.session;
122
+ if (r.ephemeral) ephemeral.push(...r.ephemeral);
123
+ if (r.durable && r.durable.length) foldDurable(r.durable);
124
+ if (r.markers && r.markers.length) appendMarkers(r.markers);
125
+ if (r.abort) {
126
+ const drained = this.drainFailureMarkers(session);
127
+ return { session: drained.session, ephemeral, durable, markers: [...handlerMarkers, ...drained.markers], abort: r.abort };
128
+ }
129
+ }
130
+ const drained = this.drainFailureMarkers(session);
131
+ return { session: drained.session, ephemeral, durable, markers: [...handlerMarkers, ...drained.markers] };
132
+ }
133
+
134
+ // contribute folds the outgoing array through each hook — a pure transform pipeline; the stored
135
+ // session is never touched.
136
+ async runContribute(ctx: Omit<ContributeContext, 'removeHook'>): Promise<Message[]> {
137
+ let outgoing = ctx.outgoing as Message[];
138
+ for (const hook of this.hooks.get('contribute') ?? []) {
139
+ if (hook.on !== 'contribute') continue;
140
+ const r = await this.invoke(hook, () => hook.handler({ ...ctx, outgoing, removeHook: () => this.removeOne('contribute', hook) }));
141
+ if (r) outgoing = r;
142
+ }
143
+ return outgoing;
144
+ }
145
+
146
+ // toolcall stops at the first hook that rejects or aborts; the rest don't run.
147
+ async runToolCall(ctx: Omit<ToolCallContext, 'removeHook'>): Promise<ToolCallResult> {
148
+ for (const hook of this.hooks.get('toolcall') ?? []) {
149
+ if (hook.on !== 'toolcall') continue;
150
+ const r = await this.invoke(hook, () => hook.handler({ ...ctx, removeHook: () => this.removeOne('toolcall', hook) }));
151
+ if (r && (r.rejectTool || r.abort)) return r;
152
+ }
153
+ return {};
154
+ }
155
+
156
+ // toolresult folds the tool result through each hook — a transform pipeline (redaction, truncation);
157
+ // a hook that returns nothing just observes (auditing). Returns the final result.
158
+ async runToolResult(ctx: Omit<ToolResultContext, 'removeHook'>): Promise<unknown> {
159
+ let result = ctx.result;
160
+ for (const hook of this.hooks.get('toolresult') ?? []) {
161
+ if (hook.on !== 'toolresult') continue;
162
+ const r = await this.invoke(hook, () => hook.handler({ ...ctx, result, removeHook: () => this.removeOne('toolresult', hook) }));
163
+ if (r) result = r.result;
164
+ }
165
+ return result;
166
+ }
167
+
168
+ // followup runs every hook and collects their resubmissions (each becomes its own head-enqueued
169
+ // turn), any durable markers (appended to the committed session by the pump), and any
170
+ // retract-and-rerun requests. A turn can be popped only once, so multiple hooks' retraction
171
+ // contexts merge into a single redo (in practice only one fires); `retract` is omitted when none did.
172
+ async runFollowup(ctx: Omit<FollowupContext, 'removeHook'>): Promise<{ resubmits: MessageContent[][]; markers: MessageContent[]; retract?: { context: MessageContent[] } }> {
173
+ const resubmits: MessageContent[][] = [];
174
+ const markers: MessageContent[] = [];
175
+ const retract: MessageContent[] = [];
176
+ for (const hook of this.hooks.get('followup') ?? []) {
177
+ if (hook.on !== 'followup') continue;
178
+ const r = await this.invoke(hook, () => hook.handler({ ...ctx, removeHook: () => this.removeOne('followup', hook) }));
179
+ if (r?.resubmit) resubmits.push(r.resubmit.content);
180
+ if (r?.retractAndRerun) retract.push(...r.retractAndRerun.context);
181
+ if (r?.markers) markers.push(...r.markers);
182
+ }
183
+ return { resubmits, markers, ...(retract.length > 0 ? { retract: { context: retract } } : {}) };
184
+ }
185
+ }
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ export type * from './types.js';
2
+ export { CONFIRM_YES, CONFIRM_NO } from './types.js';
3
+ export * from './store-query.js';
4
+ export * from './vault.js';
5
+ export * from './errors.js';
6
+ export * from './principal-context.js';
7
+ export * from './context-switch.js';
8
+ export * from './hooks.js';
9
+ export * from './plugin.js';
10
+ export * from './broadcast.js';