nexus-ai-pro 2.2.0 → 2.4.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 (298) hide show
  1. package/API_STABILITY.md +225 -0
  2. package/CHANGELOG.md +325 -1
  3. package/README.md +20 -6
  4. package/SECURITY.md +140 -0
  5. package/dist/adapter-kit/contracts.d.ts +87 -0
  6. package/dist/adapter-kit/contracts.js +237 -0
  7. package/dist/adapter-kit/errors.d.ts +39 -0
  8. package/dist/adapter-kit/errors.js +52 -0
  9. package/dist/adapter-kit/index.d.ts +144 -0
  10. package/dist/adapter-kit/index.js +178 -0
  11. package/dist/adapter-kit/semver.d.ts +12 -0
  12. package/dist/adapter-kit/semver.js +55 -0
  13. package/dist/agent/capabilities.d.ts +39 -0
  14. package/dist/agent/capabilities.js +36 -0
  15. package/dist/agent/create-agent.d.ts +61 -11
  16. package/dist/agent/create-agent.js +136 -22
  17. package/dist/agent/index.d.ts +3 -2
  18. package/dist/agent/index.js +1 -1
  19. package/dist/agent/middleware/approval.d.ts +26 -0
  20. package/dist/agent/middleware/approval.js +23 -0
  21. package/dist/agent/{middleware.d.ts → middleware/basic.d.ts} +5 -4
  22. package/dist/agent/{middleware.js → middleware/basic.js} +3 -5
  23. package/dist/agent/middleware/context-editor.d.ts +52 -0
  24. package/dist/agent/middleware/context-editor.js +66 -0
  25. package/dist/agent/middleware/filesystem.d.ts +44 -0
  26. package/dist/agent/middleware/filesystem.js +83 -0
  27. package/dist/agent/middleware/index.d.ts +19 -0
  28. package/dist/agent/middleware/index.js +9 -0
  29. package/dist/agent/middleware/limits.d.ts +42 -0
  30. package/dist/agent/middleware/limits.js +52 -0
  31. package/dist/agent/middleware/models.d.ts +48 -0
  32. package/dist/agent/middleware/models.js +44 -0
  33. package/dist/agent/middleware/pii.d.ts +67 -0
  34. package/dist/agent/middleware/pii.js +142 -0
  35. package/dist/agent/middleware/retry.d.ts +66 -0
  36. package/dist/agent/middleware/retry.js +59 -0
  37. package/dist/agent/middleware/shared.d.ts +41 -0
  38. package/dist/agent/middleware/shared.js +73 -0
  39. package/dist/agent/middleware/tool-selector.d.ts +64 -0
  40. package/dist/agent/middleware/tool-selector.js +106 -0
  41. package/dist/agent/permissions.d.ts +113 -0
  42. package/dist/agent/permissions.js +180 -0
  43. package/dist/agent/sandbox.d.ts +151 -0
  44. package/dist/agent/sandbox.js +257 -0
  45. package/dist/agent/tool.d.ts +8 -3
  46. package/dist/agent/tool.js +14 -3
  47. package/dist/core/secure-stream.js +4 -3
  48. package/dist/deep-agent/index.d.ts +109 -0
  49. package/dist/deep-agent/index.js +216 -0
  50. package/dist/embeddings/adapters.js +2 -1
  51. package/dist/evals/judge.js +2 -5
  52. package/dist/evaluate/cache.d.ts +0 -14
  53. package/dist/evaluate/cache.js +0 -30
  54. package/dist/evaluate/file-cache.d.ts +15 -0
  55. package/dist/evaluate/file-cache.js +30 -0
  56. package/dist/evaluate/index.d.ts +2 -1
  57. package/dist/evaluate/index.js +2 -1
  58. package/dist/evaluate/review.js +2 -2
  59. package/dist/evaluate/run.js +2 -2
  60. package/dist/evaluate/version.js +3 -3
  61. package/dist/graph/functional.d.ts +9 -0
  62. package/dist/graph/functional.js +20 -3
  63. package/dist/graph/graph.js +27 -6
  64. package/dist/graph/lint.d.ts +4 -1
  65. package/dist/graph/lint.js +35 -0
  66. package/dist/graph/node-cache.js +3 -3
  67. package/dist/hallucination/rag.d.ts +4 -1
  68. package/dist/hallucination/rag.js +6 -1
  69. package/dist/images/asset-stores.js +2 -3
  70. package/dist/images/asset-support.js +2 -2
  71. package/dist/images/assets.js +1 -2
  72. package/dist/images/evals.js +4 -4
  73. package/dist/insights/proposals.js +1 -2
  74. package/dist/insights/regressions.d.ts +26 -2
  75. package/dist/insights/regressions.js +129 -3
  76. package/dist/loaders/git.js +8 -1
  77. package/dist/loaders/web.js +7 -1
  78. package/dist/mcp/client.d.ts +14 -0
  79. package/dist/mcp/client.js +59 -1
  80. package/dist/mcp/registry.d.ts +6 -0
  81. package/dist/mcp/registry.js +7 -0
  82. package/dist/postgres/fulltext.d.ts +67 -0
  83. package/dist/postgres/fulltext.js +91 -0
  84. package/dist/prompts/file.js +28 -11
  85. package/dist/protocols/a2a.d.ts +235 -0
  86. package/dist/protocols/a2a.js +386 -0
  87. package/dist/protocols/acp.d.ts +87 -0
  88. package/dist/protocols/acp.js +322 -0
  89. package/dist/protocols/ag-ui.d.ts +120 -0
  90. package/dist/protocols/ag-ui.js +180 -0
  91. package/dist/protocols/shared.d.ts +80 -0
  92. package/dist/protocols/shared.js +49 -0
  93. package/dist/providers/anthropic.js +1 -0
  94. package/dist/providers/cohere.js +2 -2
  95. package/dist/providers/google.js +2 -11
  96. package/dist/providers/openai.js +1 -0
  97. package/dist/rag/elasticsearch.d.ts +71 -0
  98. package/dist/rag/elasticsearch.js +130 -0
  99. package/dist/rag/file-ingestion.js +15 -9
  100. package/dist/rag/pipeline.d.ts +140 -0
  101. package/dist/rag/pipeline.js +187 -0
  102. package/dist/rag/rerankers.d.ts +92 -0
  103. package/dist/rag/rerankers.js +97 -0
  104. package/dist/rag/retrievers.d.ts +12 -1
  105. package/dist/runtime/detect.d.ts +17 -0
  106. package/dist/runtime/detect.js +16 -0
  107. package/dist/runtime/index.d.ts +19 -0
  108. package/dist/runtime/index.js +7 -0
  109. package/dist/security/injection-detector.d.ts +2 -0
  110. package/dist/security/injection-detector.js +7 -1
  111. package/dist/security/input-guard.js +5 -2
  112. package/dist/security/output-guard.js +8 -4
  113. package/dist/security/pii-detector.js +22 -6
  114. package/dist/security/prompt-hardening.js +6 -2
  115. package/dist/security/semantic-injection-classifier.d.ts +2 -1
  116. package/dist/security/semantic-injection-classifier.js +31 -35
  117. package/dist/security/upload-scanner.d.ts +8 -0
  118. package/dist/security/upload-scanner.js +51 -9
  119. package/dist/server/assistant.d.ts +5 -1
  120. package/dist/server/assistant.js +4 -2
  121. package/dist/server/auth.d.ts +250 -0
  122. package/dist/server/auth.js +392 -0
  123. package/dist/server/deployments.d.ts +63 -1
  124. package/dist/server/deployments.js +75 -2
  125. package/dist/server/runs.d.ts +9 -0
  126. package/dist/server/runs.js +20 -0
  127. package/dist/server/server.js +5 -0
  128. package/dist/store/memory.d.ts +10 -0
  129. package/dist/store/memory.js +10 -0
  130. package/dist/testing/record.js +2 -2
  131. package/dist/tracing/stores.js +2 -1
  132. package/dist/tracing/tracer.js +2 -2
  133. package/dist/types/config.d.ts +20 -0
  134. package/dist/types/graph.d.ts +38 -0
  135. package/dist/types/messages.d.ts +36 -2
  136. package/dist/types/principal.d.ts +21 -0
  137. package/dist/types/principal.js +1 -0
  138. package/dist/types/server.d.ts +8 -9
  139. package/dist/utils/base64.d.ts +4 -0
  140. package/dist/utils/base64.js +21 -0
  141. package/dist/utils/checksums.d.ts +22 -0
  142. package/dist/utils/checksums.js +39 -0
  143. package/dist/utils/ids.d.ts +8 -0
  144. package/dist/utils/ids.js +26 -2
  145. package/dist/utils/sha256.d.ts +22 -0
  146. package/dist/utils/sha256.js +120 -0
  147. package/dist/utils/tenant.d.ts +11 -0
  148. package/dist/utils/tenant.js +14 -0
  149. package/dist/version.d.ts +1 -1
  150. package/dist/version.js +1 -1
  151. package/dist-cjs/adapter-kit/contracts.d.ts +87 -0
  152. package/dist-cjs/adapter-kit/contracts.js +243 -0
  153. package/dist-cjs/adapter-kit/errors.d.ts +39 -0
  154. package/dist-cjs/adapter-kit/errors.js +57 -0
  155. package/dist-cjs/adapter-kit/index.d.ts +144 -0
  156. package/dist-cjs/adapter-kit/index.js +194 -0
  157. package/dist-cjs/adapter-kit/semver.d.ts +12 -0
  158. package/dist-cjs/adapter-kit/semver.js +59 -0
  159. package/dist-cjs/agent/capabilities.d.ts +39 -0
  160. package/dist-cjs/agent/capabilities.js +41 -0
  161. package/dist-cjs/agent/create-agent.d.ts +61 -11
  162. package/dist-cjs/agent/create-agent.js +136 -22
  163. package/dist-cjs/agent/index.d.ts +3 -2
  164. package/dist-cjs/agent/index.js +4 -4
  165. package/dist-cjs/agent/middleware/approval.d.ts +26 -0
  166. package/dist-cjs/agent/middleware/approval.js +26 -0
  167. package/dist-cjs/agent/{middleware.d.ts → middleware/basic.d.ts} +5 -4
  168. package/dist-cjs/agent/{middleware.js → middleware/basic.js} +3 -5
  169. package/dist-cjs/agent/middleware/context-editor.d.ts +52 -0
  170. package/dist-cjs/agent/middleware/context-editor.js +70 -0
  171. package/dist-cjs/agent/middleware/filesystem.d.ts +44 -0
  172. package/dist-cjs/agent/middleware/filesystem.js +86 -0
  173. package/dist-cjs/agent/middleware/index.d.ts +19 -0
  174. package/dist-cjs/agent/middleware/index.js +28 -0
  175. package/dist-cjs/agent/middleware/limits.d.ts +42 -0
  176. package/dist-cjs/agent/middleware/limits.js +57 -0
  177. package/dist-cjs/agent/middleware/models.d.ts +48 -0
  178. package/dist-cjs/agent/middleware/models.js +48 -0
  179. package/dist-cjs/agent/middleware/pii.d.ts +67 -0
  180. package/dist-cjs/agent/middleware/pii.js +147 -0
  181. package/dist-cjs/agent/middleware/retry.d.ts +66 -0
  182. package/dist-cjs/agent/middleware/retry.js +63 -0
  183. package/dist-cjs/agent/middleware/shared.d.ts +41 -0
  184. package/dist-cjs/agent/middleware/shared.js +83 -0
  185. package/dist-cjs/agent/middleware/tool-selector.d.ts +64 -0
  186. package/dist-cjs/agent/middleware/tool-selector.js +109 -0
  187. package/dist-cjs/agent/permissions.d.ts +113 -0
  188. package/dist-cjs/agent/permissions.js +189 -0
  189. package/dist-cjs/agent/sandbox.d.ts +151 -0
  190. package/dist-cjs/agent/sandbox.js +297 -0
  191. package/dist-cjs/agent/tool.d.ts +8 -3
  192. package/dist-cjs/agent/tool.js +14 -3
  193. package/dist-cjs/core/secure-stream.js +4 -3
  194. package/dist-cjs/deep-agent/index.d.ts +109 -0
  195. package/dist-cjs/deep-agent/index.js +219 -0
  196. package/dist-cjs/embeddings/adapters.js +2 -1
  197. package/dist-cjs/evals/judge.js +2 -5
  198. package/dist-cjs/evaluate/cache.d.ts +0 -14
  199. package/dist-cjs/evaluate/cache.js +1 -65
  200. package/dist-cjs/evaluate/file-cache.d.ts +15 -0
  201. package/dist-cjs/evaluate/file-cache.js +67 -0
  202. package/dist-cjs/evaluate/index.d.ts +2 -1
  203. package/dist-cjs/evaluate/index.js +3 -2
  204. package/dist-cjs/evaluate/review.js +2 -2
  205. package/dist-cjs/evaluate/run.js +2 -2
  206. package/dist-cjs/evaluate/version.js +3 -3
  207. package/dist-cjs/graph/functional.d.ts +9 -0
  208. package/dist-cjs/graph/functional.js +20 -3
  209. package/dist-cjs/graph/graph.js +27 -6
  210. package/dist-cjs/graph/lint.d.ts +4 -1
  211. package/dist-cjs/graph/lint.js +35 -0
  212. package/dist-cjs/graph/node-cache.js +3 -3
  213. package/dist-cjs/hallucination/rag.d.ts +4 -1
  214. package/dist-cjs/hallucination/rag.js +6 -1
  215. package/dist-cjs/images/asset-stores.js +2 -3
  216. package/dist-cjs/images/asset-support.js +2 -2
  217. package/dist-cjs/images/assets.js +1 -2
  218. package/dist-cjs/images/evals.js +4 -4
  219. package/dist-cjs/insights/proposals.js +1 -2
  220. package/dist-cjs/insights/regressions.d.ts +26 -2
  221. package/dist-cjs/insights/regressions.js +129 -3
  222. package/dist-cjs/loaders/git.js +8 -1
  223. package/dist-cjs/loaders/web.js +7 -1
  224. package/dist-cjs/mcp/client.d.ts +14 -0
  225. package/dist-cjs/mcp/client.js +60 -1
  226. package/dist-cjs/mcp/registry.d.ts +6 -0
  227. package/dist-cjs/mcp/registry.js +7 -0
  228. package/dist-cjs/postgres/fulltext.d.ts +67 -0
  229. package/dist-cjs/postgres/fulltext.js +129 -0
  230. package/dist-cjs/prompts/file.js +28 -11
  231. package/dist-cjs/protocols/a2a.d.ts +235 -0
  232. package/dist-cjs/protocols/a2a.js +393 -0
  233. package/dist-cjs/protocols/acp.d.ts +87 -0
  234. package/dist-cjs/protocols/acp.js +326 -0
  235. package/dist-cjs/protocols/ag-ui.d.ts +120 -0
  236. package/dist-cjs/protocols/ag-ui.js +186 -0
  237. package/dist-cjs/protocols/shared.d.ts +80 -0
  238. package/dist-cjs/protocols/shared.js +59 -0
  239. package/dist-cjs/providers/anthropic.js +1 -0
  240. package/dist-cjs/providers/cohere.js +2 -2
  241. package/dist-cjs/providers/google.js +3 -12
  242. package/dist-cjs/providers/openai.js +1 -0
  243. package/dist-cjs/rag/elasticsearch.d.ts +71 -0
  244. package/dist-cjs/rag/elasticsearch.js +135 -0
  245. package/dist-cjs/rag/file-ingestion.js +14 -8
  246. package/dist-cjs/rag/pipeline.d.ts +140 -0
  247. package/dist-cjs/rag/pipeline.js +191 -0
  248. package/dist-cjs/rag/rerankers.d.ts +92 -0
  249. package/dist-cjs/rag/rerankers.js +107 -0
  250. package/dist-cjs/rag/retrievers.d.ts +12 -1
  251. package/dist-cjs/runtime/detect.d.ts +17 -0
  252. package/dist-cjs/runtime/detect.js +19 -0
  253. package/dist-cjs/runtime/index.d.ts +19 -0
  254. package/dist-cjs/runtime/index.js +31 -0
  255. package/dist-cjs/security/injection-detector.d.ts +2 -0
  256. package/dist-cjs/security/injection-detector.js +7 -1
  257. package/dist-cjs/security/input-guard.js +5 -2
  258. package/dist-cjs/security/output-guard.js +8 -4
  259. package/dist-cjs/security/pii-detector.js +22 -6
  260. package/dist-cjs/security/prompt-hardening.js +6 -2
  261. package/dist-cjs/security/semantic-injection-classifier.d.ts +2 -1
  262. package/dist-cjs/security/semantic-injection-classifier.js +31 -35
  263. package/dist-cjs/security/upload-scanner.d.ts +8 -0
  264. package/dist-cjs/security/upload-scanner.js +53 -9
  265. package/dist-cjs/server/assistant.d.ts +5 -1
  266. package/dist-cjs/server/assistant.js +4 -2
  267. package/dist-cjs/server/auth.d.ts +250 -0
  268. package/dist-cjs/server/auth.js +402 -0
  269. package/dist-cjs/server/deployments.d.ts +63 -1
  270. package/dist-cjs/server/deployments.js +75 -2
  271. package/dist-cjs/server/runs.d.ts +9 -0
  272. package/dist-cjs/server/runs.js +20 -0
  273. package/dist-cjs/server/server.js +5 -0
  274. package/dist-cjs/store/memory.d.ts +10 -0
  275. package/dist-cjs/store/memory.js +10 -0
  276. package/dist-cjs/testing/record.js +2 -2
  277. package/dist-cjs/tracing/stores.js +2 -1
  278. package/dist-cjs/tracing/tracer.js +2 -2
  279. package/dist-cjs/types/config.d.ts +20 -0
  280. package/dist-cjs/types/graph.d.ts +38 -0
  281. package/dist-cjs/types/messages.d.ts +36 -2
  282. package/dist-cjs/types/principal.d.ts +21 -0
  283. package/dist-cjs/types/principal.js +2 -0
  284. package/dist-cjs/types/server.d.ts +8 -9
  285. package/dist-cjs/utils/base64.d.ts +4 -0
  286. package/dist-cjs/utils/base64.js +25 -0
  287. package/dist-cjs/utils/checksums.d.ts +22 -0
  288. package/dist-cjs/utils/checksums.js +46 -0
  289. package/dist-cjs/utils/ids.d.ts +8 -0
  290. package/dist-cjs/utils/ids.js +28 -2
  291. package/dist-cjs/utils/sha256.d.ts +22 -0
  292. package/dist-cjs/utils/sha256.js +125 -0
  293. package/dist-cjs/utils/tenant.d.ts +11 -0
  294. package/dist-cjs/utils/tenant.js +15 -0
  295. package/dist-cjs/version.d.ts +1 -1
  296. package/dist-cjs/version.js +1 -1
  297. package/llms.txt +7 -3
  298. package/package.json +193 -6
@@ -1,6 +1,7 @@
1
1
  import { appendList, counter, lastValue } from '../graph/channels.js';
2
2
  import { createGraph } from '../graph/graph.js';
3
3
  import { Command, END, Send } from '../types/graph.js';
4
+ import { capabilitiesOf } from './capabilities.js';
4
5
  import { ToolExecutor, toolMessageContent } from './tool.js';
5
6
  const agentChannels = () => ({
6
7
  messages: appendList(),
@@ -34,24 +35,47 @@ export function createAgent(options) {
34
35
  ...(options.responseFormat ? { responseFormat: options.responseFormat } : {}),
35
36
  ...(options.metadata ? { metadata: options.metadata } : {}),
36
37
  };
38
+ const hooks = hookContext(context, state, options.store);
37
39
  for (const item of middleware) {
38
- request = (await item.beforeModel?.({ request, state, store: options.store })) ?? request;
40
+ request = (await item.beforeModel?.({ ...hooks, request })) ?? request;
39
41
  }
40
- let response = options.streamTokens && options.client.stream
41
- ? await streamed(options.client.stream(request), (chunk) => context.message(chunk))
42
- : await options.client.complete(request);
43
- if (!(options.streamTokens && options.client.stream) && response.content) {
42
+ const streaming = Boolean(options.streamTokens && options.client.stream);
43
+ const send = (next) => streaming && options.client.stream
44
+ ? streamed(options.client.stream(next), (chunk) => context.message(chunk))
45
+ : options.client.complete(next);
46
+ const stops = new WeakSet();
47
+ const modelContext = {
48
+ ...hooks,
49
+ stop: (answer) => {
50
+ const stopped = stopResponse(answer, request.model);
51
+ stops.add(stopped);
52
+ return stopped;
53
+ },
54
+ };
55
+ const wrapped = middleware.reduceRight((next, item) => {
56
+ const wrap = item.wrapModelCall?.bind(item);
57
+ return wrap ? (current) => Promise.resolve(wrap(current, next, modelContext)) : next;
58
+ }, send);
59
+ let response = await wrapped(request);
60
+ const stopped = stops.has(response);
61
+ if ((!streaming || stopped) && response.content) {
44
62
  context.message({ content: response.content });
45
63
  }
46
64
  for (const item of middleware) {
47
- response = (await item.afterModel?.({ response, state, store: options.store })) ?? response;
65
+ response = (await item.afterModel?.({ ...hooks, response })) ?? response;
48
66
  }
49
67
  const assistant = {
50
68
  role: 'assistant',
51
69
  content: response.content,
52
- ...(response.toolCalls?.length ? { toolCalls: response.toolCalls } : {}),
70
+ ...(response.toolCalls?.length && !stopped ? { toolCalls: response.toolCalls } : {}),
53
71
  };
54
- const calls = response.toolCalls ?? [];
72
+ const calls = stopped ? [] : (response.toolCalls ?? []);
73
+ if (stopped) {
74
+ return new Command({
75
+ update: { messages: [assistant], iterations: 1, answer: response.content, stopReason: 'stopped' },
76
+ goto: END,
77
+ });
78
+ }
55
79
  if (calls.length === 0) {
56
80
  return new Command({
57
81
  update: { messages: [assistant], iterations: 1, answer: response.content, stopReason: 'completed' },
@@ -76,27 +100,82 @@ export function createAgent(options) {
76
100
  return { messages: [toolMessage(call, { ok: false, error: parsed.error })] };
77
101
  }
78
102
  let args = parsed.args;
79
- const description = { id: call.id, name: call.function.name, args };
103
+ const definition = executor.get(call.function.name);
104
+ const capabilities = capabilitiesOf(definition, args);
105
+ const description = {
106
+ id: call.id,
107
+ name: call.function.name,
108
+ args,
109
+ ...(capabilities ? { capabilities } : {}),
110
+ };
111
+ const refuse = (error) => {
112
+ context.tool({ phase: 'error', id: call.id, name: description.name, error });
113
+ return { messages: [toolMessage(call, { ok: false, error })] };
114
+ };
115
+ let permission;
116
+ if (options.permissions) {
117
+ const verdict = await options.permissions.decide({
118
+ tool: description.name,
119
+ args,
120
+ capabilities,
121
+ ...(context.principal ? { principal: context.principal } : {}),
122
+ });
123
+ if (verdict.decision === 'deny')
124
+ return refuse(`Permission denied: ${verdict.reason}`);
125
+ if (verdict.decision === 'ask')
126
+ permission = verdict.reason;
127
+ }
80
128
  const policy = approvals[description.name];
81
- if (policy) {
129
+ if (policy || permission) {
130
+ const asked = permission ? { ...description, permission } : description;
82
131
  const decision = context.interrupt({
83
- reason: (policy === true ? undefined : policy.reason?.(description)) ?? defaultReason(description),
84
- payload: description,
132
+ reason: (policy && policy !== true ? policy.reason?.(asked) : undefined) ??
133
+ (permission ? `${defaultReason(asked)} (${permission})` : defaultReason(asked)),
134
+ payload: asked,
85
135
  });
86
136
  const verdict = normalizeApproval(decision);
87
- if (!verdict.approved) {
88
- return {
89
- messages: [toolMessage(call, { ok: false, error: verdict.reason ?? 'A human refused this tool call' })],
90
- };
91
- }
92
- if (verdict.args)
137
+ if (!verdict.approved)
138
+ return refuse(verdict.reason ?? 'A human refused this tool call');
139
+ if (verdict.args) {
93
140
  args = verdict.args;
141
+ if (options.permissions) {
142
+ const recheck = await options.permissions.decide({
143
+ tool: description.name,
144
+ args,
145
+ capabilities: capabilitiesOf(definition, args),
146
+ });
147
+ if (recheck.decision === 'deny')
148
+ return refuse(`Permission denied: ${recheck.reason}`);
149
+ }
150
+ }
94
151
  }
95
- const run = async () => executor.execute(description.name, args);
152
+ const run = async (current) => {
153
+ if (options.permissions && current.args !== args) {
154
+ const recheck = await options.permissions.decide({
155
+ tool: description.name,
156
+ args: current.args,
157
+ capabilities: capabilitiesOf(definition, current.args),
158
+ });
159
+ if (recheck.decision === 'deny')
160
+ return { ok: false, error: `Permission denied: ${recheck.reason}` };
161
+ }
162
+ return executor.execute(description.name, current.args, {
163
+ toolCallId: call.id,
164
+ threadId: context.threadId,
165
+ ...(context.tenantId !== undefined ? { tenantId: context.tenantId } : {}),
166
+ ...(context.principal ? { principal: context.principal } : {}),
167
+ signal: context.signal,
168
+ ...(context.store ? { store: context.store } : {}),
169
+ });
170
+ };
96
171
  context.tool({ phase: 'start', id: call.id, name: description.name, args });
97
- const result = await middleware.reduceRight((next, item) => item.wrapToolCall
98
- ? () => Promise.resolve(item.wrapToolCall?.({ ...description, args }, next))
99
- : next, run)();
172
+ const hooks = hookContext(context, context.state, options.store);
173
+ const result = await middleware.reduceRight((next, item) => {
174
+ const wrap = item.wrapToolCall?.bind(item);
175
+ return wrap
176
+ ? (current) => Promise.resolve(wrap(current, (changed) => next(changed ?? current), hooks))
177
+ : next;
178
+ }, run)({ ...description, args });
100
179
  context.tool(result.ok
101
180
  ? { phase: 'result', id: call.id, name: description.name, result: result.result }
102
181
  : { phase: 'error', id: call.id, name: description.name, error: result.error ?? 'The tool failed' });
@@ -111,6 +190,12 @@ export function createAgent(options) {
111
190
  ...(options.store ? { store: options.store } : {}),
112
191
  ...(options.name ? { name: options.name } : {}),
113
192
  ...(options.lifecycle ? { lifecycle: options.lifecycle, lifecycleFamily: 'agent' } : {}),
193
+ tools: executor.list().map((definition) => ({
194
+ name: definition.name,
195
+ ...(Array.isArray(definition.capabilities) ? { capabilities: [...definition.capabilities] } : {}),
196
+ ...(typeof definition.capabilities === 'function' ? { dynamic: true } : {}),
197
+ approval: approvals[definition.name] ? 'interrupt' : options.permissions ? 'policy' : 'none',
198
+ })),
114
199
  });
115
200
  }
116
201
  export function agentAsTool(options) {
@@ -165,6 +250,35 @@ function parseArguments(raw) {
165
250
  return { ok: false, error: `Tool arguments are not valid JSON (${reason}); the tool was not run` };
166
251
  }
167
252
  }
253
+ function hookContext(context, state, store) {
254
+ return {
255
+ state,
256
+ ...((context.store ?? store) ? { store: context.store ?? store } : {}),
257
+ threadId: context.threadId,
258
+ ...(context.tenantId ? { tenantId: context.tenantId } : {}),
259
+ ...(context.principal ? { principal: context.principal } : {}),
260
+ signal: context.signal,
261
+ interrupt: (request) => context.interrupt(request),
262
+ };
263
+ }
264
+ function stopResponse(answer, model) {
265
+ return {
266
+ content: answer,
267
+ role: 'assistant',
268
+ finishReason: 'stop',
269
+ meta: {
270
+ requestId: '',
271
+ providerUsed: 'none',
272
+ modelUsed: model,
273
+ latencyMs: 0,
274
+ tokensInput: 0,
275
+ tokensOutput: 0,
276
+ tokensSaved: 0,
277
+ cacheHit: false,
278
+ guardrailsApplied: ['stopped-by-middleware'],
279
+ },
280
+ };
281
+ }
168
282
  async function streamed(chunks, onChunk) {
169
283
  let content = '';
170
284
  const toolCalls = [];
@@ -1,5 +1,6 @@
1
1
  export { AgentLoop, type AgentModelClient as AgentLoopModelClient } from './loop.js';
2
2
  export { isToolOutput, tool, ToolExecutor, toolMessageContent, toolOutput } from './tool.js';
3
- export { limitToolCalls, redactMessages, type RedactOptions, summarizeHistory, type SummarizeOptions, } from './middleware.js';
4
- export { agentAsTool, agentInput, type AgentApproval, type AgentApprovalPolicy, type AgentChannels, type AgentGraph, type AgentMiddleware, type AgentModelClient, type AgentState, type AgentStopReason, type AgentToolCall, type AgentToolResult, createAgent, type CreateAgentOptions, } from './create-agent.js';
3
+ export { limitToolCalls, redactMessages, type RedactOptions, summarizeHistory, type SummarizeOptions, } from './middleware/basic.js';
4
+ export { agentAsTool, agentInput, type AgentApproval, type AgentApprovalPolicy, type AgentChannels, type AgentGraph, type AgentMiddleware, type AgentMiddlewareContext, type AgentModelCallContext, type AgentModelClient, type AgentState, type AgentStopReason, type AgentToolCall, type AgentToolResult, createAgent, type CreateAgentOptions, } from './create-agent.js';
5
5
  export type { AgentConfig, AgentResult, AgentStep, ToolExecutionResult } from '../types/agent.js';
6
+ export type { ToolContext } from '../types/messages.js';
@@ -1,4 +1,4 @@
1
1
  export { AgentLoop } from './loop.js';
2
2
  export { isToolOutput, tool, ToolExecutor, toolMessageContent, toolOutput } from './tool.js';
3
- export { limitToolCalls, redactMessages, summarizeHistory, } from './middleware.js';
3
+ export { limitToolCalls, redactMessages, summarizeHistory, } from './middleware/basic.js';
4
4
  export { agentAsTool, agentInput, createAgent, } from './create-agent.js';
@@ -0,0 +1,26 @@
1
+ import type { AgentApproval, AgentMiddleware, AgentMiddlewareContext, AgentToolCall } from '../create-agent.js';
2
+ /** Options for `humanApproval()`. */
3
+ export interface HumanApprovalOptions {
4
+ /**
5
+ * Which calls need a person's approval. Defaults to every call whose tool declares nothing, or
6
+ * declares a capability that does anything but read.
7
+ */
8
+ when?: (call: AgentToolCall, context: AgentMiddlewareContext) => boolean;
9
+ /** The question a person sees. Defaults to naming the tool and its arguments. */
10
+ reason?: (call: AgentToolCall) => string;
11
+ /**
12
+ * Asks out of band instead of suspending the run: posts to a chat and waits for the answer, or
13
+ * applies a rule of your own. Without it, the run suspends through `interrupt()` until `resume()`
14
+ * answers, as `interruptOn` does.
15
+ */
16
+ approve?: (call: AgentToolCall, context: AgentMiddlewareContext) => AgentApproval | Promise<AgentApproval>;
17
+ }
18
+ /**
19
+ * Asks a person before a tool call runs, decided per call rather than per tool name.
20
+ *
21
+ * `interruptOn` approves every call to a named tool; this approves the calls a rule picks: a refund
22
+ * over a limit, a write outside a draft folder, anything a tool does that is not a read. An
23
+ * approver may refuse, or correct the arguments, which the permission policy then decides again.
24
+ * Put it before `toolRetry()`, so a retried call is not asked about twice.
25
+ */
26
+ export declare function humanApproval(options?: HumanApprovalOptions): AgentMiddleware;
@@ -0,0 +1,23 @@
1
+ import { isSensitiveCapability } from '../capabilities.js';
2
+ export function humanApproval(options = {}) {
3
+ const when = options.when ??
4
+ ((call) => call.capabilities === undefined || call.capabilities.some(isSensitiveCapability));
5
+ const reason = options.reason ?? ((call) => `Run tool "${call.name}" with ${JSON.stringify(call.args)}?`);
6
+ return {
7
+ name: 'human-approval',
8
+ async wrapToolCall(call, next, context) {
9
+ if (!when(call, context))
10
+ return next();
11
+ const answer = options.approve
12
+ ? await options.approve(call, context)
13
+ : context.interrupt({ reason: reason(call), payload: call });
14
+ if (answer === false || (typeof answer === 'object' && !answer.approved)) {
15
+ const why = typeof answer === 'object' && !answer.approved ? answer.reason : undefined;
16
+ return { ok: false, error: why ?? 'A person refused this tool call' };
17
+ }
18
+ return typeof answer === 'object' && answer.approved && answer.args
19
+ ? next({ ...call, args: answer.args })
20
+ : next();
21
+ },
22
+ };
23
+ }
@@ -1,5 +1,5 @@
1
- import type { Message } from '../types/messages.js';
2
- import type { AgentMiddleware } from './create-agent.js';
1
+ import type { Message } from '../../types/messages.js';
2
+ import type { AgentMiddleware } from '../create-agent.js';
3
3
  /**
4
4
  * Middleware that ships with the agent.
5
5
  *
@@ -40,9 +40,10 @@ export interface RedactOptions {
40
40
  */
41
41
  export declare function redactMessages(options: RedactOptions): AgentMiddleware;
42
42
  /**
43
- * Caps how often a tool may be called in one run.
43
+ * Caps how often a tool may be called in one run: one turn, from a user message to the answer.
44
44
  *
45
45
  * A model that loops on the same call otherwise burns the iteration budget, and with an expensive
46
- * tool it burns money too.
46
+ * tool it burns money too. Calls are counted from the transcript, so the count survives a restart
47
+ * and a resumed approval, and two threads never share one.
47
48
  */
48
49
  export declare function limitToolCalls(limits: Record<string, number>): AgentMiddleware;
@@ -1,3 +1,4 @@
1
+ import { callPosition } from './shared.js';
1
2
  export function summarizeHistory(options) {
2
3
  const keepLast = options.keepLast ?? 6;
3
4
  const triggerAfter = options.triggerAfter ?? 20;
@@ -40,18 +41,15 @@ export function redactMessages(options) {
40
41
  };
41
42
  }
42
43
  export function limitToolCalls(limits) {
43
- const counts = new Map();
44
44
  return {
45
45
  name: 'limit-tool-calls',
46
- async wrapToolCall(call, next) {
46
+ async wrapToolCall(call, next, context) {
47
47
  const limit = limits[call.name];
48
48
  if (limit === undefined)
49
49
  return next();
50
- const used = counts.get(call.name) ?? 0;
51
- if (used >= limit) {
50
+ if (callPosition(context.state.messages, call) > limit) {
52
51
  return { ok: false, error: `Tool "${call.name}" has already run ${limit} times in this run` };
53
52
  }
54
- counts.set(call.name, used + 1);
55
53
  return next();
56
54
  },
57
55
  };
@@ -0,0 +1,52 @@
1
+ import type { CompletionRequest } from '../../types/messages.js';
2
+ import type { AgentMiddleware } from '../create-agent.js';
3
+ /** One cleared result, for a custom placeholder. */
4
+ export interface ClearedToolResult {
5
+ /** The tool whose result was cleared. */
6
+ tool: string;
7
+ /** How long the result was, in characters. */
8
+ length: number;
9
+ }
10
+ /** What one edit did, for logs and for measuring what it saves. */
11
+ export interface ContextEdit {
12
+ /** Tool results cleared. */
13
+ cleared: number;
14
+ /** The request's estimated tokens before. */
15
+ tokensBefore: number;
16
+ /** And after. */
17
+ tokensAfter: number;
18
+ }
19
+ /** Options for `contextEditor()`. */
20
+ export interface ContextEditorOptions {
21
+ /** Editing starts once the request's estimated tokens pass this. Defaults to 30,000. */
22
+ triggerTokens?: number;
23
+ /** The most recent tool results, kept whole. Defaults to 3. */
24
+ keepToolResults?: number;
25
+ /**
26
+ * Results are cleared this many at a time, so the edited prefix stays the same for several calls
27
+ * and a provider's prompt cache keeps working between edits. Defaults to 5.
28
+ */
29
+ batch?: number;
30
+ /** Tools whose results are never cleared. */
31
+ exclude?: readonly string[];
32
+ /** Also empties the arguments of each call whose result is cleared, for tools that take large inputs. */
33
+ clearArguments?: boolean;
34
+ /** What a cleared result says instead. Defaults to a line naming the tool and how to get it back. */
35
+ placeholder?: string | ((cleared: ClearedToolResult) => string);
36
+ /** Estimates a request's tokens. Defaults to about four characters a token. */
37
+ estimateTokens?: (request: CompletionRequest) => number;
38
+ /** Called after each edit. */
39
+ onEdit?: (edit: ContextEdit) => void;
40
+ }
41
+ /**
42
+ * Clears old tool results from what the model is sent, once the request grows past a threshold.
43
+ *
44
+ * Tool output is most of a long agent's context, and the model rarely needs a result from twenty
45
+ * steps ago verbatim. Every result but the most recent few is replaced by a short placeholder, in
46
+ * batches, so the edited prefix stays the same between edits and a provider's prompt cache keeps
47
+ * working. Only the request changes: the transcript in state keeps every result, and checkpoints,
48
+ * events, and a later summary still see them.
49
+ */
50
+ export declare function contextEditor(options?: ContextEditorOptions): AgentMiddleware;
51
+ /** About four characters a token, over the messages, the tool calls, and the tool schemas. */
52
+ export declare function estimateRequestTokens(request: CompletionRequest): number;
@@ -0,0 +1,66 @@
1
+ import { textOf } from './shared.js';
2
+ export function contextEditor(options = {}) {
3
+ const triggerTokens = options.triggerTokens ?? 30_000;
4
+ const keep = Math.max(0, options.keepToolResults ?? 3);
5
+ const batch = Math.max(1, options.batch ?? 5);
6
+ const exclude = new Set(options.exclude ?? []);
7
+ const estimate = options.estimateTokens ?? estimateRequestTokens;
8
+ const placeholder = (cleared) => typeof options.placeholder === 'function'
9
+ ? options.placeholder(cleared)
10
+ : (options.placeholder ??
11
+ `[Cleared to save context: the result of ${cleared.tool}, ${cleared.length} characters. Call the tool again if you need it.]`);
12
+ return {
13
+ name: 'context-editor',
14
+ beforeModel({ request }) {
15
+ const tokensBefore = estimate(request);
16
+ if (tokensBefore <= triggerTokens)
17
+ return;
18
+ const names = new Map();
19
+ for (const message of request.messages) {
20
+ for (const call of message.toolCalls ?? [])
21
+ names.set(call.id, call.function.name);
22
+ }
23
+ const results = request.messages.flatMap((message, index) => (message.role === 'tool' ? [index] : []));
24
+ const eligible = Math.max(0, results.length - keep);
25
+ const count = eligible < batch ? eligible : eligible - (eligible % batch);
26
+ const clearable = new Set(results.slice(0, count).filter((index) => {
27
+ const id = request.messages[index]?.toolCallId;
28
+ return !exclude.has(names.get(id ?? '') ?? '');
29
+ }));
30
+ if (clearable.size === 0)
31
+ return;
32
+ const clearedIds = new Set();
33
+ const messages = request.messages.map((message, index) => {
34
+ if (!clearable.has(index))
35
+ return message;
36
+ const text = textOf(message.content);
37
+ const tool = names.get(message.toolCallId ?? '') ?? 'a tool';
38
+ clearedIds.add(message.toolCallId ?? '');
39
+ return { ...message, content: placeholder({ tool, length: text.length }) };
40
+ });
41
+ const edited = options.clearArguments
42
+ ? messages.map((message) => message.toolCalls?.some((call) => clearedIds.has(call.id))
43
+ ? {
44
+ ...message,
45
+ toolCalls: message.toolCalls.map((call) => clearedIds.has(call.id) ? { ...call, function: { ...call.function, arguments: '{}' } } : call),
46
+ }
47
+ : message)
48
+ : messages;
49
+ const next = { ...request, messages: edited };
50
+ options.onEdit?.({ cleared: clearable.size, tokensBefore, tokensAfter: estimate(next) });
51
+ return next;
52
+ },
53
+ };
54
+ }
55
+ export function estimateRequestTokens(request) {
56
+ let characters = 0;
57
+ for (const message of request.messages) {
58
+ characters += textOf(message.content).length + 4;
59
+ for (const call of message.toolCalls ?? [])
60
+ characters += call.function.name.length + call.function.arguments.length;
61
+ }
62
+ for (const tool of request.tools ?? []) {
63
+ characters += tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length;
64
+ }
65
+ return Math.ceil(characters / 4);
66
+ }
@@ -0,0 +1,44 @@
1
+ import type { AgentMiddleware } from '../create-agent.js';
2
+ import type { Sandbox } from '../sandbox.js';
3
+ /** Where `filesystemContext()` reads and writes: a `Sandbox`, or anything with the same file methods. */
4
+ export type FilesystemContextSource = Pick<Sandbox, 'readFile'> & Partial<Pick<Sandbox, 'writeFile' | 'listFiles'>>;
5
+ /** Where large tool results go instead of the transcript. */
6
+ export interface ContextOffloadOptions {
7
+ /** Results longer than this, in characters, are offloaded. Defaults to 20,000. */
8
+ overChars?: number;
9
+ /** The directory they are written to, inside the source. Defaults to `.context`. */
10
+ directory?: string;
11
+ /** How much of a result stays in the transcript as a preview, in characters. Defaults to 1,000. */
12
+ previewChars?: number;
13
+ /** Tools whose results are never offloaded. Defaults to `read_file`, so reading one back cannot loop. */
14
+ exclude?: readonly string[];
15
+ }
16
+ /** Options for `filesystemContext()`. */
17
+ export interface FilesystemContextOptions {
18
+ /** Where files are read from and offloaded to. */
19
+ source: FilesystemContextSource;
20
+ /**
21
+ * Files whose contents the model sees on every call, after the system prompt: project
22
+ * instructions such as `AGENTS.md`, conventions, a glossary. A missing file is skipped.
23
+ */
24
+ include?: readonly string[];
25
+ /** Lists a directory after the files, so the model knows what exists without a tool call. Needs `listFiles`. */
26
+ listing?: {
27
+ directory?: string;
28
+ maxEntries?: number;
29
+ };
30
+ /** The most characters of included files, together. Defaults to 32,000; the rest is cut. */
31
+ maxChars?: number;
32
+ /** Writes large tool results to a file and leaves a preview and the path. Needs `writeFile`. */
33
+ offload?: ContextOffloadOptions | boolean;
34
+ }
35
+ /**
36
+ * The filesystem as the agent's context: files in, large results out.
37
+ *
38
+ * Instruction files reach the model on every call without a tool call, read once per run and placed
39
+ * right after the system prompt, so the prefix a provider caches stays the same. A tool result too
40
+ * large for the context is written to a file instead, and the model reads a preview and a path it can
41
+ * open with `read_file` when it needs the rest: the transcript stays small however much a tool
42
+ * returns, and nothing is lost.
43
+ */
44
+ export declare function filesystemContext(options: FilesystemContextOptions): AgentMiddleware;
@@ -0,0 +1,83 @@
1
+ export function filesystemContext(options) {
2
+ const maxChars = options.maxChars ?? 32_000;
3
+ const offload = options.offload === true
4
+ ? {}
5
+ : options.offload === false || options.offload === undefined
6
+ ? undefined
7
+ : options.offload;
8
+ if (offload && !options.source.writeFile) {
9
+ throw new TypeError('filesystemContext() offloading needs a source with writeFile()');
10
+ }
11
+ const loaded = new Map();
12
+ const load = async () => {
13
+ const sections = [];
14
+ let budget = maxChars;
15
+ for (const file of options.include ?? []) {
16
+ if (budget <= 0)
17
+ break;
18
+ let text;
19
+ try {
20
+ text = await options.source.readFile(file);
21
+ }
22
+ catch {
23
+ continue;
24
+ }
25
+ const cut = text.length > budget ? `${text.slice(0, budget)}\n[cut: ${text.length - budget} more characters]` : text;
26
+ budget -= text.length;
27
+ sections.push(`<file path="${file}">\n${cut}\n</file>`);
28
+ }
29
+ if (options.listing && options.source.listFiles) {
30
+ try {
31
+ const entries = await options.source.listFiles(options.listing.directory ?? '.');
32
+ const max = options.listing.maxEntries ?? 200;
33
+ const shown = entries.slice(0, max).join('\n');
34
+ sections.push(`<listing directory="${options.listing.directory ?? '.'}">\n${shown}${entries.length > max ? `\n[${entries.length - max} more]` : ''}\n</listing>`);
35
+ }
36
+ catch {
37
+ }
38
+ }
39
+ return sections.length ? `Files from the workspace:\n\n${sections.join('\n\n')}` : undefined;
40
+ };
41
+ return {
42
+ name: 'filesystem-context',
43
+ async beforeModel({ request, state, threadId }) {
44
+ if (!options.include?.length && !options.listing)
45
+ return;
46
+ const turn = state.messages.filter((message) => message.role === 'user').length;
47
+ const key = `${threadId}:${turn}`;
48
+ let pending = loaded.get(key);
49
+ if (!pending) {
50
+ pending = load();
51
+ loaded.set(key, pending);
52
+ if (loaded.size > 256)
53
+ loaded.delete(loaded.keys().next().value);
54
+ }
55
+ const text = await pending;
56
+ if (!text)
57
+ return;
58
+ const systemCount = request.messages.findIndex((message) => message.role !== 'system');
59
+ const at = systemCount === -1 ? request.messages.length : systemCount;
60
+ const context = { role: 'system', content: text };
61
+ return { ...request, messages: [...request.messages.slice(0, at), context, ...request.messages.slice(at)] };
62
+ },
63
+ async wrapToolCall(call, next) {
64
+ const result = await next();
65
+ if (!offload || !result.ok || (offload.exclude ?? ['read_file']).includes(call.name))
66
+ return result;
67
+ const value = result.result;
68
+ if (value?.type === 'tool_output')
69
+ return result;
70
+ const text = typeof value === 'string' ? value : JSON.stringify(value);
71
+ if (text === undefined || text.length <= (offload.overChars ?? 20_000))
72
+ return result;
73
+ const directory = (offload.directory ?? '.context').replace(/\/+$/, '');
74
+ const file = `${directory}/${`${call.name}-${call.id}`.replace(/[^A-Za-z0-9._-]/g, '_')}.txt`;
75
+ await options.source.writeFile?.(file, text);
76
+ const preview = text.slice(0, offload.previewChars ?? 1_000);
77
+ return {
78
+ ok: true,
79
+ result: `${preview}\n\n[This result is ${text.length} characters; the first ${preview.length} are above. The whole result is in ${file}: read it with read_file when you need the rest.]`,
80
+ };
81
+ },
82
+ };
83
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Middleware for `createAgent()`, each its own import: retries, fallbacks, model choice, tool
3
+ * selection, context editing, personal data, approvals, limits, and the filesystem as context.
4
+ *
5
+ * Each is ordinary `AgentMiddleware` built on the same hooks an application's own middleware uses,
6
+ * so any of them can be read, copied, and changed. None adds a dependency, and a bundler keeps only
7
+ * the ones imported.
8
+ */
9
+ export { limitToolCalls, redactMessages, type RedactOptions, summarizeHistory, type SummarizeOptions, } from './basic.js';
10
+ export { type ClearedToolResult, type ContextEdit, contextEditor, type ContextEditorOptions, estimateRequestTokens, } from './context-editor.js';
11
+ export { type ContextOffloadOptions, filesystemContext, type FilesystemContextOptions, type FilesystemContextSource, } from './filesystem.js';
12
+ export { humanApproval, type HumanApprovalOptions } from './approval.js';
13
+ export { modelCallLimit, ModelCallLimitError, type ModelCallLimitOptions } from './limits.js';
14
+ export { type DynamicModelContext, dynamicModel, modelFallback, type ModelFallbackEvent, type ModelFallbackOptions, type ModelFallbackTarget, } from './models.js';
15
+ export { PiiBlockedError, type PiiFinding, type PiiKind, piiMiddleware, type PiiMiddlewareOptions, type PiiStrategy, type PiiWhere, } from './pii.js';
16
+ export { modelRetry, type ModelRetryOptions, type RetryEvent, toolRetry, type ToolRetryOptions } from './retry.js';
17
+ export type { RetryBackoff } from './shared.js';
18
+ export { type ToolSelection, type ToolSelectionContext, toolSelector, type ToolSelectorOptions, } from './tool-selector.js';
19
+ export type { AgentMiddleware, AgentMiddlewareContext, AgentModelCallContext, AgentToolCall, AgentToolResult, } from '../create-agent.js';
@@ -0,0 +1,9 @@
1
+ export { limitToolCalls, redactMessages, summarizeHistory, } from './basic.js';
2
+ export { contextEditor, estimateRequestTokens, } from './context-editor.js';
3
+ export { filesystemContext, } from './filesystem.js';
4
+ export { humanApproval } from './approval.js';
5
+ export { modelCallLimit, ModelCallLimitError } from './limits.js';
6
+ export { dynamicModel, modelFallback, } from './models.js';
7
+ export { PiiBlockedError, piiMiddleware, } from './pii.js';
8
+ export { modelRetry, toolRetry } from './retry.js';
9
+ export { toolSelector, } from './tool-selector.js';
@@ -0,0 +1,42 @@
1
+ import type { AgentMiddleware } from '../create-agent.js';
2
+ /** Options for `modelCallLimit()`. Set `run`, `thread`, or both. */
3
+ export interface ModelCallLimitOptions {
4
+ /** Model calls in one run: from a user message to the answer, a resumed approval included. */
5
+ run?: number;
6
+ /**
7
+ * Model calls over a thread's whole life, every run on it included. Counted in the agent's store
8
+ * when it has one, so every process shares the count and it survives a restart; otherwise in this
9
+ * process. A budget, not a lock: two runs on one thread at the same moment may each pass it once.
10
+ */
11
+ thread?: number;
12
+ /**
13
+ * What happens at a limit: `end` answers with `message` and stops with `stopReason: 'stopped'`,
14
+ * without calling the model; `error` fails the run with a `ModelCallLimitError`. Defaults to `end`.
15
+ */
16
+ onLimit?: 'end' | 'error';
17
+ /** The answer a run ends with under `end`. Defaults to a sentence naming the limit. */
18
+ message?: string;
19
+ }
20
+ /** Thrown by `modelCallLimit()` under `onLimit: 'error'`. */
21
+ export declare class ModelCallLimitError extends Error {
22
+ /** Which limit was reached. */
23
+ readonly scope: 'run' | 'thread';
24
+ /** The limit. */
25
+ readonly limit: number;
26
+ /** Always `MODEL_CALL_LIMIT`. */
27
+ readonly code = "MODEL_CALL_LIMIT";
28
+ constructor(
29
+ /** Which limit was reached. */
30
+ scope: 'run' | 'thread',
31
+ /** The limit. */
32
+ limit: number);
33
+ }
34
+ /**
35
+ * Caps the model calls of a run, of a thread, or both.
36
+ *
37
+ * `maxIterations` stops one run that keeps calling tools; this is a budget an application sets per
38
+ * run and per conversation, so a thread a user keeps coming back to cannot spend without bound. The
39
+ * run count is read from the transcript, so it survives a restart. A run that reaches a limit ends
40
+ * with an answer rather than an error, unless you ask for one.
41
+ */
42
+ export declare function modelCallLimit(options: ModelCallLimitOptions): AgentMiddleware;