@librechat/agents 3.1.68 → 3.1.71-dev.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/dist/cjs/agents/AgentContext.cjs +23 -3
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +16 -1
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +136 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +162 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
- package/dist/cjs/hooks/executeHooks.cjs +276 -0
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
- package/dist/cjs/hooks/matchers.cjs +256 -0
- package/dist/cjs/hooks/matchers.cjs.map +1 -0
- package/dist/cjs/hooks/types.cjs +27 -0
- package/dist/cjs/hooks/types.cjs.map +1 -0
- package/dist/cjs/main.cjs +57 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +74 -12
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs +9 -2
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/run.cjs +115 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +44 -0
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +208 -0
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +287 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/CodeExecutor.cjs +0 -9
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +7 -23
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ReadFile.cjs +43 -0
- package/dist/cjs/tools/ReadFile.cjs.map +1 -0
- package/dist/cjs/tools/SkillTool.cjs +50 -0
- package/dist/cjs/tools/SkillTool.cjs.map +1 -0
- package/dist/cjs/tools/SubagentTool.cjs +92 -0
- package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +746 -174
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearch.cjs +2 -13
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
- package/dist/cjs/tools/skillCatalog.cjs +84 -0
- package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
- package/dist/cjs/tools/toolOutputReferences.cjs +475 -0
- package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -0
- package/dist/cjs/utils/truncation.cjs +28 -0
- package/dist/cjs/utils/truncation.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +23 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +15 -2
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +136 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +160 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
- package/dist/esm/hooks/executeHooks.mjs +273 -0
- package/dist/esm/hooks/executeHooks.mjs.map +1 -0
- package/dist/esm/hooks/matchers.mjs +251 -0
- package/dist/esm/hooks/matchers.mjs.map +1 -0
- package/dist/esm/hooks/types.mjs +25 -0
- package/dist/esm/hooks/types.mjs.map +1 -0
- package/dist/esm/main.mjs +13 -2
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +66 -4
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs +9 -2
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/run.mjs +115 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +44 -0
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +200 -0
- package/dist/esm/tools/BashExecutor.mjs.map +1 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +278 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/CodeExecutor.mjs +0 -9
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +8 -24
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ReadFile.mjs +38 -0
- package/dist/esm/tools/ReadFile.mjs.map +1 -0
- package/dist/esm/tools/SkillTool.mjs +45 -0
- package/dist/esm/tools/SkillTool.mjs.map +1 -0
- package/dist/esm/tools/SubagentTool.mjs +85 -0
- package/dist/esm/tools/SubagentTool.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +748 -176
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearch.mjs +3 -14
- package/dist/esm/tools/ToolSearch.mjs.map +1 -1
- package/dist/esm/tools/skillCatalog.mjs +82 -0
- package/dist/esm/tools/skillCatalog.mjs.map +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
- package/dist/esm/tools/toolOutputReferences.mjs +468 -0
- package/dist/esm/tools/toolOutputReferences.mjs.map +1 -0
- package/dist/esm/utils/truncation.mjs +27 -1
- package/dist/esm/utils/truncation.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +6 -0
- package/dist/types/common/enum.d.ts +10 -2
- package/dist/types/graphs/Graph.d.ts +23 -0
- package/dist/types/hooks/HookRegistry.d.ts +56 -0
- package/dist/types/hooks/executeHooks.d.ts +79 -0
- package/dist/types/hooks/index.d.ts +6 -0
- package/dist/types/hooks/matchers.d.ts +95 -0
- package/dist/types/hooks/types.d.ts +320 -0
- package/dist/types/index.d.ts +8 -0
- package/dist/types/messages/format.d.ts +2 -1
- package/dist/types/run.d.ts +2 -0
- package/dist/types/summarization/node.d.ts +2 -0
- package/dist/types/tools/BashExecutor.d.ts +76 -0
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +4 -9
- package/dist/types/tools/ReadFile.d.ts +28 -0
- package/dist/types/tools/SkillTool.d.ts +40 -0
- package/dist/types/tools/SubagentTool.d.ts +36 -0
- package/dist/types/tools/ToolNode.d.ts +109 -4
- package/dist/types/tools/ToolSearch.d.ts +2 -2
- package/dist/types/tools/skillCatalog.d.ts +19 -0
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
- package/dist/types/tools/subagent/index.d.ts +2 -0
- package/dist/types/tools/toolOutputReferences.d.ts +205 -0
- package/dist/types/types/graph.d.ts +61 -2
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/types/run.d.ts +28 -0
- package/dist/types/types/skill.d.ts +9 -0
- package/dist/types/types/tools.d.ts +108 -10
- package/dist/types/utils/truncation.d.ts +21 -0
- package/package.json +5 -1
- package/src/agents/AgentContext.ts +26 -2
- package/src/common/enum.ts +15 -1
- package/src/graphs/Graph.ts +161 -0
- package/src/hooks/HookRegistry.ts +208 -0
- package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
- package/src/hooks/__tests__/compactHooks.test.ts +214 -0
- package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
- package/src/hooks/__tests__/integration.test.ts +337 -0
- package/src/hooks/__tests__/matchers.test.ts +238 -0
- package/src/hooks/__tests__/toolHooks.test.ts +669 -0
- package/src/hooks/executeHooks.ts +375 -0
- package/src/hooks/index.ts +57 -0
- package/src/hooks/matchers.ts +280 -0
- package/src/hooks/types.ts +404 -0
- package/src/index.ts +10 -0
- package/src/messages/format.ts +74 -4
- package/src/messages/formatAgentMessages.skills.test.ts +334 -0
- package/src/messages/prune.ts +9 -2
- package/src/run.ts +130 -0
- package/src/scripts/multi-agent-subagent.ts +246 -0
- package/src/scripts/programmatic_exec.ts +1 -10
- package/src/scripts/subagent-event-driven-debug.ts +190 -0
- package/src/scripts/subagent-tools-debug.ts +160 -0
- package/src/scripts/test_code_api.ts +0 -7
- package/src/scripts/tool_search.ts +1 -10
- package/src/specs/prune.test.ts +413 -0
- package/src/specs/subagent.test.ts +305 -0
- package/src/summarization/node.ts +53 -0
- package/src/tools/BashExecutor.ts +238 -0
- package/src/tools/BashProgrammaticToolCalling.ts +381 -0
- package/src/tools/CodeExecutor.ts +0 -11
- package/src/tools/ProgrammaticToolCalling.ts +4 -29
- package/src/tools/ReadFile.ts +39 -0
- package/src/tools/SkillTool.ts +46 -0
- package/src/tools/SubagentTool.ts +100 -0
- package/src/tools/ToolNode.ts +999 -214
- package/src/tools/ToolSearch.ts +3 -19
- package/src/tools/__tests__/BashExecutor.test.ts +36 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +7 -8
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -1
- package/src/tools/__tests__/ReadFile.test.ts +44 -0
- package/src/tools/__tests__/SkillTool.test.ts +442 -0
- package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
- package/src/tools/__tests__/SubagentTool.test.ts +149 -0
- package/src/tools/__tests__/ToolNode.outputReferences.test.ts +1395 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
- package/src/tools/__tests__/ToolSearch.integration.test.ts +7 -8
- package/src/tools/__tests__/skillCatalog.test.ts +161 -0
- package/src/tools/__tests__/subagentHooks.test.ts +215 -0
- package/src/tools/__tests__/toolOutputReferences.test.ts +415 -0
- package/src/tools/skillCatalog.ts +126 -0
- package/src/tools/subagent/SubagentExecutor.ts +676 -0
- package/src/tools/subagent/index.ts +13 -0
- package/src/tools/toolOutputReferences.ts +590 -0
- package/src/types/graph.ts +80 -1
- package/src/types/index.ts +1 -0
- package/src/types/run.ts +28 -0
- package/src/types/skill.ts +11 -0
- package/src/types/tools.ts +112 -10
- package/src/utils/__tests__/truncation.test.ts +66 -0
- package/src/utils/truncation.ts +30 -0
|
@@ -4,8 +4,10 @@ import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
|
|
|
4
4
|
import type { ToolCall } from '@langchain/core/messages/tool';
|
|
5
5
|
import type * as t from '@/types';
|
|
6
6
|
import { ToolNode as CustomToolNode } from '@/tools/ToolNode';
|
|
7
|
+
import { ToolOutputReferenceRegistry } from '@/tools/toolOutputReferences';
|
|
7
8
|
import { AgentContext } from '@/agents/AgentContext';
|
|
8
9
|
import { HandlerRegistry } from '@/events';
|
|
10
|
+
import type { HookRegistry } from '@/hooks';
|
|
9
11
|
export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphState, _TNodeName extends string = string> {
|
|
10
12
|
abstract resetValues(): void;
|
|
11
13
|
abstract initializeTools({ currentTools, currentToolMap, }: {
|
|
@@ -43,6 +45,20 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
|
|
|
43
45
|
/** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
|
|
44
46
|
invokedToolIds?: Set<string>;
|
|
45
47
|
handlerRegistry: HandlerRegistry | undefined;
|
|
48
|
+
hookRegistry: HookRegistry | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Run-scoped config for the tool output reference registry. Threaded
|
|
51
|
+
* from `RunConfig.toolOutputReferences` down into every ToolNode this
|
|
52
|
+
* graph compiles.
|
|
53
|
+
*/
|
|
54
|
+
toolOutputReferences: t.ToolOutputReferencesConfig | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* Shared registry instance used by every ToolNode compiled from this
|
|
57
|
+
* graph. Lazily constructed on first access so multi-agent graphs
|
|
58
|
+
* produce one registry per run (not one per agent), letting cross-
|
|
59
|
+
* agent `{{tool<i>turn<n>}}` substitutions resolve.
|
|
60
|
+
*/
|
|
61
|
+
private _toolOutputRegistry?;
|
|
46
62
|
/**
|
|
47
63
|
* Tool session contexts for automatic state persistence across tool invocations.
|
|
48
64
|
* Keyed by tool name (e.g., Constants.EXECUTE_CODE).
|
|
@@ -55,6 +71,13 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
|
|
|
55
71
|
* Call after a run completes and content has been extracted.
|
|
56
72
|
*/
|
|
57
73
|
clearHeavyState(): void;
|
|
74
|
+
/**
|
|
75
|
+
* Returns the shared `ToolOutputReferenceRegistry` for this run,
|
|
76
|
+
* constructing it on first access. Returns `undefined` when the
|
|
77
|
+
* feature is disabled. All ToolNodes compiled from this graph share
|
|
78
|
+
* this single instance so cross-agent `{{…}}` references resolve.
|
|
79
|
+
*/
|
|
80
|
+
protected getOrCreateToolOutputRegistry(): ToolOutputReferenceRegistry | undefined;
|
|
58
81
|
}
|
|
59
82
|
export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
60
83
|
overrideModel?: t.ChatModel;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { HookEvent, HookMatcher } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Run-scoped storage for hook matchers with an additional layer for
|
|
4
|
+
* session-scoped matchers that should be cleaned up between sessions.
|
|
5
|
+
*
|
|
6
|
+
* Hosts construct one registry per `Run` (mirroring how `HandlerRegistry` is
|
|
7
|
+
* scoped) and register global matchers + per-session matchers against it.
|
|
8
|
+
* Registration is strictly additive — nothing in this class mutates a
|
|
9
|
+
* matcher's callbacks or flags after insertion.
|
|
10
|
+
*
|
|
11
|
+
* ## Why `Map<sessionId, MatcherBucket>` and not `Record`
|
|
12
|
+
*
|
|
13
|
+
* LibreChat runs thousands of parallel sessions in one Node process, and
|
|
14
|
+
* hook registration happens inside hot paths (tool loading, agent spawning).
|
|
15
|
+
* A `Record<sessionId, ...>` has to be spread on every insertion, which is
|
|
16
|
+
* O(n) per call and O(n²) total for a batch of parallel registrations. A
|
|
17
|
+
* Map mutates in place, keeping insertions O(1). This mirrors the reasoning
|
|
18
|
+
* Claude Code documents at `utils/hooks/sessionHooks.ts:62`.
|
|
19
|
+
*/
|
|
20
|
+
export declare class HookRegistry {
|
|
21
|
+
private readonly global;
|
|
22
|
+
private readonly sessions;
|
|
23
|
+
/**
|
|
24
|
+
* Register a matcher for the lifetime of this registry (= one Run).
|
|
25
|
+
* Returns an unregister function that removes the matcher by reference.
|
|
26
|
+
*/
|
|
27
|
+
register<E extends HookEvent>(event: E, matcher: HookMatcher<E>): () => void;
|
|
28
|
+
/**
|
|
29
|
+
* Register a matcher for a specific session. Cleared automatically when
|
|
30
|
+
* `clearSession(sessionId)` is called, or can be removed directly via the
|
|
31
|
+
* returned unregister function.
|
|
32
|
+
*/
|
|
33
|
+
registerSession<E extends HookEvent>(sessionId: string, event: E, matcher: HookMatcher<E>): () => void;
|
|
34
|
+
/**
|
|
35
|
+
* Returns all matchers registered for `event`, concatenating global first
|
|
36
|
+
* and then session-specific (when `sessionId` is supplied). The caller
|
|
37
|
+
* receives a fresh array, so iterating it is safe even if a matcher is
|
|
38
|
+
* removed mid-iteration (e.g. via `once: true`).
|
|
39
|
+
*/
|
|
40
|
+
getMatchers<E extends HookEvent>(event: E, sessionId?: string): HookMatcher<E>[];
|
|
41
|
+
/**
|
|
42
|
+
* Removes `matcher` by reference from global storage first, falling back
|
|
43
|
+
* to the session bucket when `sessionId` is supplied. Used by
|
|
44
|
+
* `executeHooks` to drop `once: true` matchers after they fire.
|
|
45
|
+
*/
|
|
46
|
+
removeMatcher<E extends HookEvent>(event: E, matcher: HookMatcher<E>, sessionId?: string): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Drops every session-scoped matcher for `sessionId`. Call this in the
|
|
49
|
+
* `finally` block around a Run so a `once: true` hook that never fired
|
|
50
|
+
* cannot leak into the next session on the same registry.
|
|
51
|
+
*/
|
|
52
|
+
clearSession(sessionId: string): void;
|
|
53
|
+
/** True if at least one matcher exists for `event` (global + session). */
|
|
54
|
+
hasHookFor(event: HookEvent, sessionId?: string): boolean;
|
|
55
|
+
private ensureSessionBucket;
|
|
56
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { Logger } from 'winston';
|
|
2
|
+
import type { HookRegistry } from './HookRegistry';
|
|
3
|
+
import type { HookInput, AggregatedHookResult } from './types';
|
|
4
|
+
/** Default per-hook timeout when a matcher doesn't set its own. */
|
|
5
|
+
export declare const DEFAULT_HOOK_TIMEOUT_MS = 30000;
|
|
6
|
+
/**
|
|
7
|
+
* Options for a single `executeHooks` call. The `input` drives everything —
|
|
8
|
+
* the event name is read from `input.hook_event_name`, matchers are looked
|
|
9
|
+
* up against that event, and each hook receives `input` directly.
|
|
10
|
+
*/
|
|
11
|
+
export interface ExecuteHooksOptions {
|
|
12
|
+
registry: HookRegistry;
|
|
13
|
+
input: HookInput;
|
|
14
|
+
/** Scope lookup to this session (in addition to global matchers). */
|
|
15
|
+
sessionId?: string;
|
|
16
|
+
/** Query string matched against each matcher's pattern (tool name, etc.). */
|
|
17
|
+
matchQuery?: string;
|
|
18
|
+
/** Parent AbortSignal — combined with per-hook timeout into the hook signal. */
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
/** Default per-hook timeout; overridden by `matcher.timeout` when present. */
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
/** Optional winston logger for non-internal hook errors. */
|
|
23
|
+
logger?: Logger;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Fires every matcher registered against `input.hook_event_name`, folding
|
|
27
|
+
* their results per `deny > ask > allow` precedence and accumulating
|
|
28
|
+
* context/errors.
|
|
29
|
+
*
|
|
30
|
+
* ## Parallelism and determinism
|
|
31
|
+
*
|
|
32
|
+
* All matching hooks fire simultaneously and are awaited via `Promise.all`,
|
|
33
|
+
* which preserves input-array order in its returned results. The fold
|
|
34
|
+
* therefore iterates outcomes in **registration order** — outer loop over
|
|
35
|
+
* matchers as they sit in the registry (global first, then session), inner
|
|
36
|
+
* loop over each matcher's `hooks` array. Last-writer-wins fields
|
|
37
|
+
* (`updatedInput`, `updatedOutput`) are deterministic in that order, even
|
|
38
|
+
* though hooks may complete in arbitrary wall-clock order.
|
|
39
|
+
*
|
|
40
|
+
* Consumers that need a single authoritative rewrite should still scope
|
|
41
|
+
* `updatedInput`/`updatedOutput` to one hook per matcher to avoid subtle
|
|
42
|
+
* precedence bugs when matchers are added in a different order than
|
|
43
|
+
* expected.
|
|
44
|
+
*
|
|
45
|
+
* ## Timeouts and cancellation
|
|
46
|
+
*
|
|
47
|
+
* Each matcher receives **one shared `AbortSignal`** derived from the
|
|
48
|
+
* caller's parent signal combined with `matcher.timeout` (falling back to
|
|
49
|
+
* `opts.timeoutMs`, default {@link DEFAULT_HOOK_TIMEOUT_MS}). Sharing the
|
|
50
|
+
* signal across hooks in a matcher collapses N timer allocations into
|
|
51
|
+
* one, which matters on the PreToolUse hot path where a matcher with
|
|
52
|
+
* several hooks fires on every tool call. Each hook call is raced
|
|
53
|
+
* against the shared signal, so even a hook that ignores the signal is
|
|
54
|
+
* force-unblocked when the timeout fires. Timeout/abort errors are
|
|
55
|
+
* swallowed into the aggregated result's `errors` array (non-fatal by
|
|
56
|
+
* default).
|
|
57
|
+
*
|
|
58
|
+
* ## Internal matchers
|
|
59
|
+
*
|
|
60
|
+
* A matcher with `internal: true` is excluded from both the `errors` array
|
|
61
|
+
* and the logger output. Use it for infrastructure hooks whose failures
|
|
62
|
+
* should not pollute user-visible diagnostics.
|
|
63
|
+
*
|
|
64
|
+
* ## Once semantics — atomic at-most-once
|
|
65
|
+
*
|
|
66
|
+
* A matcher with `once: true` is removed from the registry **before any
|
|
67
|
+
* hook runs**, inside the synchronous prefix of `executeHooks` (between
|
|
68
|
+
* `getMatchers` and the first `await`). Because Node's event loop serialises
|
|
69
|
+
* sync work, two concurrent `executeHooks` calls can never both observe
|
|
70
|
+
* and dispatch the same `once` matcher — whichever call runs its sync
|
|
71
|
+
* prefix first consumes it, and the loser sees an empty bucket.
|
|
72
|
+
*
|
|
73
|
+
* Trade-off: if every hook in a `once` matcher throws, the matcher is
|
|
74
|
+
* still gone. "Once" here means "at most one dispatch, ever", not "at
|
|
75
|
+
* most one successful execution with retry on failure". Hosts that need
|
|
76
|
+
* retry semantics should register a normal matcher and self-unregister
|
|
77
|
+
* via the `unregister` callback returned from `registry.register`.
|
|
78
|
+
*/
|
|
79
|
+
export declare function executeHooks(opts: ExecuteHooksOptions): Promise<AggregatedHookResult>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { HookRegistry } from './HookRegistry';
|
|
2
|
+
export { executeHooks, DEFAULT_HOOK_TIMEOUT_MS } from './executeHooks';
|
|
3
|
+
export { matchesQuery, hasNestedQuantifier, MAX_PATTERN_LENGTH, MAX_CACHE_SIZE, } from './matchers';
|
|
4
|
+
export { HOOK_EVENTS } from './types';
|
|
5
|
+
export type { HookEvent, HookInput, HookOutput, HookCallback, HookMatcher, HooksByEvent, HookInputByEvent, HookOutputByEvent, BaseHookInput, BaseHookOutput, ToolDecision, StopDecision, AggregatedHookResult, RunStartHookInput, UserPromptSubmitHookInput, PreToolUseHookInput, PostToolUseHookInput, PostToolUseFailureHookInput, PermissionDeniedHookInput, SubagentStartHookInput, SubagentStopHookInput, StopHookInput, StopFailureHookInput, PreCompactHookInput, PostCompactHookInput, RunStartHookOutput, UserPromptSubmitHookOutput, PreToolUseHookOutput, PostToolUseHookOutput, PostToolUseFailureHookOutput, PermissionDeniedHookOutput, SubagentStartHookOutput, SubagentStopHookOutput, StopHookOutput, StopFailureHookOutput, PreCompactHookOutput, PostCompactHookOutput, } from './types';
|
|
6
|
+
export type { ExecuteHooksOptions } from './executeHooks';
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Upper bound on hook-matcher pattern length. Patterns longer than this
|
|
3
|
+
* are rejected outright — the goal is a cheap cap on pathological inputs
|
|
4
|
+
* (repeated quantifiers, huge alternation groups) without pulling in a
|
|
5
|
+
* safe-regex dependency.
|
|
6
|
+
*
|
|
7
|
+
* Legitimate matchers are almost always under 50 characters (tool names,
|
|
8
|
+
* short alternations, simple prefix anchors); 512 leaves generous
|
|
9
|
+
* headroom while preventing 10KB regexes.
|
|
10
|
+
*/
|
|
11
|
+
export declare const MAX_PATTERN_LENGTH = 512;
|
|
12
|
+
/**
|
|
13
|
+
* Upper bound on the compilation cache. Chosen to comfortably hold every
|
|
14
|
+
* distinct pattern a single multi-tenant run is likely to see (tools,
|
|
15
|
+
* agent types, basename filters) without growing without bound.
|
|
16
|
+
*
|
|
17
|
+
* Under hosts that register unique patterns per tenant, LRU eviction
|
|
18
|
+
* keeps the working set bounded — cold patterns are re-compiled on next
|
|
19
|
+
* use, which is the correct cost trade-off for long-running processes
|
|
20
|
+
* that must not leak memory.
|
|
21
|
+
*/
|
|
22
|
+
export declare const MAX_CACHE_SIZE = 256;
|
|
23
|
+
/**
|
|
24
|
+
* Cheap syntactic detector for the most common catastrophic-backtracking
|
|
25
|
+
* shape: a quantified group that contains another quantifier (e.g.
|
|
26
|
+
* `(a+)+`, `(.*)*`, `(\w+)+$`, `(?:(a+))+`). This is the "nested
|
|
27
|
+
* quantifier" class of ReDoS — runs in polynomial-or-worse time on
|
|
28
|
+
* adversarial inputs.
|
|
29
|
+
*
|
|
30
|
+
* The scan walks the pattern linearly using an explicit stack of group
|
|
31
|
+
* frames. For each group it tracks whether the group's contents include
|
|
32
|
+
* "backtrack risk" — meaning a direct quantifier OR a nested group that
|
|
33
|
+
* carries risk up. When a group closes with a trailing quantifier AND its
|
|
34
|
+
* frame carries backtrack risk, the pattern is flagged. Risk propagates
|
|
35
|
+
* to the enclosing frame when a child group closes (whether the child
|
|
36
|
+
* itself was quantified or not), so `(?:(a+))+` — equivalent to `(a+)+`
|
|
37
|
+
* — is flagged correctly even though the outer non-capturing wrapper is
|
|
38
|
+
* one level removed from the inner quantifier.
|
|
39
|
+
*
|
|
40
|
+
* ## Group-syntax prefixes
|
|
41
|
+
*
|
|
42
|
+
* Non-capturing groups (`(?:`), lookaheads (`(?=`, `(?!`), lookbehinds
|
|
43
|
+
* (`(?<=`, `(?<!`), and named groups (`(?<name>`) are skipped over at
|
|
44
|
+
* the `(` so their `?` is not misread as a quantifier. Without this,
|
|
45
|
+
* `(?:pre_)?tool_name` would be incorrectly rejected because the scanner
|
|
46
|
+
* would see the group-syntax `?` as a quantifier at depth 1.
|
|
47
|
+
*
|
|
48
|
+
* ## Heuristic, not a proof
|
|
49
|
+
*
|
|
50
|
+
* This catches the common forms but not all. Ambiguous-alternation ReDoS
|
|
51
|
+
* like `(a|a)+` is not detected. Pathologically long patterns are also
|
|
52
|
+
* caught by {@link MAX_PATTERN_LENGTH}. Hosts that accept user-supplied
|
|
53
|
+
* patterns must still validate upstream.
|
|
54
|
+
*/
|
|
55
|
+
export declare function hasNestedQuantifier(pattern: string): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Tests whether a hook matcher pattern matches the given query string.
|
|
58
|
+
*
|
|
59
|
+
* ## Semantics
|
|
60
|
+
*
|
|
61
|
+
* - `undefined` or empty `pattern` matches any query (wildcard). This is
|
|
62
|
+
* the intended shape for events that do not supply a query string at
|
|
63
|
+
* all (`RunStart`, `Stop`, etc.) — register such matchers without a
|
|
64
|
+
* pattern.
|
|
65
|
+
* - `undefined` or empty `query` with a non-empty `pattern` never matches.
|
|
66
|
+
* Setting a pattern on a query-less event is therefore inert: the
|
|
67
|
+
* matcher will simply never fire. This is intentional — it keeps
|
|
68
|
+
* query-based filtering out of event types where "query" has no meaning,
|
|
69
|
+
* and is documented on `HookMatcher.pattern`.
|
|
70
|
+
* - Otherwise, the pattern is compiled once (via a bounded LRU cache) and
|
|
71
|
+
* tested against the query.
|
|
72
|
+
* - Invalid regex patterns never throw — a failed compile is cached as
|
|
73
|
+
* "never matches" so a single malformed pattern cannot take out a whole
|
|
74
|
+
* `executeHooks` batch.
|
|
75
|
+
*
|
|
76
|
+
* ## ReDoS mitigations
|
|
77
|
+
*
|
|
78
|
+
* Patterns compile through three cheap gates before reaching `new RegExp`:
|
|
79
|
+
*
|
|
80
|
+
* 1. {@link MAX_PATTERN_LENGTH} length cap rejects oversized inputs.
|
|
81
|
+
* 2. {@link hasNestedQuantifier} rejects the most common catastrophic-
|
|
82
|
+
* backtracking shape (quantified group containing a quantifier).
|
|
83
|
+
* 3. Successful compiles are cached in a bounded LRU so repeated calls
|
|
84
|
+
* never re-enter the regex compiler.
|
|
85
|
+
*
|
|
86
|
+
* These are a floor, not a ceiling. Hosts that accept user-supplied
|
|
87
|
+
* patterns should still validate upstream. The design report §3.8 routes
|
|
88
|
+
* persistable hooks through a host-side compiler before they reach this
|
|
89
|
+
* module.
|
|
90
|
+
*/
|
|
91
|
+
export declare function matchesQuery(pattern: string | undefined, query: string | undefined): boolean;
|
|
92
|
+
/** Clears the regex compilation cache. Intended for test isolation. */
|
|
93
|
+
export declare function clearMatcherCache(): void;
|
|
94
|
+
/** Returns the current size of the compilation cache. Intended for tests. */
|
|
95
|
+
export declare function getMatcherCacheSize(): number;
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import type { BaseMessage } from '@langchain/core/messages';
|
|
2
|
+
/**
|
|
3
|
+
* Closed set of hook lifecycle events supported by the hooks system.
|
|
4
|
+
*
|
|
5
|
+
* These mirror the subset of Claude Code's event surface that makes sense
|
|
6
|
+
* for a library context (no filesystem/CLI-specific events). See
|
|
7
|
+
* `docs/hooks-design-report.md` §3.2 for the mapping to existing
|
|
8
|
+
* `@librechat/agents` emission points.
|
|
9
|
+
*/
|
|
10
|
+
export declare const HOOK_EVENTS: readonly ["RunStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionDenied", "SubagentStart", "SubagentStop", "Stop", "StopFailure", "PreCompact", "PostCompact"];
|
|
11
|
+
export type HookEvent = (typeof HOOK_EVENTS)[number];
|
|
12
|
+
/** Tool-gating decision; executeHooks folds with `deny > ask > allow` precedence. */
|
|
13
|
+
export type ToolDecision = 'allow' | 'deny' | 'ask';
|
|
14
|
+
/** Stop-loop decision; `block` means "do not stop, run another turn". Any `block` wins. */
|
|
15
|
+
export type StopDecision = 'continue' | 'block';
|
|
16
|
+
/**
|
|
17
|
+
* Fields shared by every `HookInput`. Discriminated by `hook_event_name`.
|
|
18
|
+
*
|
|
19
|
+
* - `runId` identifies the current agent run and is always present.
|
|
20
|
+
* - `threadId` identifies the conversation thread when the host has one.
|
|
21
|
+
* - `agentId` is only set when the hook fires inside a subagent scope.
|
|
22
|
+
*/
|
|
23
|
+
export interface BaseHookInput {
|
|
24
|
+
runId: string;
|
|
25
|
+
threadId?: string;
|
|
26
|
+
agentId?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface RunStartHookInput extends BaseHookInput {
|
|
29
|
+
hook_event_name: 'RunStart';
|
|
30
|
+
messages: BaseMessage[];
|
|
31
|
+
}
|
|
32
|
+
export interface UserPromptSubmitHookInput extends BaseHookInput {
|
|
33
|
+
hook_event_name: 'UserPromptSubmit';
|
|
34
|
+
prompt: string;
|
|
35
|
+
attachments?: BaseMessage[];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Fires before a tool is invoked. Hook may return `deny`/`ask`/`allow` and/or
|
|
39
|
+
* an `updatedInput` that replaces the tool arguments before invocation.
|
|
40
|
+
*
|
|
41
|
+
* `toolInput` is intentionally typed as `Record<string, unknown>` because the
|
|
42
|
+
* SDK is tool-agnostic — concrete tool argument shapes are only known at the
|
|
43
|
+
* call site and are narrowed by the host. This is the one escape hatch in
|
|
44
|
+
* the hook type system.
|
|
45
|
+
*/
|
|
46
|
+
export interface PreToolUseHookInput extends BaseHookInput {
|
|
47
|
+
hook_event_name: 'PreToolUse';
|
|
48
|
+
toolName: string;
|
|
49
|
+
toolInput: Record<string, unknown>;
|
|
50
|
+
toolUseId: string;
|
|
51
|
+
stepId?: string;
|
|
52
|
+
/**
|
|
53
|
+
* Number of times this tool has been invoked in prior batches within the
|
|
54
|
+
* current run. Within a single batch of parallel calls, all calls to the
|
|
55
|
+
* same tool share the same turn value — per-call discrimination within a
|
|
56
|
+
* batch is not supported in v1.
|
|
57
|
+
*/
|
|
58
|
+
turn?: number;
|
|
59
|
+
}
|
|
60
|
+
export interface PostToolUseHookInput extends BaseHookInput {
|
|
61
|
+
hook_event_name: 'PostToolUse';
|
|
62
|
+
toolName: string;
|
|
63
|
+
toolInput: Record<string, unknown>;
|
|
64
|
+
toolOutput: unknown;
|
|
65
|
+
toolUseId: string;
|
|
66
|
+
stepId?: string;
|
|
67
|
+
turn?: number;
|
|
68
|
+
}
|
|
69
|
+
export interface PostToolUseFailureHookInput extends BaseHookInput {
|
|
70
|
+
hook_event_name: 'PostToolUseFailure';
|
|
71
|
+
toolName: string;
|
|
72
|
+
toolInput: Record<string, unknown>;
|
|
73
|
+
toolUseId: string;
|
|
74
|
+
error: string;
|
|
75
|
+
stepId?: string;
|
|
76
|
+
turn?: number;
|
|
77
|
+
}
|
|
78
|
+
export interface PermissionDeniedHookInput extends BaseHookInput {
|
|
79
|
+
hook_event_name: 'PermissionDenied';
|
|
80
|
+
toolName: string;
|
|
81
|
+
toolInput: Record<string, unknown>;
|
|
82
|
+
toolUseId: string;
|
|
83
|
+
reason: string;
|
|
84
|
+
}
|
|
85
|
+
export interface SubagentStartHookInput extends BaseHookInput {
|
|
86
|
+
hook_event_name: 'SubagentStart';
|
|
87
|
+
parentAgentId?: string;
|
|
88
|
+
agentId: string;
|
|
89
|
+
agentType: string;
|
|
90
|
+
inputs: BaseMessage[];
|
|
91
|
+
}
|
|
92
|
+
export interface SubagentStopHookInput extends BaseHookInput {
|
|
93
|
+
hook_event_name: 'SubagentStop';
|
|
94
|
+
agentId: string;
|
|
95
|
+
agentType: string;
|
|
96
|
+
messages: BaseMessage[];
|
|
97
|
+
}
|
|
98
|
+
export interface StopHookInput extends BaseHookInput {
|
|
99
|
+
hook_event_name: 'Stop';
|
|
100
|
+
messages: BaseMessage[];
|
|
101
|
+
stopReason?: string;
|
|
102
|
+
stopHookActive: boolean;
|
|
103
|
+
}
|
|
104
|
+
export interface StopFailureHookInput extends BaseHookInput {
|
|
105
|
+
hook_event_name: 'StopFailure';
|
|
106
|
+
error: string;
|
|
107
|
+
lastAssistantMessage?: BaseMessage;
|
|
108
|
+
}
|
|
109
|
+
export interface PreCompactHookInput extends BaseHookInput {
|
|
110
|
+
hook_event_name: 'PreCompact';
|
|
111
|
+
messagesBeforeCount: number;
|
|
112
|
+
/**
|
|
113
|
+
* What triggered compaction. Matches `SummarizationTrigger.type` from the
|
|
114
|
+
* agent's summarization config. `'default'` means no trigger was
|
|
115
|
+
* configured and compaction fired because messages were pruned.
|
|
116
|
+
*/
|
|
117
|
+
trigger: 'token_ratio' | 'remaining_tokens' | 'messages_to_refine' | 'default' | (string & {});
|
|
118
|
+
}
|
|
119
|
+
export interface PostCompactHookInput extends BaseHookInput {
|
|
120
|
+
hook_event_name: 'PostCompact';
|
|
121
|
+
summary: string;
|
|
122
|
+
/**
|
|
123
|
+
* Number of messages remaining after compaction. The summarize node
|
|
124
|
+
* returns a `removeAll` signal that clears all messages from state;
|
|
125
|
+
* the summary itself is injected into the system prompt, not as a
|
|
126
|
+
* message. This is `0` at the point of hook dispatch.
|
|
127
|
+
*/
|
|
128
|
+
messagesAfterCount: number;
|
|
129
|
+
}
|
|
130
|
+
/** Discriminated union of every hook input shape. */
|
|
131
|
+
export type HookInput = RunStartHookInput | UserPromptSubmitHookInput | PreToolUseHookInput | PostToolUseHookInput | PostToolUseFailureHookInput | PermissionDeniedHookInput | SubagentStartHookInput | SubagentStopHookInput | StopHookInput | StopFailureHookInput | PreCompactHookInput | PostCompactHookInput;
|
|
132
|
+
/** Compile-time map from event name to its input shape. */
|
|
133
|
+
export type HookInputByEvent = {
|
|
134
|
+
RunStart: RunStartHookInput;
|
|
135
|
+
UserPromptSubmit: UserPromptSubmitHookInput;
|
|
136
|
+
PreToolUse: PreToolUseHookInput;
|
|
137
|
+
PostToolUse: PostToolUseHookInput;
|
|
138
|
+
PostToolUseFailure: PostToolUseFailureHookInput;
|
|
139
|
+
PermissionDenied: PermissionDeniedHookInput;
|
|
140
|
+
SubagentStart: SubagentStartHookInput;
|
|
141
|
+
SubagentStop: SubagentStopHookInput;
|
|
142
|
+
Stop: StopHookInput;
|
|
143
|
+
StopFailure: StopFailureHookInput;
|
|
144
|
+
PreCompact: PreCompactHookInput;
|
|
145
|
+
PostCompact: PostCompactHookInput;
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Fields common to every hook output. Hooks that have nothing to say simply
|
|
149
|
+
* return `{}` (or omit the fields below).
|
|
150
|
+
*/
|
|
151
|
+
export interface BaseHookOutput {
|
|
152
|
+
/** Context string to inject into the conversation. Accumulated across hooks. */
|
|
153
|
+
additionalContext?: string;
|
|
154
|
+
/** True to prevent the next model turn. Any hook can set this. */
|
|
155
|
+
preventContinuation?: boolean;
|
|
156
|
+
/** Reason reported alongside `preventContinuation`. */
|
|
157
|
+
stopReason?: string;
|
|
158
|
+
}
|
|
159
|
+
export type RunStartHookOutput = BaseHookOutput;
|
|
160
|
+
export interface UserPromptSubmitHookOutput extends BaseHookOutput {
|
|
161
|
+
decision?: ToolDecision;
|
|
162
|
+
reason?: string;
|
|
163
|
+
}
|
|
164
|
+
export interface PreToolUseHookOutput extends BaseHookOutput {
|
|
165
|
+
decision?: ToolDecision;
|
|
166
|
+
reason?: string;
|
|
167
|
+
/**
|
|
168
|
+
* Replacement tool input. Merged into the pending tool call by the host.
|
|
169
|
+
*
|
|
170
|
+
* When multiple hooks set `updatedInput` within a single `executeHooks`
|
|
171
|
+
* call, the last writer in registration order wins (outer loop: matcher
|
|
172
|
+
* registration order; inner loop: hook position within the matcher). The
|
|
173
|
+
* winner is deterministic — `Promise.all` preserves input-array order.
|
|
174
|
+
* Consumers that need a single authoritative rewrite should still scope
|
|
175
|
+
* `updatedInput` to one hook per matcher to avoid confusing precedence.
|
|
176
|
+
*/
|
|
177
|
+
updatedInput?: Record<string, unknown>;
|
|
178
|
+
}
|
|
179
|
+
export interface PostToolUseHookOutput extends BaseHookOutput {
|
|
180
|
+
/**
|
|
181
|
+
* Replacement tool output. Flows through the aggregated result so the
|
|
182
|
+
* host can substitute it before appending the tool result message.
|
|
183
|
+
* Ordering semantics match `PreToolUseHookOutput.updatedInput`:
|
|
184
|
+
* last-writer-wins in registration order.
|
|
185
|
+
*/
|
|
186
|
+
updatedOutput?: unknown;
|
|
187
|
+
}
|
|
188
|
+
export type PostToolUseFailureHookOutput = BaseHookOutput;
|
|
189
|
+
export type PermissionDeniedHookOutput = BaseHookOutput;
|
|
190
|
+
export interface SubagentStartHookOutput extends BaseHookOutput {
|
|
191
|
+
decision?: ToolDecision;
|
|
192
|
+
reason?: string;
|
|
193
|
+
}
|
|
194
|
+
export type SubagentStopHookOutput = BaseHookOutput;
|
|
195
|
+
export interface StopHookOutput extends BaseHookOutput {
|
|
196
|
+
decision?: StopDecision;
|
|
197
|
+
reason?: string;
|
|
198
|
+
}
|
|
199
|
+
export type StopFailureHookOutput = BaseHookOutput;
|
|
200
|
+
export type PreCompactHookOutput = BaseHookOutput;
|
|
201
|
+
export type PostCompactHookOutput = BaseHookOutput;
|
|
202
|
+
/** Compile-time map from event name to its output shape. */
|
|
203
|
+
export type HookOutputByEvent = {
|
|
204
|
+
RunStart: RunStartHookOutput;
|
|
205
|
+
UserPromptSubmit: UserPromptSubmitHookOutput;
|
|
206
|
+
PreToolUse: PreToolUseHookOutput;
|
|
207
|
+
PostToolUse: PostToolUseHookOutput;
|
|
208
|
+
PostToolUseFailure: PostToolUseFailureHookOutput;
|
|
209
|
+
PermissionDenied: PermissionDeniedHookOutput;
|
|
210
|
+
SubagentStart: SubagentStartHookOutput;
|
|
211
|
+
SubagentStop: SubagentStopHookOutput;
|
|
212
|
+
Stop: StopHookOutput;
|
|
213
|
+
StopFailure: StopFailureHookOutput;
|
|
214
|
+
PreCompact: PreCompactHookOutput;
|
|
215
|
+
PostCompact: PostCompactHookOutput;
|
|
216
|
+
};
|
|
217
|
+
/** Superset output shape used by the executor's fold loop. */
|
|
218
|
+
export type HookOutput = RunStartHookOutput | UserPromptSubmitHookOutput | PreToolUseHookOutput | PostToolUseHookOutput | PostToolUseFailureHookOutput | PermissionDeniedHookOutput | SubagentStartHookOutput | SubagentStopHookOutput | StopHookOutput | StopFailureHookOutput | PreCompactHookOutput | PostCompactHookOutput;
|
|
219
|
+
/**
|
|
220
|
+
* A hook callback is a plain async function registered against a specific
|
|
221
|
+
* event. The `signal` is always supplied by `executeHooks` and combines the
|
|
222
|
+
* batch's parent signal with the per-hook timeout — callbacks that perform
|
|
223
|
+
* long-running work should observe it.
|
|
224
|
+
*/
|
|
225
|
+
export type HookCallback<E extends HookEvent = HookEvent> = (input: HookInputByEvent[E], signal: AbortSignal) => HookOutputByEvent[E] | Promise<HookOutputByEvent[E]>;
|
|
226
|
+
/**
|
|
227
|
+
* A matcher groups one or more callbacks under a shared regex filter and
|
|
228
|
+
* shared timeout/once/internal flags. The generic `E` ties the callback
|
|
229
|
+
* types to the event the matcher is registered against.
|
|
230
|
+
*/
|
|
231
|
+
export interface HookMatcher<E extends HookEvent = HookEvent> {
|
|
232
|
+
/**
|
|
233
|
+
* Regex pattern matched against the event's primary query string (e.g.
|
|
234
|
+
* the tool name for `PreToolUse`, the agent type for `SubagentStart`).
|
|
235
|
+
*
|
|
236
|
+
* Omitted or empty means "always match". For events that do not supply a
|
|
237
|
+
* query string (`RunStart`, `Stop`, etc.), only wildcard matchers fire —
|
|
238
|
+
* a non-empty pattern on such events will never match.
|
|
239
|
+
*
|
|
240
|
+
* Patterns are treated as trusted input: `executeHooks` compiles them
|
|
241
|
+
* with `new RegExp(pattern)` without any sandbox, and a pathological
|
|
242
|
+
* pattern can block the event loop. Host registration code is expected
|
|
243
|
+
* to validate or length-bound patterns that originate from user input.
|
|
244
|
+
*/
|
|
245
|
+
pattern?: string;
|
|
246
|
+
/** Callbacks that fire when the matcher hits. Executed in parallel. */
|
|
247
|
+
hooks: HookCallback<E>[];
|
|
248
|
+
/** Per-matcher timeout in ms. Defaults to the executor's batch timeout. */
|
|
249
|
+
timeout?: number;
|
|
250
|
+
/**
|
|
251
|
+
* Atomically remove the matcher before its first dispatch.
|
|
252
|
+
*
|
|
253
|
+
* `executeHooks` claims `once: true` matchers synchronously — between
|
|
254
|
+
* `getMatchers` and its first `await` — so two concurrent calls cannot
|
|
255
|
+
* both dispatch the same matcher. Whichever call runs its sync prefix
|
|
256
|
+
* first wins the matcher; the other sees an empty bucket.
|
|
257
|
+
*
|
|
258
|
+
* Semantics are "at most one dispatch, ever" — if every hook in the
|
|
259
|
+
* matcher throws, the matcher is still gone. Use `once` for
|
|
260
|
+
* fire-and-forget bootstrapping (registration, telemetry, setup). Hosts
|
|
261
|
+
* that need retry semantics should register a normal matcher and
|
|
262
|
+
* self-unregister via the callback returned from `registry.register`.
|
|
263
|
+
*/
|
|
264
|
+
once?: boolean;
|
|
265
|
+
/** Internal hooks are excluded from telemetry and non-fatal error logging. */
|
|
266
|
+
internal?: boolean;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Storage shape for matchers keyed by event. Each event's matcher list is
|
|
270
|
+
* a generic array parameterized by that event type, so lookup via
|
|
271
|
+
* `HooksByEvent[E]` preserves type-safe callback signatures.
|
|
272
|
+
*/
|
|
273
|
+
export type HooksByEvent = {
|
|
274
|
+
[E in HookEvent]?: HookMatcher<E>[];
|
|
275
|
+
};
|
|
276
|
+
/**
|
|
277
|
+
* Aggregated result of a single `executeHooks` call. Fields are populated
|
|
278
|
+
* according to the fold rules in `executeHooks.ts`.
|
|
279
|
+
*/
|
|
280
|
+
export interface AggregatedHookResult {
|
|
281
|
+
/** Folded tool-gating decision; `deny > ask > allow`. */
|
|
282
|
+
decision?: ToolDecision;
|
|
283
|
+
/** Folded stop decision; any `block` wins. */
|
|
284
|
+
stopDecision?: StopDecision;
|
|
285
|
+
/** Reason from the hook that set the winning decision. */
|
|
286
|
+
reason?: string;
|
|
287
|
+
/**
|
|
288
|
+
* Replacement tool input from a `PreToolUse` hook.
|
|
289
|
+
*
|
|
290
|
+
* Last-writer-wins in **registration order**: `executeHooks` uses
|
|
291
|
+
* `Promise.all`, which preserves input-array order, so the fold iterates
|
|
292
|
+
* outcomes in the same order they were pushed — outer loop over matchers
|
|
293
|
+
* as they sit in the registry, inner loop over each matcher's `hooks`
|
|
294
|
+
* array. The winner is therefore deterministic but may not match the
|
|
295
|
+
* order in which hooks actually completed. Consumers that want a single
|
|
296
|
+
* authoritative rewrite should still register one `updatedInput`-setting
|
|
297
|
+
* hook per matcher to avoid subtle precedence bugs.
|
|
298
|
+
*/
|
|
299
|
+
updatedInput?: Record<string, unknown>;
|
|
300
|
+
/**
|
|
301
|
+
* Replacement tool output from a `PostToolUse` hook.
|
|
302
|
+
*
|
|
303
|
+
* Same last-writer-wins-in-registration-order semantics as
|
|
304
|
+
* `updatedInput`. Present only when at least one hook set it; `undefined`
|
|
305
|
+
* means "use the original tool output".
|
|
306
|
+
*/
|
|
307
|
+
updatedOutput?: unknown;
|
|
308
|
+
/** Accumulated `additionalContext` strings from every hook, in order. */
|
|
309
|
+
additionalContexts: string[];
|
|
310
|
+
/** True if any hook returned `preventContinuation`. */
|
|
311
|
+
preventContinuation?: boolean;
|
|
312
|
+
/**
|
|
313
|
+
* Reason recorded alongside `preventContinuation`. First winner wins:
|
|
314
|
+
* once a hook sets both flags, later hooks that also set
|
|
315
|
+
* `preventContinuation` do not overwrite the reason.
|
|
316
|
+
*/
|
|
317
|
+
stopReason?: string;
|
|
318
|
+
/** Error messages from hooks that threw; always present (possibly empty). */
|
|
319
|
+
errors: string[];
|
|
320
|
+
}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -7,7 +7,14 @@ export * from './graphs';
|
|
|
7
7
|
export * from './summarization';
|
|
8
8
|
export * from './tools/Calculator';
|
|
9
9
|
export * from './tools/CodeExecutor';
|
|
10
|
+
export * from './tools/BashExecutor';
|
|
10
11
|
export * from './tools/ProgrammaticToolCalling';
|
|
12
|
+
export * from './tools/BashProgrammaticToolCalling';
|
|
13
|
+
export * from './tools/SkillTool';
|
|
14
|
+
export * from './tools/SubagentTool';
|
|
15
|
+
export * from './tools/subagent';
|
|
16
|
+
export * from './tools/ReadFile';
|
|
17
|
+
export * from './tools/skillCatalog';
|
|
11
18
|
export * from './tools/ToolSearch';
|
|
12
19
|
export * from './tools/ToolNode';
|
|
13
20
|
export * from './tools/schema';
|
|
@@ -15,6 +22,7 @@ export * from './tools/handlers';
|
|
|
15
22
|
export * from './tools/search';
|
|
16
23
|
export * from './common';
|
|
17
24
|
export * from './utils';
|
|
25
|
+
export * from './hooks';
|
|
18
26
|
export type * from './types';
|
|
19
27
|
export { CustomOpenAIClient } from './llm/openai';
|
|
20
28
|
export { ChatOpenRouter } from './llm/openrouter';
|
|
@@ -104,9 +104,10 @@ export declare const labelContentByAgent: (contentParts: MessageContentComplex[]
|
|
|
104
104
|
* @param payload - The array of messages to format.
|
|
105
105
|
* @param indexTokenCountMap - Optional map of message indices to token counts.
|
|
106
106
|
* @param tools - Optional set of tool names that are allowed in the request.
|
|
107
|
+
* @param skills - Optional map of skill name to body for reconstructing skill HumanMessages.
|
|
107
108
|
* @returns - Object containing formatted messages and updated indexTokenCountMap if provided.
|
|
108
109
|
*/
|
|
109
|
-
export declare const formatAgentMessages: (payload: TPayload, indexTokenCountMap?: Record<number, number | undefined>, tools?: Set<string>) => {
|
|
110
|
+
export declare const formatAgentMessages: (payload: TPayload, indexTokenCountMap?: Record<number, number | undefined>, tools?: Set<string>, skills?: Map<string, string>) => {
|
|
110
111
|
messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;
|
|
111
112
|
indexTokenCountMap?: Record<number, number>;
|
|
112
113
|
/** Cross-run summary extracted from the payload. Should be forwarded to the
|
package/dist/types/run.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ export declare class Run<_T extends t.BaseGraphState> {
|
|
|
9
9
|
id: string;
|
|
10
10
|
private tokenCounter?;
|
|
11
11
|
private handlerRegistry?;
|
|
12
|
+
private hookRegistry?;
|
|
13
|
+
private toolOutputReferences?;
|
|
12
14
|
private indexTokenCountMap?;
|
|
13
15
|
calibrationRatio: number;
|
|
14
16
|
graphRunnable?: t.CompiledStateWorkflow;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
2
2
|
import type { BaseMessage } from '@langchain/core/messages';
|
|
3
3
|
import type { AgentContext } from '@/agents/AgentContext';
|
|
4
|
+
import type { HookRegistry } from '@/hooks';
|
|
4
5
|
import type * as t from '@/types';
|
|
5
6
|
/** Structured checkpoint prompt for fresh summarization (no prior summary). */
|
|
6
7
|
export declare const DEFAULT_SUMMARIZATION_PROMPT = "Hold on, before you continue I need you to write me a checkpoint of everything so far. Your context window is filling up and this checkpoint replaces the messages above, so capture everything you need to pick right back up.\n\nDon't second-guess or fact-check anything you did, your tool results reflect exactly what happened. If a tool result appears truncated, that's just a display artifact from context management: the tool executed fully. Just record what you did and what you observed. Only the checkpoint, don't respond to me or continue the conversation.\n\n## Checkpoint\n\n## Goal\nWhat I asked you to do and any sub-goals you identified.\n\n## Constraints & Preferences\nAny rules, preferences, or configuration I established.\n\n## Progress\n### Done\n- What you completed and the outcomes\n\n### In Progress\n- What you're currently working on\n\n## Key Decisions\nDecisions you made and why.\n\n## Next Steps\nConcrete task actions remaining, in priority order.\n\n## Critical Context\nExact identifiers, names, error messages, URLs, and details you need to preserve verbatim.\n\nRules:\n- Record what you did and observed, don't judge or re-evaluate it\n- For each tool call: the tool name, key inputs, and the outcome\n- Preserve exact identifiers, names, errors, and references verbatim\n- Short declarative sentences\n- Skip empty sections";
|
|
@@ -14,6 +15,7 @@ interface CreateSummarizeNodeParams {
|
|
|
14
15
|
config?: RunnableConfig;
|
|
15
16
|
runId?: string;
|
|
16
17
|
isMultiAgent: boolean;
|
|
18
|
+
hookRegistry?: HookRegistry;
|
|
17
19
|
dispatchRunStep: (runStep: t.RunStep, config?: RunnableConfig) => Promise<void>;
|
|
18
20
|
dispatchRunStepCompleted: (stepId: string, result: t.StepCompleted, config?: RunnableConfig) => Promise<void>;
|
|
19
21
|
};
|