nexus-ai-pro 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/API_STABILITY.md +39 -0
  2. package/CHANGELOG.md +142 -1
  3. package/README.md +10 -5
  4. package/dist/agent/capabilities.d.ts +39 -0
  5. package/dist/agent/capabilities.js +36 -0
  6. package/dist/agent/create-agent.d.ts +61 -11
  7. package/dist/agent/create-agent.js +136 -22
  8. package/dist/agent/index.d.ts +3 -2
  9. package/dist/agent/index.js +1 -1
  10. package/dist/agent/middleware/approval.d.ts +26 -0
  11. package/dist/agent/middleware/approval.js +23 -0
  12. package/dist/agent/{middleware.d.ts → middleware/basic.d.ts} +5 -4
  13. package/dist/agent/{middleware.js → middleware/basic.js} +3 -5
  14. package/dist/agent/middleware/context-editor.d.ts +52 -0
  15. package/dist/agent/middleware/context-editor.js +66 -0
  16. package/dist/agent/middleware/filesystem.d.ts +44 -0
  17. package/dist/agent/middleware/filesystem.js +83 -0
  18. package/dist/agent/middleware/index.d.ts +19 -0
  19. package/dist/agent/middleware/index.js +9 -0
  20. package/dist/agent/middleware/limits.d.ts +42 -0
  21. package/dist/agent/middleware/limits.js +52 -0
  22. package/dist/agent/middleware/models.d.ts +48 -0
  23. package/dist/agent/middleware/models.js +44 -0
  24. package/dist/agent/middleware/pii.d.ts +67 -0
  25. package/dist/agent/middleware/pii.js +173 -0
  26. package/dist/agent/middleware/retry.d.ts +66 -0
  27. package/dist/agent/middleware/retry.js +59 -0
  28. package/dist/agent/middleware/shared.d.ts +41 -0
  29. package/dist/agent/middleware/shared.js +73 -0
  30. package/dist/agent/middleware/tool-selector.d.ts +64 -0
  31. package/dist/agent/middleware/tool-selector.js +106 -0
  32. package/dist/agent/permissions.d.ts +113 -0
  33. package/dist/agent/permissions.js +180 -0
  34. package/dist/agent/sandbox.d.ts +151 -0
  35. package/dist/agent/sandbox.js +257 -0
  36. package/dist/agent/tool.d.ts +8 -3
  37. package/dist/agent/tool.js +14 -3
  38. package/dist/deep-agent/index.d.ts +109 -0
  39. package/dist/deep-agent/index.js +216 -0
  40. package/dist/graph/functional.d.ts +9 -0
  41. package/dist/graph/functional.js +20 -3
  42. package/dist/graph/graph.js +25 -4
  43. package/dist/graph/lint.d.ts +4 -1
  44. package/dist/graph/lint.js +35 -0
  45. package/dist/postgres/fulltext.d.ts +67 -0
  46. package/dist/postgres/fulltext.js +91 -0
  47. package/dist/rag/elasticsearch.d.ts +71 -0
  48. package/dist/rag/elasticsearch.js +130 -0
  49. package/dist/rag/pipeline.d.ts +140 -0
  50. package/dist/rag/pipeline.js +187 -0
  51. package/dist/rag/rerankers.d.ts +92 -0
  52. package/dist/rag/rerankers.js +97 -0
  53. package/dist/rag/retrievers.d.ts +12 -1
  54. package/dist/server/assistant.d.ts +5 -1
  55. package/dist/server/assistant.js +4 -2
  56. package/dist/server/auth.d.ts +250 -0
  57. package/dist/server/auth.js +392 -0
  58. package/dist/store/memory.d.ts +10 -0
  59. package/dist/store/memory.js +10 -0
  60. package/dist/types/graph.d.ts +38 -0
  61. package/dist/types/messages.d.ts +36 -2
  62. package/dist/types/principal.d.ts +21 -0
  63. package/dist/types/principal.js +1 -0
  64. package/dist/types/server.d.ts +2 -9
  65. package/dist/utils/tenant.d.ts +11 -0
  66. package/dist/utils/tenant.js +14 -0
  67. package/dist/version.d.ts +1 -1
  68. package/dist/version.js +1 -1
  69. package/dist-cjs/agent/capabilities.d.ts +39 -0
  70. package/dist-cjs/agent/capabilities.js +41 -0
  71. package/dist-cjs/agent/create-agent.d.ts +61 -11
  72. package/dist-cjs/agent/create-agent.js +136 -22
  73. package/dist-cjs/agent/index.d.ts +3 -2
  74. package/dist-cjs/agent/index.js +4 -4
  75. package/dist-cjs/agent/middleware/approval.d.ts +26 -0
  76. package/dist-cjs/agent/middleware/approval.js +26 -0
  77. package/dist-cjs/agent/{middleware.d.ts → middleware/basic.d.ts} +5 -4
  78. package/dist-cjs/agent/{middleware.js → middleware/basic.js} +3 -5
  79. package/dist-cjs/agent/middleware/context-editor.d.ts +52 -0
  80. package/dist-cjs/agent/middleware/context-editor.js +70 -0
  81. package/dist-cjs/agent/middleware/filesystem.d.ts +44 -0
  82. package/dist-cjs/agent/middleware/filesystem.js +86 -0
  83. package/dist-cjs/agent/middleware/index.d.ts +19 -0
  84. package/dist-cjs/agent/middleware/index.js +28 -0
  85. package/dist-cjs/agent/middleware/limits.d.ts +42 -0
  86. package/dist-cjs/agent/middleware/limits.js +57 -0
  87. package/dist-cjs/agent/middleware/models.d.ts +48 -0
  88. package/dist-cjs/agent/middleware/models.js +48 -0
  89. package/dist-cjs/agent/middleware/pii.d.ts +67 -0
  90. package/dist-cjs/agent/middleware/pii.js +178 -0
  91. package/dist-cjs/agent/middleware/retry.d.ts +66 -0
  92. package/dist-cjs/agent/middleware/retry.js +63 -0
  93. package/dist-cjs/agent/middleware/shared.d.ts +41 -0
  94. package/dist-cjs/agent/middleware/shared.js +83 -0
  95. package/dist-cjs/agent/middleware/tool-selector.d.ts +64 -0
  96. package/dist-cjs/agent/middleware/tool-selector.js +109 -0
  97. package/dist-cjs/agent/permissions.d.ts +113 -0
  98. package/dist-cjs/agent/permissions.js +189 -0
  99. package/dist-cjs/agent/sandbox.d.ts +151 -0
  100. package/dist-cjs/agent/sandbox.js +297 -0
  101. package/dist-cjs/agent/tool.d.ts +8 -3
  102. package/dist-cjs/agent/tool.js +14 -3
  103. package/dist-cjs/deep-agent/index.d.ts +109 -0
  104. package/dist-cjs/deep-agent/index.js +219 -0
  105. package/dist-cjs/graph/functional.d.ts +9 -0
  106. package/dist-cjs/graph/functional.js +20 -3
  107. package/dist-cjs/graph/graph.js +25 -4
  108. package/dist-cjs/graph/lint.d.ts +4 -1
  109. package/dist-cjs/graph/lint.js +35 -0
  110. package/dist-cjs/postgres/fulltext.d.ts +67 -0
  111. package/dist-cjs/postgres/fulltext.js +129 -0
  112. package/dist-cjs/rag/elasticsearch.d.ts +71 -0
  113. package/dist-cjs/rag/elasticsearch.js +135 -0
  114. package/dist-cjs/rag/pipeline.d.ts +140 -0
  115. package/dist-cjs/rag/pipeline.js +191 -0
  116. package/dist-cjs/rag/rerankers.d.ts +92 -0
  117. package/dist-cjs/rag/rerankers.js +107 -0
  118. package/dist-cjs/rag/retrievers.d.ts +12 -1
  119. package/dist-cjs/server/assistant.d.ts +5 -1
  120. package/dist-cjs/server/assistant.js +4 -2
  121. package/dist-cjs/server/auth.d.ts +250 -0
  122. package/dist-cjs/server/auth.js +402 -0
  123. package/dist-cjs/store/memory.d.ts +10 -0
  124. package/dist-cjs/store/memory.js +10 -0
  125. package/dist-cjs/types/graph.d.ts +38 -0
  126. package/dist-cjs/types/messages.d.ts +36 -2
  127. package/dist-cjs/types/principal.d.ts +21 -0
  128. package/dist-cjs/types/principal.js +2 -0
  129. package/dist-cjs/types/server.d.ts +2 -9
  130. package/dist-cjs/utils/tenant.d.ts +11 -0
  131. package/dist-cjs/utils/tenant.js +15 -0
  132. package/dist-cjs/version.d.ts +1 -1
  133. package/dist-cjs/version.js +1 -1
  134. package/llms.txt +4 -3
  135. package/package.json +118 -1
@@ -0,0 +1,173 @@
1
+ import { shortHash } from './shared.js';
2
+ export class PiiBlockedError extends Error {
3
+ kind;
4
+ where;
5
+ code = 'PII_BLOCKED';
6
+ constructor(kind, where) {
7
+ super(`The ${where === 'input' ? 'request' : 'response'} contains ${kind}, which is blocked`);
8
+ this.kind = kind;
9
+ this.where = where;
10
+ this.name = 'PiiBlockedError';
11
+ }
12
+ }
13
+ const DETECTORS = {
14
+ secret: {
15
+ pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----|\b(?:sk-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36,}|xox[abprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35})\b/g,
16
+ },
17
+ email: { pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g },
18
+ 'credit-card': { pattern: /\b\d(?:[ -]?\d){12,18}\b/g, valid: luhn },
19
+ iban: { pattern: /\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b/g, valid: ibanChecksum },
20
+ ssn: { pattern: /\b(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b/g },
21
+ 'ip-address': { pattern: /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g },
22
+ phone: {
23
+ pattern: /(?<![\w+])\+?(?:\(\d{1,4}\)|\d{1,4})(?:[ .-]?(?:\(\d{1,4}\)|\d{2,4})){2,4}(?!\w)/g,
24
+ valid: (match) => {
25
+ const digits = match.replace(/\D/g, '').length;
26
+ return digits >= 10 && digits <= 15 && (/^\+/.test(match) || /[ .()-]/.test(match));
27
+ },
28
+ },
29
+ };
30
+ const ORDER = ['secret', 'email', 'credit-card', 'iban', 'ssn', 'ip-address', 'phone'];
31
+ export function piiMiddleware(options = {}) {
32
+ const kinds = new Set(options.kinds ?? ORDER);
33
+ const detectors = [
34
+ ...ORDER.filter((kind) => kinds.has(kind)).map((kind) => [kind, DETECTORS[kind]]),
35
+ ...Object.entries(options.patterns ?? {}).map(([kind, pattern]) => [
36
+ kind,
37
+ { pattern: pattern.flags.includes('g') ? pattern : new RegExp(pattern.source, `${pattern.flags}g`) },
38
+ ]),
39
+ ];
40
+ const apply = { input: true, output: false, toolResults: true, ...options.apply };
41
+ const strategyOf = (kind) => typeof options.strategy === 'string' ? options.strategy : (options.strategy?.[kind] ?? 'redact');
42
+ const clean = (text, where) => {
43
+ let current = text;
44
+ for (const [kind, detector] of detectors) {
45
+ const strategy = strategyOf(kind);
46
+ let blocked = false;
47
+ current = current.replace(detector.pattern, (match) => {
48
+ if (detector.valid && !detector.valid(match))
49
+ return match;
50
+ options.onDetect?.({ kind, where, strategy });
51
+ if (strategy === 'block')
52
+ blocked = true;
53
+ return replace(match, kind, strategy);
54
+ });
55
+ if (blocked)
56
+ return { blocked: kind };
57
+ }
58
+ return { text: current };
59
+ };
60
+ const cleanMessage = (message, where) => {
61
+ if (typeof message.content === 'string') {
62
+ const result = clean(message.content, where);
63
+ if ('blocked' in result)
64
+ throw new PiiBlockedError(result.blocked, where);
65
+ return result.text === message.content ? message : { ...message, content: result.text };
66
+ }
67
+ let changed = false;
68
+ const content = message.content.map((part) => {
69
+ if (part.type !== 'text')
70
+ return part;
71
+ const result = clean(part.text, where);
72
+ if ('blocked' in result)
73
+ throw new PiiBlockedError(result.blocked, where);
74
+ if (result.text === part.text)
75
+ return part;
76
+ changed = true;
77
+ return { ...part, text: result.text };
78
+ });
79
+ return changed ? { ...message, content } : message;
80
+ };
81
+ return {
82
+ name: 'pii',
83
+ beforeModel({ request }) {
84
+ if (!apply.input)
85
+ return;
86
+ return {
87
+ ...request,
88
+ messages: request.messages.map((message) => message.role === 'system' ? message : cleanMessage(message, 'input')),
89
+ };
90
+ },
91
+ afterModel({ response }) {
92
+ if (!apply.output || !response.content)
93
+ return;
94
+ const result = clean(response.content, 'output');
95
+ if ('blocked' in result)
96
+ throw new PiiBlockedError(result.blocked, 'output');
97
+ return result.text === response.content ? undefined : { ...response, content: result.text };
98
+ },
99
+ async wrapToolCall(_call, next) {
100
+ const result = await next();
101
+ if (!apply.toolResults || !result.ok)
102
+ return result;
103
+ let blocked;
104
+ const walk = (value) => {
105
+ if (blocked)
106
+ return value;
107
+ if (typeof value === 'string') {
108
+ const cleaned = clean(value, 'tool');
109
+ if ('blocked' in cleaned) {
110
+ blocked = cleaned.blocked;
111
+ return value;
112
+ }
113
+ return cleaned.text;
114
+ }
115
+ if (Array.isArray(value))
116
+ return value.map(walk);
117
+ if (isToolOutput(value)) {
118
+ const content = value.content.map((part) => part.type === 'text' ? { ...part, text: walk(part.text) } : part);
119
+ return { ...value, content };
120
+ }
121
+ if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
122
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, walk(entry)]));
123
+ }
124
+ return value;
125
+ };
126
+ const cleaned = walk(result.result);
127
+ if (blocked)
128
+ return { ok: false, error: `The tool's result was withheld: it contains ${blocked}` };
129
+ return { ...result, result: cleaned };
130
+ },
131
+ };
132
+ }
133
+ function replace(match, kind, strategy) {
134
+ if (strategy === 'mask') {
135
+ const visible = match.replace(/[^A-Za-z0-9]/g, '').slice(-4);
136
+ return `${'*'.repeat(Math.max(4, match.length - visible.length))}${visible}`;
137
+ }
138
+ if (strategy === 'hash')
139
+ return `[${kind}:${shortHash(match)}]`;
140
+ return `[${kind}]`;
141
+ }
142
+ function isToolOutput(value) {
143
+ return value?.type === 'tool_output' && Array.isArray(value.content);
144
+ }
145
+ function luhn(match) {
146
+ const digits = match.replace(/\D/g, '');
147
+ if (digits.length < 13 || digits.length > 19)
148
+ return false;
149
+ let sum = 0;
150
+ for (let index = 0; index < digits.length; index += 1) {
151
+ let digit = Number(digits[digits.length - 1 - index]);
152
+ if (index % 2 === 1) {
153
+ digit *= 2;
154
+ if (digit > 9)
155
+ digit -= 9;
156
+ }
157
+ sum += digit;
158
+ }
159
+ return sum % 10 === 0;
160
+ }
161
+ function ibanChecksum(match) {
162
+ const iban = match.replace(/ /g, '');
163
+ if (iban.length < 15 || iban.length > 34)
164
+ return false;
165
+ const rearranged = `${iban.slice(4)}${iban.slice(0, 4)}`;
166
+ let remainder = 0;
167
+ for (const char of rearranged) {
168
+ const value = /\d/.test(char) ? char : String(char.charCodeAt(0) - 55);
169
+ for (const digit of value)
170
+ remainder = (remainder * 10 + Number(digit)) % 97;
171
+ }
172
+ return remainder === 1;
173
+ }
@@ -0,0 +1,66 @@
1
+ import type { NexusResponse } from '../../types/response.js';
2
+ import type { AgentMiddleware, AgentToolCall, AgentToolResult } from '../create-agent.js';
3
+ import { type RetryBackoff } from './shared.js';
4
+ /** One retry about to happen. */
5
+ export interface RetryEvent {
6
+ /** The attempt that failed, from 1. */
7
+ attempt: number;
8
+ /** How long until the next attempt, in milliseconds. */
9
+ delayMs: number;
10
+ /** The error a model call threw, when it threw. */
11
+ error?: unknown;
12
+ /** The failed tool call's result, for a tool retry. */
13
+ result?: AgentToolResult;
14
+ /** The tool's name, for a tool retry. */
15
+ tool?: string;
16
+ }
17
+ /** Options for `modelRetry()`. */
18
+ export interface ModelRetryOptions {
19
+ /** Attempts in all, the first included. Defaults to 3. */
20
+ attempts?: number;
21
+ /** How long to wait between attempts. */
22
+ backoff?: RetryBackoff;
23
+ /**
24
+ * Whether an error is worth another attempt. Defaults to every error not marked
25
+ * `retryable: false`, such as a provider's authentication error, and never a cancellation.
26
+ */
27
+ retryOn?: (error: unknown, attempt: number) => boolean;
28
+ /** Whether a response that did arrive is tried again, such as an empty one. Defaults to never. */
29
+ retryResponse?: (response: NexusResponse, attempt: number) => boolean;
30
+ /** Called before each new attempt, for logs and metrics. */
31
+ onRetry?: (event: RetryEvent) => void;
32
+ }
33
+ /**
34
+ * Tries a failed model call again, with exponential backoff.
35
+ *
36
+ * The client already retries one provider request; this retries the agent's step as a whole, after
37
+ * the client gave up, and can retry a response that arrived but is unusable. A streamed call that
38
+ * fails halfway streams again from the start. Waits stop when the run is cancelled.
39
+ */
40
+ export declare function modelRetry(options?: ModelRetryOptions): AgentMiddleware;
41
+ /** Options for `toolRetry()`. */
42
+ export interface ToolRetryOptions {
43
+ /** Attempts in all, the first included. Defaults to 3. */
44
+ attempts?: number;
45
+ /** How long to wait between attempts. */
46
+ backoff?: RetryBackoff;
47
+ /**
48
+ * Which calls may run again: tool names, `'all'`, or a function of the call. Defaults to calls
49
+ * that are safe to repeat, whose tool declares capabilities and none of them writes, runs a
50
+ * command or code, reaches the network, or is the application's own. A call that may already have
51
+ * changed something is retried only when you say so.
52
+ */
53
+ tools?: readonly string[] | 'all' | ((call: AgentToolCall) => boolean);
54
+ /** Whether a result is a failure worth another attempt. Defaults to any result with `ok: false`. */
55
+ retryOn?: (result: AgentToolResult, call: AgentToolCall, attempt: number) => boolean;
56
+ /** Called before each new attempt, for logs and metrics. */
57
+ onRetry?: (event: RetryEvent) => void;
58
+ }
59
+ /**
60
+ * Runs a failed tool call again, with exponential backoff.
61
+ *
62
+ * By default only a call that cannot have changed anything is repeated: retrying a payment or a
63
+ * write that timed out after it landed would do it twice. Name the tools that are idempotent to
64
+ * retry those too.
65
+ */
66
+ export declare function toolRetry(options?: ToolRetryOptions): AgentMiddleware;
@@ -0,0 +1,59 @@
1
+ import { isSensitiveCapability } from '../capabilities.js';
2
+ import { backoffDelay, isCancellation, sleep } from './shared.js';
3
+ export function modelRetry(options = {}) {
4
+ const attempts = Math.max(1, options.attempts ?? 3);
5
+ const retryOn = options.retryOn ?? ((error) => error?.retryable !== false);
6
+ return {
7
+ name: 'model-retry',
8
+ async wrapModelCall(request, next, context) {
9
+ for (let attempt = 1;; attempt += 1) {
10
+ try {
11
+ const response = await next(request);
12
+ if (attempt < attempts && options.retryResponse?.(response, attempt)) {
13
+ const delayMs = backoffDelay(attempt, options.backoff);
14
+ options.onRetry?.({ attempt, delayMs });
15
+ await sleep(delayMs, context.signal);
16
+ continue;
17
+ }
18
+ return response;
19
+ }
20
+ catch (error) {
21
+ if (attempt >= attempts || isCancellation(error, context.signal) || !retryOn(error, attempt))
22
+ throw error;
23
+ const delayMs = backoffDelay(attempt, options.backoff);
24
+ options.onRetry?.({ attempt, delayMs, error });
25
+ await sleep(delayMs, context.signal);
26
+ }
27
+ }
28
+ },
29
+ };
30
+ }
31
+ export function toolRetry(options = {}) {
32
+ const attempts = Math.max(1, options.attempts ?? 3);
33
+ const retryOn = options.retryOn ?? ((result) => !result.ok);
34
+ const eligible = (call) => {
35
+ const tools = options.tools;
36
+ if (tools === 'all')
37
+ return true;
38
+ if (typeof tools === 'function')
39
+ return tools(call);
40
+ if (tools)
41
+ return tools.includes(call.name);
42
+ return call.capabilities !== undefined && !call.capabilities.some(isSensitiveCapability);
43
+ };
44
+ return {
45
+ name: 'tool-retry',
46
+ async wrapToolCall(call, next, context) {
47
+ if (!eligible(call))
48
+ return next();
49
+ for (let attempt = 1;; attempt += 1) {
50
+ const result = await next();
51
+ if (attempt >= attempts || context.signal.aborted || !retryOn(result, call, attempt))
52
+ return result;
53
+ const delayMs = backoffDelay(attempt, options.backoff);
54
+ options.onRetry?.({ attempt, delayMs, result, tool: call.name });
55
+ await sleep(delayMs, context.signal);
56
+ }
57
+ },
58
+ };
59
+ }
@@ -0,0 +1,41 @@
1
+ import type { Message } from '../../types/messages.js';
2
+ import type { AgentToolCall } from '../create-agent.js';
3
+ /**
4
+ * What the middleware share. Every count here is read from the transcript rather than kept in
5
+ * memory, so it survives a restart, a resumed approval, and a second process, and two threads never
6
+ * share one.
7
+ */
8
+ /**
9
+ * The current turn: every message after the latest user message. One `invoke()` is one turn; a run
10
+ * that resumes after an approval is the same turn.
11
+ */
12
+ export declare function turnOf(messages: readonly Message[]): readonly Message[];
13
+ /** Model calls made in the current turn: its assistant messages. */
14
+ export declare function modelCallsInTurn(messages: readonly Message[]): number;
15
+ /**
16
+ * Where a call sits among the current turn's calls to the same tool, from 1. Calls the model made in
17
+ * parallel are ordered as the model listed them, so the position never depends on which finished
18
+ * first.
19
+ */
20
+ export declare function callPosition(messages: readonly Message[], call: Pick<AgentToolCall, 'id' | 'name'>): number;
21
+ /** A message's text: the string, or its text parts joined. */
22
+ export declare function textOf(content: Message['content']): string;
23
+ /** How long to wait between attempts. */
24
+ export interface RetryBackoff {
25
+ /** The wait before the second attempt, in milliseconds. Defaults to 500. */
26
+ initialMs?: number;
27
+ /** The longest wait, in milliseconds. Defaults to 10,000. */
28
+ maxMs?: number;
29
+ /** What each wait is multiplied by. Defaults to 2. */
30
+ factor?: number;
31
+ /** Spreads each wait between half and all of it, so runs that failed together retry apart. Defaults to true. */
32
+ jitter?: boolean;
33
+ }
34
+ /** The wait before attempt `attempt + 1`, after `attempt` failed. */
35
+ export declare function backoffDelay(attempt: number, backoff?: RetryBackoff): number;
36
+ /** Waits, or rejects with the signal's reason as soon as it aborts. */
37
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
38
+ /** True for a cancellation: never worth retrying or falling back from. */
39
+ export declare function isCancellation(error: unknown, signal?: AbortSignal): boolean;
40
+ /** A short, stable hash of a text: cyrb53 as 8 hex digits. Not a security boundary. */
41
+ export declare function shortHash(text: string): string;
@@ -0,0 +1,73 @@
1
+ export function turnOf(messages) {
2
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
3
+ if (messages[index]?.role === 'user')
4
+ return messages.slice(index + 1);
5
+ }
6
+ return messages;
7
+ }
8
+ export function modelCallsInTurn(messages) {
9
+ return turnOf(messages).filter((message) => message.role === 'assistant').length;
10
+ }
11
+ export function callPosition(messages, call) {
12
+ let position = 0;
13
+ for (const message of turnOf(messages)) {
14
+ for (const made of message.toolCalls ?? []) {
15
+ if (made.function.name !== call.name)
16
+ continue;
17
+ position += 1;
18
+ if (made.id === call.id)
19
+ return position;
20
+ }
21
+ }
22
+ return position + 1;
23
+ }
24
+ export function textOf(content) {
25
+ if (typeof content === 'string')
26
+ return content;
27
+ return content
28
+ .filter((part) => part.type === 'text')
29
+ .map((part) => part.text)
30
+ .join('\n');
31
+ }
32
+ export function backoffDelay(attempt, backoff = {}) {
33
+ const initial = backoff.initialMs ?? 500;
34
+ const delay = Math.min(backoff.maxMs ?? 10_000, initial * (backoff.factor ?? 2) ** Math.max(0, attempt - 1));
35
+ return backoff.jitter === false ? delay : delay / 2 + Math.random() * (delay / 2);
36
+ }
37
+ export function sleep(ms, signal) {
38
+ if (ms <= 0)
39
+ return signal?.aborted ? Promise.reject(signal.reason) : Promise.resolve();
40
+ return new Promise((resolve, reject) => {
41
+ if (signal?.aborted) {
42
+ reject(signal.reason);
43
+ return;
44
+ }
45
+ const onAbort = () => {
46
+ clearTimeout(timer);
47
+ reject(signal?.reason);
48
+ };
49
+ const timer = setTimeout(() => {
50
+ signal?.removeEventListener('abort', onAbort);
51
+ resolve();
52
+ }, ms);
53
+ signal?.addEventListener('abort', onAbort, { once: true });
54
+ });
55
+ }
56
+ export function isCancellation(error, signal) {
57
+ if (signal?.aborted)
58
+ return true;
59
+ const name = error?.name;
60
+ return name === 'AbortError';
61
+ }
62
+ export function shortHash(text) {
63
+ let h1 = 0xdeadbeef;
64
+ let h2 = 0x41c6ce57;
65
+ for (let index = 0; index < text.length; index += 1) {
66
+ const code = text.charCodeAt(index);
67
+ h1 = Math.imul(h1 ^ code, 2654435761);
68
+ h2 = Math.imul(h2 ^ code, 1597334677);
69
+ }
70
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
71
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
72
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0').slice(-8);
73
+ }
@@ -0,0 +1,64 @@
1
+ import type { CompletionRequest, ToolDefinition } from '../../types/messages.js';
2
+ import type { AgentMiddleware, AgentMiddlewareContext } from '../create-agent.js';
3
+ /** What a rule chooses tools from. */
4
+ export interface ToolSelectionContext extends AgentMiddlewareContext {
5
+ /** The request about to be sent. */
6
+ request: CompletionRequest;
7
+ /** Every tool the request offers. */
8
+ tools: readonly ToolDefinition[];
9
+ /** What the turn is about: the text `query` returned. */
10
+ query: string;
11
+ }
12
+ /** Options for `toolSelector()`. Give it `select`, `embed`, or both. */
13
+ export interface ToolSelectorOptions {
14
+ /**
15
+ * A rule: the names of the tools to send. With `embed` too, the rule narrows the candidates and
16
+ * similarity ranks what is left.
17
+ */
18
+ select?: (context: ToolSelectionContext) => readonly string[] | Promise<readonly string[]>;
19
+ /**
20
+ * Embeds texts, for choosing by similarity: any embedding function, such as one from
21
+ * `toEmbeddingFunction()`. Each tool is embedded once, from `describe`; the query once per turn.
22
+ */
23
+ embed?: (texts: string[]) => Promise<readonly (readonly number[])[]> | readonly (readonly number[])[];
24
+ /** The most tools sent, `always` included. Defaults to 12. */
25
+ maxTools?: number;
26
+ /** The lowest similarity a tool needs to be sent, from -1 to 1. Defaults to none. */
27
+ minScore?: number;
28
+ /** Tools sent on every call, whatever the turn is about. */
29
+ always?: readonly string[];
30
+ /**
31
+ * Keeps every tool the model already called this turn, so a tool it is halfway through using
32
+ * never disappears from under it. Defaults to true.
33
+ */
34
+ keepUsed?: boolean;
35
+ /** What the turn is about. Defaults to the latest user message. */
36
+ query?: (context: AgentMiddlewareContext & {
37
+ request: CompletionRequest;
38
+ }) => string;
39
+ /** The text a tool is embedded from. Defaults to its name and description. */
40
+ describe?: (tool: ToolDefinition) => string;
41
+ /** Called with each selection, for logs and for measuring what the selector saves. */
42
+ onSelect?: (selection: ToolSelection) => void;
43
+ }
44
+ /** What `toolSelector()` sent for one call. */
45
+ export interface ToolSelection {
46
+ /** The query the tools were chosen for. */
47
+ query: string;
48
+ /** The names of the tools sent. */
49
+ selected: string[];
50
+ /** How many tools the request offered. */
51
+ offered: number;
52
+ /** Each ranked tool's similarity to the query, when tools were chosen by similarity. */
53
+ scores?: Record<string, number>;
54
+ }
55
+ /**
56
+ * Sends a model only the tools relevant to the turn.
57
+ *
58
+ * An agent with 150 tools otherwise sends 150 schemas on every call: the tokens are paid each time,
59
+ * the call is slower, and a model choosing among that many picks worse. A rule, embedding
60
+ * similarity, or both choose a dozen; tools named in `always`, the tool a `toolChoice` forces, and
61
+ * the tools the model already used this turn are always kept. The agent can still run every tool —
62
+ * only what the model is offered changes.
63
+ */
64
+ export declare function toolSelector(options: ToolSelectorOptions): AgentMiddleware;
@@ -0,0 +1,106 @@
1
+ import { textOf, turnOf } from './shared.js';
2
+ export function toolSelector(options) {
3
+ if (!options.select && !options.embed) {
4
+ throw new TypeError('toolSelector() needs a select rule, an embed function, or both');
5
+ }
6
+ const maxTools = Math.max(1, options.maxTools ?? 12);
7
+ const describe = options.describe ?? ((tool) => `${tool.name}: ${tool.description}`);
8
+ const vectors = new Map();
9
+ let lastQuery;
10
+ const embedTools = async (tools) => {
11
+ const missing = [...new Set(tools.map(describe).filter((text) => !vectors.has(text)))];
12
+ if (missing.length === 0 || !options.embed)
13
+ return;
14
+ const embedded = await options.embed(missing);
15
+ missing.forEach((text, index) => {
16
+ const vector = embedded[index];
17
+ if (vector)
18
+ vectors.set(text, normalize(vector));
19
+ });
20
+ };
21
+ const embedQuery = async (text) => {
22
+ if (!options.embed || !text.trim())
23
+ return undefined;
24
+ if (lastQuery?.text === text)
25
+ return lastQuery.vector;
26
+ const [vector] = await options.embed([text]);
27
+ if (!vector)
28
+ return undefined;
29
+ lastQuery = { text, vector: normalize(vector) };
30
+ return lastQuery.vector;
31
+ };
32
+ return {
33
+ name: 'tool-selector',
34
+ async beforeModel(context) {
35
+ const { request } = context;
36
+ const offered = request.tools ?? [];
37
+ if (offered.length === 0 || (!options.select && offered.length <= maxTools))
38
+ return;
39
+ const query = options.query?.(context) ?? latestUserText(context.state.messages);
40
+ const kept = new Set(options.always ?? []);
41
+ if (request.toolChoice && typeof request.toolChoice === 'object')
42
+ kept.add(request.toolChoice.name);
43
+ if (options.keepUsed !== false) {
44
+ for (const message of turnOf(context.state.messages)) {
45
+ for (const call of message.toolCalls ?? [])
46
+ kept.add(call.function.name);
47
+ }
48
+ }
49
+ let candidates = offered.filter((tool) => !kept.has(tool.name));
50
+ if (options.select) {
51
+ const chosen = new Set(await options.select({ ...context, tools: offered, query }));
52
+ candidates = candidates.filter((tool) => chosen.has(tool.name));
53
+ }
54
+ let scores;
55
+ const room = Math.max(0, maxTools - kept.size);
56
+ if (options.embed) {
57
+ const vector = await embedQuery(query);
58
+ if (vector) {
59
+ await embedTools(candidates);
60
+ scores = {};
61
+ const ranked = candidates
62
+ .map((tool) => ({ tool, score: dot(vector, vectors.get(describe(tool)) ?? []) }))
63
+ .filter((entry) => options.minScore === undefined || entry.score >= options.minScore)
64
+ .sort((left, right) => right.score - left.score);
65
+ for (const entry of ranked)
66
+ scores[entry.tool.name] = round(entry.score);
67
+ candidates = ranked.map((entry) => entry.tool);
68
+ }
69
+ }
70
+ const names = new Set([...kept, ...candidates.slice(0, room).map((tool) => tool.name)]);
71
+ const tools = offered.filter((tool) => names.has(tool.name));
72
+ options.onSelect?.({
73
+ query,
74
+ selected: tools.map((tool) => tool.name),
75
+ offered: offered.length,
76
+ ...(scores ? { scores } : {}),
77
+ });
78
+ return { ...request, tools };
79
+ },
80
+ };
81
+ }
82
+ function latestUserText(messages) {
83
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
84
+ const message = messages[index];
85
+ if (message?.role === 'user')
86
+ return textOf(message.content);
87
+ }
88
+ return '';
89
+ }
90
+ function normalize(vector) {
91
+ let norm = 0;
92
+ for (const value of vector)
93
+ norm += value * value;
94
+ norm = Math.sqrt(norm);
95
+ return norm === 0 ? vector : vector.map((value) => value / norm);
96
+ }
97
+ function dot(left, right) {
98
+ let total = 0;
99
+ const length = Math.min(left.length, right.length);
100
+ for (let index = 0; index < length; index += 1)
101
+ total += left[index] * right[index];
102
+ return total;
103
+ }
104
+ function round(value) {
105
+ return Math.round(value * 1000) / 1000;
106
+ }