@rebon/cli-darwin-arm64 1.8.7 → 1.9.2

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 (43) hide show
  1. package/bin/compose-runtime/payload/compose/shims/dsh-environment.js +34 -0
  2. package/bin/compose-runtime/src/commands-runtime.mjs +72 -0
  3. package/bin/compose-runtime/src/loader.mjs +7 -0
  4. package/bin/compose-runtime/src/probe.mjs +77 -0
  5. package/bin/compose-runtime/src/provided-modules.json +38 -0
  6. package/bin/compose-runtime/src/realm.mjs +5 -3
  7. package/bin/compose-runtime/src/registry.mjs +15 -2
  8. package/bin/compose-runtime/src/resolve.mjs +3 -33
  9. package/bin/marketplace/.claude-plugin/marketplace.json +258 -0
  10. package/bin/marketplace/plugins/dsh-llm-deepseek/LICENSE +21 -0
  11. package/bin/marketplace/plugins/dsh-llm-deepseek/llm-deepseek.js +672 -0
  12. package/bin/marketplace/plugins/dsh-llm-deepseek/rebon-plugin.json +27 -0
  13. package/bin/marketplace/plugins/dsh-tool-todo/LICENSE +21 -0
  14. package/bin/marketplace/plugins/dsh-tool-todo/rebon-plugin.json +27 -0
  15. package/bin/marketplace/plugins/dsh-tool-todo/tool-todo.js +143 -0
  16. package/bin/marketplace/plugins/dsh-tool-web/LICENSE +21 -0
  17. package/bin/marketplace/plugins/dsh-tool-web/rebon-plugin.json +27 -0
  18. package/bin/marketplace/plugins/dsh-tool-web/tool-web.js +1527 -0
  19. package/bin/marketplace/plugins/dsh-web-search-exa/LICENSE +21 -0
  20. package/bin/marketplace/plugins/dsh-web-search-exa/rebon-plugin.json +27 -0
  21. package/bin/marketplace/plugins/dsh-web-search-exa/web-search-exa.js +122 -0
  22. package/bin/mods-runtime/package.json +13 -0
  23. package/bin/mods-runtime/src/chain.mjs +188 -0
  24. package/bin/mods-runtime/src/classic.mjs +217 -0
  25. package/bin/mods-runtime/src/claude-code.mjs +101 -0
  26. package/bin/mods-runtime/src/client.mjs +316 -0
  27. package/bin/mods-runtime/src/engine.mjs +196 -0
  28. package/bin/mods-runtime/src/index.mjs +58 -0
  29. package/bin/mods-runtime/src/jsx-transform.mjs +324 -0
  30. package/bin/mods-runtime/src/mod.mjs +370 -0
  31. package/bin/mods-runtime/src/render.mjs +122 -0
  32. package/bin/mods-runtime/src/transpile.mjs +167 -0
  33. package/bin/plugin-host/src/cli.mjs +13 -0
  34. package/bin/plugin-host/src/host.mjs +11 -1
  35. package/bin/plugin-host/src/methods.mjs +4 -1
  36. package/bin/plugin-host/src/protocol.mjs +38 -4
  37. package/bin/rebon +2 -2
  38. package/bin/rebon-boa-helper +0 -0
  39. package/bin/rebon-browser-mcp +0 -0
  40. package/bin/rebon-computer-use +0 -0
  41. package/bin/rebon-lsp-mcp +0 -0
  42. package/bin/sandbox-win +0 -0
  43. package/package.json +1 -1
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "dsh-web-search-exa",
3
+ "version": "0.1.0",
4
+ "description": "DeepSeek Harness Exa search backend for web_search (needs an Exa API key). Packaged from the DeepSeek Harness module Rebon vendors (@deepseek-ai/dsh-web-search-exa).",
5
+ "license": "MIT",
6
+ "capabilities": {
7
+ "kernelPlugins": {
8
+ "dsh-web-search-exa": {
9
+ "entry": "web-search-exa.js",
10
+ "services": [
11
+ "web:search:exa"
12
+ ],
13
+ "seats": [
14
+ "credentials"
15
+ ]
16
+ }
17
+ }
18
+ },
19
+ "metadata": {
20
+ "upstream": "@deepseek-ai/dsh-web-search-exa"
21
+ },
22
+ "container": {
23
+ "network": [
24
+ "api.exa.ai"
25
+ ]
26
+ }
27
+ }
@@ -0,0 +1,122 @@
1
+ // packages/web/web-search-exa/src/index.ts
2
+ import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
3
+ import z from "@deepseek-ai/schemastery";
4
+
5
+ // packages/web/web-search-exa/src/provider.ts
6
+ import { WebError } from "@deepseek-ai/dsh-web";
7
+ var EXA_PROVIDER_ID = "exa";
8
+ var EXA_DEFAULT_BASE_URL = "https://api.exa.ai";
9
+ var EXA_DEFAULT_SEARCH_TYPE = "auto";
10
+ var EXA_DEFAULT_HIGHLIGHTS_PER_RESULT = 1;
11
+ var USER_AGENT = "deepseek-harness/0.0.1";
12
+ function mapExaResult(result) {
13
+ const snippet = result.highlights?.find((highlight) => highlight.trim().length > 0);
14
+ if (snippet === void 0) return void 0;
15
+ return {
16
+ url: result.url,
17
+ ...result.title != null && result.title.length > 0 ? { title: result.title } : {},
18
+ snippet,
19
+ ...result.publishedDate != null && result.publishedDate.length > 0 ? { publishedAt: result.publishedDate } : {}
20
+ };
21
+ }
22
+ function mapExaResponse(response) {
23
+ const sources = (response.results ?? []).map(mapExaResult).filter((source) => source !== void 0);
24
+ return { sources, truncated: false };
25
+ }
26
+ var ExaSearchProvider = class {
27
+ constructor(options) {
28
+ this.options = options;
29
+ }
30
+ options;
31
+ id = EXA_PROVIDER_ID;
32
+ available() {
33
+ return this.options.apiKey.length > 0 && isValidBaseUrl(this.options.baseURL) && isPositiveInteger(this.options.highlightsPerResult) && (this.options.numResults === void 0 || isPositiveInteger(this.options.numResults));
34
+ }
35
+ async search(request, signal) {
36
+ const numResults = request.maxResults ?? this.options.numResults;
37
+ let response;
38
+ try {
39
+ response = await fetch(`${this.options.baseURL}/search`, {
40
+ method: "POST",
41
+ redirect: "error",
42
+ headers: {
43
+ "authorization": `Bearer ${this.options.apiKey}`,
44
+ "content-type": "application/json",
45
+ "accept": "application/json",
46
+ "user-agent": USER_AGENT
47
+ },
48
+ body: JSON.stringify({
49
+ query: request.query,
50
+ type: this.options.searchType,
51
+ contents: { highlights: { highlightsPerUrl: this.options.highlightsPerResult } },
52
+ ...numResults !== void 0 ? { numResults } : {}
53
+ }),
54
+ ...signal !== void 0 ? { signal } : {}
55
+ });
56
+ } catch (error) {
57
+ if (isAbortError(error)) throw new WebError("Exa search aborted", "WEB_ABORTED", { cause: error });
58
+ throw new WebError(`Exa search request failed: ${String(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
59
+ }
60
+ if (!response.ok) {
61
+ const status = response.status;
62
+ let message = `Exa API error (HTTP ${status})`;
63
+ try {
64
+ const parsed = await response.json();
65
+ const detail = parsed.error ?? parsed.message;
66
+ if (detail !== void 0 && detail.length > 0) message = detail;
67
+ } catch (error) {
68
+ if (isAbortError(error)) throw new WebError("Exa search aborted", "WEB_ABORTED", { cause: error });
69
+ }
70
+ throw new WebError(message, "WEB_PROVIDER_ERROR");
71
+ }
72
+ try {
73
+ const payload = await response.json();
74
+ return mapExaResponse(payload);
75
+ } catch (error) {
76
+ if (isAbortError(error)) throw new WebError("Exa search aborted", "WEB_ABORTED", { cause: error });
77
+ throw new WebError(`Exa returned an unprocessable response body: ${String(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
78
+ }
79
+ }
80
+ };
81
+ function isValidBaseUrl(baseURL) {
82
+ return URL.canParse(baseURL);
83
+ }
84
+ function isPositiveInteger(value) {
85
+ return Number.isInteger(value) && value > 0;
86
+ }
87
+ function isAbortError(error) {
88
+ return error instanceof DOMException && error.name === "AbortError";
89
+ }
90
+
91
+ // packages/web/web-search-exa/src/index.ts
92
+ var name = "web-search-exa";
93
+ var inject = ["web"];
94
+ var Config = z.object({
95
+ apiKey: z.string(),
96
+ baseURL: z.string(),
97
+ searchType: z.union(["auto", "keyword", "neural"]),
98
+ numResults: z.number().step(1).min(1),
99
+ highlightsPerResult: z.number().step(1).min(1)
100
+ });
101
+ function apply(ctx, config) {
102
+ ctx.web.registerSearchProvider(new ExaSearchProvider({
103
+ // Every environment layer may name this key: the product trusts the
104
+ // project it is launched in, and the managed store is not involved here.
105
+ apiKey: config.apiKey ?? launchEnvironmentOf(ctx).get("EXA_API_KEY")?.value ?? "",
106
+ baseURL: config.baseURL ?? EXA_DEFAULT_BASE_URL,
107
+ searchType: config.searchType ?? EXA_DEFAULT_SEARCH_TYPE,
108
+ highlightsPerResult: config.highlightsPerResult ?? EXA_DEFAULT_HIGHLIGHTS_PER_RESULT,
109
+ ...config.numResults !== void 0 ? { numResults: config.numResults } : {}
110
+ }));
111
+ }
112
+ export {
113
+ Config,
114
+ EXA_DEFAULT_BASE_URL,
115
+ EXA_DEFAULT_HIGHLIGHTS_PER_RESULT,
116
+ EXA_DEFAULT_SEARCH_TYPE,
117
+ EXA_PROVIDER_ID,
118
+ ExaSearchProvider,
119
+ apply,
120
+ inject,
121
+ name
122
+ };
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@rebon/mods-runtime",
3
+ "version": "0.0.0-private",
4
+ "private": true,
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "engines": { "node": ">=24.19.0 <25" },
8
+ "scripts": { "test": "node --test test/*.test.mjs" },
9
+ "exports": {
10
+ ".": "./src/index.mjs",
11
+ "./claude-code": "./src/claude-code.mjs"
12
+ }
13
+ }
@@ -0,0 +1,188 @@
1
+ // The hook chain: what `on(event, matcher?, hook)` builds and what a
2
+ // dispatch runs through it.
3
+ //
4
+ // Every hook is `($, e, next)`. `next(e)` runs the hooks beneath and then
5
+ // the engine's own behaviour (`core`), resolving to the event's result. A
6
+ // hook that returns without calling `next` answers for itself; one that
7
+ // calls `next({ ...e, x })` rewrites what the rest sees; one that returns
8
+ // nothing after calling `next` leaves the answer from beneath as it is.
9
+ //
10
+ // A hook that throws or runs out of its budget is skipped and the chain
11
+ // continues without it, unless its registration's `.catch` handler answers
12
+ // in its place — the rule the mods reference states, and the one that keeps
13
+ // a broken mod from blocking a prompt. The failure is reported through
14
+ // `onFailure` so the host can write it to the debug log under the mod's name.
15
+
16
+ const DEFAULT_BUDGET_MS = 15_000;
17
+
18
+ /// Whether `pattern` (an event name, `*`, `ns.*` or `!name`) selects `event`.
19
+ export function patternSelects(pattern, event) {
20
+ if (pattern === '*') return !event.startsWith('telemetry.');
21
+ if (pattern.startsWith('!')) {
22
+ const excluded = pattern.slice(1);
23
+ if (event.startsWith('telemetry.')) return false;
24
+ return !patternSelects(excluded, event);
25
+ }
26
+ if (pattern.endsWith('.*')) return event.startsWith(pattern.slice(0, -1));
27
+ return pattern === event;
28
+ }
29
+
30
+ /// Whether a matcher selects a value: a literal by equality, a RegExp by
31
+ /// test, a list by any member, an object by every key, an array value by
32
+ /// any item.
33
+ export function matcherSelects(matcher, value) {
34
+ if (matcher === undefined) return true;
35
+ if (matcher instanceof RegExp) return typeof value === 'string' && matcher.test(value);
36
+ if (Array.isArray(matcher)) return matcher.some((alternative) => matcherSelects(alternative, value));
37
+ if (Array.isArray(value)) return value.some((item) => matcherSelects(matcher, item));
38
+ if (matcher !== null && typeof matcher === 'object') {
39
+ if (value === null || typeof value !== 'object') return false;
40
+ return Object.keys(matcher).every((key) => matcherSelects(matcher[key], value[key]));
41
+ }
42
+ return matcher === value;
43
+ }
44
+
45
+ /// What `on()` returns: the registration, with `.catch` for a fallback.
46
+ class Registration {
47
+ constructor(entry) { this.entry = entry; }
48
+ catch(handler) {
49
+ if (typeof handler !== 'function') throw new TypeError('.catch() takes a function');
50
+ this.entry.catchHandler = handler;
51
+ return this;
52
+ }
53
+ }
54
+
55
+ export class HookChain {
56
+ #entries = [];
57
+ #sequence = 0;
58
+ constructor({ onFailure } = {}) {
59
+ this.onFailure = onFailure ?? (() => {});
60
+ }
61
+
62
+ /// `on(pattern, hook)` or `on(pattern, matcher, hook)`.
63
+ on(pattern, matcherOrHook, maybeHook) {
64
+ if (typeof pattern !== 'string' || pattern.length === 0) throw new TypeError('on() needs an event pattern');
65
+ const hook = maybeHook === undefined ? matcherOrHook : maybeHook;
66
+ const matcher = maybeHook === undefined ? undefined : matcherOrHook;
67
+ if (typeof hook !== 'function') throw new TypeError(`on(${JSON.stringify(pattern)}) needs a hook function`);
68
+ if (matcher !== undefined && (matcher === null || typeof matcher !== 'object')) {
69
+ throw new TypeError(`on(${JSON.stringify(pattern)}) takes a matcher object before the hook`);
70
+ }
71
+ const entry = { id: ++this.#sequence, pattern, matcher, hook, catchHandler: undefined };
72
+ this.#entries.push(entry);
73
+ return new Registration(entry);
74
+ }
75
+
76
+ /// The patterns registered, in registration order, each once.
77
+ patterns() {
78
+ const seen = new Set();
79
+ const out = [];
80
+ for (const entry of this.#entries) {
81
+ if (seen.has(entry.pattern)) continue;
82
+ seen.add(entry.pattern);
83
+ out.push(entry.pattern);
84
+ }
85
+ return out;
86
+ }
87
+
88
+ /// Whether any registration could select `event` (matchers aside).
89
+ listens(event) {
90
+ return this.#entries.some((entry) => patternSelects(entry.pattern, event));
91
+ }
92
+
93
+ /// The registrations whose pattern selects `event`. Their matchers are
94
+ /// tested per hook at dispatch, against the event as the hooks above
95
+ /// left it: a rewrite upstream is what a matcher downstream sees.
96
+ hooksFor(event) {
97
+ return this.#entries.filter((entry) => patternSelects(entry.pattern, event));
98
+ }
99
+
100
+ /// Runs `event` through the hooks that select it, `core` beneath them.
101
+ ///
102
+ /// `core(e)` is the engine's own behaviour for the event as the chain left
103
+ /// `e`; it is called at most once. The resolved value is the event's result.
104
+ async dispatch(event, input, core, options = {}) {
105
+ const hooks = this.hooksFor(event);
106
+ const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;
107
+ const engine = options.engine;
108
+ const started = Date.now();
109
+ const controller = new AbortController();
110
+ if (options.signal) options.signal.addEventListener('abort', () => controller.abort(), { once: true });
111
+ const remaining = () => Math.max(0, budgetMs - (Date.now() - started));
112
+ const dispatchState = { reachedCore: false, coreInput: undefined };
113
+
114
+ const run = async (index, current) => {
115
+ if (index >= hooks.length) {
116
+ dispatchState.reachedCore = true;
117
+ dispatchState.coreInput = current;
118
+ return core(current);
119
+ }
120
+ const entry = hooks[index];
121
+ if (!matcherSelects(entry.matcher, current)) return run(index + 1, current);
122
+ let nextCalled = false;
123
+ let beneath;
124
+ const next = (rewritten = current) => {
125
+ if (nextCalled) return beneath;
126
+ nextCalled = true;
127
+ beneath = run(index + 1, rewritten);
128
+ return beneath;
129
+ };
130
+ next.signal = controller.signal;
131
+ next.budget = () => remaining();
132
+ next.origin = options.origin;
133
+ const frozen = freezeDeep(current);
134
+ try {
135
+ const answer = await withBudget(entry.hook(engine, frozen, next), remaining(), controller);
136
+ if (answer !== undefined) return answer;
137
+ if (nextCalled) return await beneath;
138
+ return run(index + 1, current);
139
+ } catch (error) {
140
+ this.onFailure({ event, pattern: entry.pattern, error });
141
+ if (entry.catchHandler) {
142
+ const caught = Object.assign((rewritten = current) => next(rewritten), next, {
143
+ error,
144
+ cause: error,
145
+ });
146
+ try {
147
+ const answer = await withBudget(entry.catchHandler(engine, frozen, caught), remaining(), controller);
148
+ if (answer !== undefined) return answer;
149
+ } catch (second) {
150
+ this.onFailure({ event, pattern: entry.pattern, error: second, inCatch: true });
151
+ }
152
+ }
153
+ if (nextCalled) return await beneath;
154
+ return run(index + 1, current);
155
+ }
156
+ };
157
+ const result = await run(0, input);
158
+ return { result, reachedCore: dispatchState.reachedCore, coreInput: dispatchState.coreInput };
159
+ }
160
+ }
161
+
162
+ async function withBudget(pending, ms, controller) {
163
+ if (!(pending instanceof Promise)) return pending;
164
+ let timer;
165
+ const timeout = new Promise((_, reject) => {
166
+ timer = setTimeout(() => {
167
+ controller.abort();
168
+ reject(new Error(`[HOOK_BUDGET] the hook did not answer within ${ms}ms`));
169
+ }, ms);
170
+ });
171
+ try {
172
+ return await Promise.race([pending, timeout]);
173
+ } finally {
174
+ clearTimeout(timer);
175
+ }
176
+ }
177
+
178
+ /// A frozen copy of a plain value, so a hook reads `e` and cannot write it.
179
+ export function freezeDeep(value) {
180
+ if (value === null || typeof value !== 'object') return value;
181
+ if (Object.isFrozen(value)) return value;
182
+ if (Array.isArray(value)) return Object.freeze(value.map(freezeDeep));
183
+ const proto = Object.getPrototypeOf(value);
184
+ if (proto !== Object.prototype && proto !== null) return value;
185
+ const out = {};
186
+ for (const key of Object.keys(value)) out[key] = freezeDeep(value[key]);
187
+ return Object.freeze(out);
188
+ }
@@ -0,0 +1,217 @@
1
+ // Rebon's hook events, as a mod's native events and as `classic.<Event>`.
2
+ //
3
+ // Rebon raises the Claude Code settings-hook events (`PreToolUse`,
4
+ // `UserPromptSubmit`, `Stop`, ...) through its policy seat; the `mods`
5
+ // subscriber hands each one here as `{ event, input }`, `input` being what a
6
+ // settings hook would read on stdin. Two things happen with it:
7
+ //
8
+ // 1. The native event the mods reference maps it to fires through the
9
+ // chain — `tool.call` for PreToolUse, `prompt.submit` for
10
+ // UserPromptSubmit, `turn.complete` for Stop, and so on — and what the
11
+ // chain answered is written back as a settings hook's JSON output, the
12
+ // one vocabulary Rebon's hook runtime projects into effects.
13
+ // 2. `classic.<Event>` fires with the stdin shape itself, and a hook's
14
+ // return value is that JSON output, passed through as written.
15
+ //
16
+ // The answer is a list of such outputs. Rebon parses each one exactly as
17
+ // it parses a command hook's stdout, aggregates them and projects the
18
+ // effects, so a mod can do precisely what a settings hook can do, and the
19
+ // mapping below is the whole statement of what a native answer means.
20
+ //
21
+ // `tool.call` spans two of Rebon's events. The hook calls `next(e)` for the
22
+ // result, and the result arrives with PostToolUse: the chain is suspended at
23
+ // its core until then, and the PreToolUse answer is given the moment the
24
+ // chain reaches core (the rewritten input) or returns without it (a deny).
25
+
26
+ const PENDING_CALL_TTL_MS = 10 * 60 * 1000;
27
+
28
+ const NATIVE_OF = Object.freeze({
29
+ PreToolUse: 'tool.call',
30
+ PostToolUse: 'tool.call',
31
+ PostToolUseFailure: 'tool.call',
32
+ PermissionDenied: 'tool.call',
33
+ PermissionRequest: 'tool.check',
34
+ UserPromptSubmit: 'prompt.submit',
35
+ Stop: 'turn.complete',
36
+ PreCompact: 'session.compact',
37
+ SessionEnd: 'session.end',
38
+ });
39
+
40
+ /// The native event a classic one maps to, when it maps to one.
41
+ export function nativeEventOf(classic) {
42
+ return NATIVE_OF[classic];
43
+ }
44
+
45
+ /// The classic events a chain with these patterns would want to hear.
46
+ export function classicEventsOf(chain, allEvents) {
47
+ return allEvents.filter((event) => {
48
+ if (chain.listens(`classic.${event}`)) return true;
49
+ const native = NATIVE_OF[event];
50
+ return native !== undefined && chain.listens(native);
51
+ });
52
+ }
53
+
54
+ function plain(value) {
55
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
56
+ }
57
+
58
+ function sameJson(left, right) {
59
+ return JSON.stringify(left) === JSON.stringify(right);
60
+ }
61
+
62
+ /// Runs one classic event through `mod`'s chain and answers the outputs.
63
+ export async function dispatchClassic(mod, { event, input }) {
64
+ const outputs = [];
65
+ const native = NATIVE_OF[event];
66
+ if (native !== undefined && mod.chain.listens(native)) {
67
+ const output = await dispatchNative(mod, event, input);
68
+ if (output !== undefined) outputs.push(output);
69
+ }
70
+ const classic = `classic.${event}`;
71
+ if (mod.chain.listens(classic)) {
72
+ const { result, reachedCore } = await mod.chain.dispatch(classic, input, async () => ({}), mod.dispatchOptions());
73
+ if (plain(result) && !(reachedCore && Object.keys(result).length === 0)) outputs.push(result);
74
+ }
75
+ return { outputs };
76
+ }
77
+
78
+ async function dispatchNative(mod, event, input) {
79
+ switch (event) {
80
+ case 'PreToolUse': return preToolUse(mod, input);
81
+ case 'PostToolUse': return settleToolCall(mod, input.tool_use_id, { result: input.tool_response, isError: false }, 'PostToolUse');
82
+ case 'PostToolUseFailure': return settleToolCall(mod, input.tool_use_id, { result: { error: input.error }, isError: true, text: input.error }, 'PostToolUseFailure');
83
+ case 'PermissionDenied': return settleToolCall(mod, input.tool_use_id, { result: { error: input.message ?? 'permission denied' }, isError: true, deny: input.message ?? 'permission denied' }, undefined);
84
+ case 'PermissionRequest': return toolCheck(mod, input);
85
+ case 'UserPromptSubmit': return promptSubmit(mod, input);
86
+ case 'Stop': return turnComplete(mod, input);
87
+ case 'PreCompact': return sessionCompact(mod, input);
88
+ case 'SessionEnd': {
89
+ await mod.chain.dispatch('session.end', { reason: input.reason ?? 'other', resume: {} }, async () => ({ sessionId: input.session_id }), mod.dispatchOptions());
90
+ return undefined;
91
+ }
92
+ default: return undefined;
93
+ }
94
+ }
95
+
96
+ /// PreToolUse → `tool.call`: the chain runs until it reaches core or
97
+ /// answers; core parks until the tool's result arrives.
98
+ async function preToolUse(mod, input) {
99
+ const e = {
100
+ tool: input.tool_name,
101
+ tool_use_id: input.tool_use_id,
102
+ input: input.tool_input ?? {},
103
+ agentId: input.agent_id,
104
+ origin: { kind: 'model' },
105
+ };
106
+ let settle;
107
+ const parked = new Promise((resolve) => { settle = resolve; });
108
+ let reportPre;
109
+ const preAnswered = new Promise((resolve) => { reportPre = resolve; });
110
+ const core = (final) => {
111
+ reportPre({ continued: true, input: final.input });
112
+ return parked;
113
+ };
114
+ const whole = mod.chain.dispatch('tool.call', e, core, mod.dispatchOptions({ budgetMs: PENDING_CALL_TTL_MS }))
115
+ .then((outcome) => { reportPre({ continued: false, outcome }); return outcome; })
116
+ .catch((error) => { mod.report('tool.call', error); reportPre({ continued: false, outcome: { result: undefined } }); return { result: undefined }; });
117
+ const pre = await preAnswered;
118
+ if (pre.continued) {
119
+ const expiry = setTimeout(() => mod.pendingCalls.delete(input.tool_use_id), PENDING_CALL_TTL_MS);
120
+ mod.pendingCalls.set(input.tool_use_id, { settle, whole, expiry, coreResult: undefined });
121
+ if (!sameJson(pre.input, e.input) && plain(pre.input)) {
122
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput: pre.input } };
123
+ }
124
+ return undefined;
125
+ }
126
+ const answer = pre.outcome?.result;
127
+ if (plain(answer) && typeof answer.deny === 'string') {
128
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: answer.deny } };
129
+ }
130
+ if (plain(answer) && 'result' in answer) {
131
+ // A mod answered the call itself. Rebon's hook model has no way to hand
132
+ // the model a result without running the tool, so the call goes on and
133
+ // the mod's answer is reported where the person can read why.
134
+ mod.log(`tool.call for ${e.tool} was answered by the mod; Rebon runs the tool anyway`, 'debug');
135
+ }
136
+ return undefined;
137
+ }
138
+
139
+ /// PostToolUse / PostToolUseFailure / PermissionDenied → the parked
140
+ /// `tool.call` core resolves and the hook's final answer is read.
141
+ async function settleToolCall(mod, toolUseId, coreResult, eventName) {
142
+ const pending = mod.pendingCalls.get(toolUseId);
143
+ if (!pending) return undefined;
144
+ mod.pendingCalls.delete(toolUseId);
145
+ clearTimeout(pending.expiry);
146
+ pending.settle(coreResult);
147
+ const outcome = await pending.whole;
148
+ const answer = outcome?.result;
149
+ if (eventName === undefined || !plain(answer)) return undefined;
150
+ const output = { hookEventName: eventName };
151
+ let any = false;
152
+ if (eventName === 'PostToolUse' && 'result' in answer && !sameJson(answer.result, coreResult.result)) {
153
+ output.updatedMCPToolOutput = answer.result;
154
+ any = true;
155
+ }
156
+ if (typeof answer.context === 'string' && answer.context.length > 0) {
157
+ output.additionalContext = answer.context;
158
+ any = true;
159
+ }
160
+ return any ? { hookSpecificOutput: output } : undefined;
161
+ }
162
+
163
+ /// PermissionRequest → `tool.check`: `{ decision }` becomes the request's
164
+ /// answer; `ask` leaves the prompt to the person.
165
+ async function toolCheck(mod, input) {
166
+ const e = { tool: input.tool_name, tool_use_id: input.tool_use_id, input: input.tool_input ?? {}, reason: input.reason };
167
+ const { result } = await mod.chain.dispatch('tool.check', e, async () => ({ decision: 'ask' }), mod.dispatchOptions());
168
+ if (!plain(result)) return undefined;
169
+ if (result.decision === 'allow') {
170
+ return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'allow' } } };
171
+ }
172
+ if (result.decision === 'deny') {
173
+ return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'deny', message: result.reason ?? 'denied by a mod' } } };
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ /// UserPromptSubmit → `prompt.submit`: a rewrite replaces the prompt, a
179
+ /// `drop` refuses it, `context` rides along as additional context.
180
+ async function promptSubmit(mod, input) {
181
+ const e = { text: input.prompt ?? '', origin: { kind: 'user' }, sessionId: input.session_id, cwd: input.cwd };
182
+ const { result, reachedCore, coreInput } = await mod.chain.dispatch('prompt.submit', e, async (final) => ({ isQueued: true, text: final.text }), mod.dispatchOptions());
183
+ if (plain(result) && typeof result.drop === 'string') return { decision: 'block', reason: result.drop };
184
+ const specific = { hookEventName: 'UserPromptSubmit' };
185
+ let any = false;
186
+ if (reachedCore && typeof coreInput?.text === 'string' && coreInput.text !== e.text) {
187
+ specific.replacementPrompt = coreInput.text;
188
+ any = true;
189
+ }
190
+ if (plain(result) && typeof result.context === 'string' && result.context.length > 0) {
191
+ specific.additionalContext = result.context;
192
+ any = true;
193
+ }
194
+ if (plain(result) && typeof result.sessionTitle === 'string') {
195
+ specific.sessionTitle = result.sessionTitle;
196
+ any = true;
197
+ }
198
+ return any ? { hookSpecificOutput: specific } : undefined;
199
+ }
200
+
201
+ /// Stop → `turn.complete`: a different `text` shows beneath the answer.
202
+ async function turnComplete(mod, input) {
203
+ const e = { reason: input.stop_reason ?? 'end_turn', turnId: input.turn_id ?? null, text: input.last_assistant_message ?? '' };
204
+ const { result } = await mod.chain.dispatch('turn.complete', e, async (final) => ({ text: final.text }), mod.dispatchOptions());
205
+ if (plain(result) && typeof result.text === 'string' && result.text !== e.text && result.text.length > 0) {
206
+ return { systemMessage: result.text };
207
+ }
208
+ return undefined;
209
+ }
210
+
211
+ /// PreCompact → `session.compact`: `{ skip }` keeps the conversation.
212
+ async function sessionCompact(mod, input) {
213
+ const e = { trigger: input.trigger ?? 'manual', instructions: input.custom_instructions ?? '', messages: [] };
214
+ const { result } = await mod.chain.dispatch('session.compact', e, async () => ({ messages: [] }), mod.dispatchOptions());
215
+ if (plain(result) && typeof result.skip === 'string') return { decision: 'block', reason: result.skip };
216
+ return undefined;
217
+ }