@cuylabs/agent-core 0.9.0 → 0.10.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 (116) hide show
  1. package/README.md +33 -17
  2. package/dist/chunk-2O4MCSQS.js +780 -0
  3. package/dist/chunk-2TTOLHBT.js +198 -0
  4. package/dist/chunk-5FMSGQVX.js +281 -0
  5. package/dist/chunk-5NVVNXPQ.js +288 -0
  6. package/dist/{chunk-EKR6PKXU.js → chunk-6HZBHFOL.js} +3 -3
  7. package/dist/chunk-CJI7PVS2.js +58 -0
  8. package/dist/{chunk-WKHDSSXG.js → chunk-CMYN2RCB.js} +146 -46
  9. package/dist/chunk-FII65CN7.js +117 -0
  10. package/dist/{chunk-UHCJEM2E.js → chunk-ICZ66572.js} +13 -6
  11. package/dist/chunk-KYLPMBHD.js +316 -0
  12. package/dist/chunk-MXAP4UG6.js +2956 -0
  13. package/dist/{chunk-4QFNWPIF.js → chunk-N3VX7FEE.js} +35 -2
  14. package/dist/{chunk-MAZ5DY5B.js → chunk-NDZWXCBZ.js} +213 -78
  15. package/dist/{chunk-MHKK374K.js → chunk-Q742PSH3.js} +11 -27
  16. package/dist/{chunk-WGZAPU6N.js → chunk-QAL3OMI3.js} +15 -1
  17. package/dist/{chunk-UDCZ673N.js → chunk-RN6WZEUF.js} +27 -23
  18. package/dist/{chunk-ZXAKHMWH.js → chunk-ROTGCYDW.js} +22 -84
  19. package/dist/chunk-SPBFQXOT.js +0 -0
  20. package/dist/chunk-SSFBF3US.js +602 -0
  21. package/dist/chunk-SZ2XBPTW.js +8 -0
  22. package/dist/chunk-T4UIX5D7.js +115 -0
  23. package/dist/{chunk-IYWQOJMQ.js → chunk-TIHPYVAJ.js} +34 -34
  24. package/dist/{chunk-RKEW5WXI.js → chunk-TOTDGK3P.js} +1 -1
  25. package/dist/chunk-V4RFNEET.js +563 -0
  26. package/dist/chunk-VOUEJSW6.js +0 -0
  27. package/dist/{chunk-J4QDGZIA.js → chunk-WBPOZ7CL.js} +659 -275
  28. package/dist/chunk-X4VN4GIJ.js +185 -0
  29. package/dist/dispatch/index.d.ts +93 -0
  30. package/dist/dispatch/index.js +37 -0
  31. package/dist/events/index.d.ts +93 -0
  32. package/dist/events/index.js +6 -0
  33. package/dist/{runtime → execution}/index.d.ts +120 -35
  34. package/dist/{runtime → execution}/index.js +17 -11
  35. package/dist/index.d.ts +489 -115
  36. package/dist/index.js +1665 -462
  37. package/dist/inference/errors/index.js +1 -1
  38. package/dist/inference/index.d.ts +13 -21
  39. package/dist/inference/index.js +15 -12
  40. package/dist/instance-BqV2D5pc.d.ts +5723 -0
  41. package/dist/logger/index.d.ts +50 -0
  42. package/dist/logger/index.js +11 -0
  43. package/dist/mcp/index.d.ts +5 -9
  44. package/dist/mcp/index.js +2 -3
  45. package/dist/middleware/index.d.ts +10 -150
  46. package/dist/middleware/index.js +10 -2
  47. package/dist/model-messages-B4nK9D1-.d.ts +13 -0
  48. package/dist/models/index.d.ts +5 -2
  49. package/dist/models/index.js +2 -1
  50. package/dist/models/reasoning/index.js +2 -1
  51. package/dist/plugin/index.d.ts +55 -11
  52. package/dist/plugin/index.js +1 -1
  53. package/dist/profiles/index.d.ts +55 -0
  54. package/dist/{presets → profiles}/index.js +10 -10
  55. package/dist/prompt/index.d.ts +8 -13
  56. package/dist/safety/index.d.ts +109 -14
  57. package/dist/safety/index.js +59 -3
  58. package/dist/sandbox/index.d.ts +81 -0
  59. package/dist/sandbox/index.js +1 -0
  60. package/dist/skill/index.d.ts +10 -8
  61. package/dist/skill/index.js +2 -2
  62. package/dist/storage/index.d.ts +12 -4
  63. package/dist/storage/index.js +1 -1
  64. package/dist/subagents/index.d.ts +177 -0
  65. package/dist/subagents/index.js +78 -0
  66. package/dist/team/index.d.ts +544 -0
  67. package/dist/team/index.js +41 -0
  68. package/dist/tool/host/index.d.ts +41 -0
  69. package/dist/tool/host/index.js +10 -0
  70. package/dist/tool/index.d.ts +111 -21
  71. package/dist/tool/index.js +20 -13
  72. package/dist/{types-VQgymC1N.d.ts → types-Bj_J8u_W.d.ts} +44 -64
  73. package/dist/{types-CHiPh8U2.d.ts → types-C_LCeYNg.d.ts} +7 -7
  74. package/dist/types-RSCv7nQ4.d.ts +59 -0
  75. package/package.json +46 -47
  76. package/dist/builder-BgZ_j4Vs.d.ts +0 -35
  77. package/dist/chunk-5ARZJWD2.js +0 -259
  78. package/dist/chunk-DXFBQMXP.js +0 -53
  79. package/dist/chunk-H3FUYU52.js +0 -81
  80. package/dist/chunk-JLXG2SH7.js +0 -905
  81. package/dist/chunk-N7P4PN3O.js +0 -84
  82. package/dist/chunk-OFDKHNCX.js +0 -727
  83. package/dist/chunk-SDSBEQXG.js +0 -157
  84. package/dist/chunk-VEKUXUVF.js +0 -41
  85. package/dist/chunk-VNQBHPCT.js +0 -398
  86. package/dist/chunk-WWYYNWEW.js +0 -259
  87. package/dist/context/index.d.ts +0 -259
  88. package/dist/context/index.js +0 -26
  89. package/dist/events-CE72w8W4.d.ts +0 -149
  90. package/dist/host/index.d.ts +0 -45
  91. package/dist/host/index.js +0 -8
  92. package/dist/index-DQuTZ8xL.d.ts +0 -1335
  93. package/dist/messages-BYWGn8TY.d.ts +0 -110
  94. package/dist/presets/index.d.ts +0 -53
  95. package/dist/registry-DwYqsQkX.d.ts +0 -164
  96. package/dist/runner-CI-XeR16.d.ts +0 -91
  97. package/dist/scope/index.d.ts +0 -10
  98. package/dist/scope/index.js +0 -14
  99. package/dist/session-manager-KbYt2WUh.d.ts +0 -282
  100. package/dist/signal/index.d.ts +0 -28
  101. package/dist/signal/index.js +0 -6
  102. package/dist/sub-agent/index.d.ts +0 -24
  103. package/dist/sub-agent/index.js +0 -32
  104. package/dist/tool-CZWN3KbO.d.ts +0 -141
  105. package/dist/tool-DkhSCV2Y.d.ts +0 -145
  106. package/dist/tracker-DClqYqTj.d.ts +0 -96
  107. package/dist/tracking/index.d.ts +0 -111
  108. package/dist/tracking/index.js +0 -20
  109. package/dist/types-BfNpU8NS.d.ts +0 -270
  110. package/dist/types-BlOKk-Bb.d.ts +0 -330
  111. package/dist/types-BlZwmnuW.d.ts +0 -50
  112. package/dist/types-CQL-SvTn.d.ts +0 -29
  113. package/dist/types-CWm-7rvB.d.ts +0 -55
  114. package/dist/types-DTSkxakL.d.ts +0 -651
  115. package/dist/types-DmDwi2zI.d.ts +0 -339
  116. package/dist/types-YuWV4ag7.d.ts +0 -72
@@ -0,0 +1,288 @@
1
+ import {
2
+ formatApprovalDeniedReason
3
+ } from "./chunk-V4RFNEET.js";
4
+ import {
5
+ requiresToolHost
6
+ } from "./chunk-FII65CN7.js";
7
+
8
+ // src/scope/store.ts
9
+ import { AsyncLocalStorage } from "async_hooks";
10
+ import { randomUUID } from "crypto";
11
+ var scopeStore = new AsyncLocalStorage();
12
+ function cloneAttributes(attributes) {
13
+ return { ...attributes };
14
+ }
15
+ function cloneScope(scope) {
16
+ return {
17
+ ...scope,
18
+ attributes: cloneAttributes(scope.attributes)
19
+ };
20
+ }
21
+ function getStoredScope() {
22
+ return scopeStore.getStore();
23
+ }
24
+ function buildScope(options, current) {
25
+ const parent = options.parent === void 0 ? current : options.parent ?? void 0;
26
+ const id = options.id ?? randomUUID();
27
+ return {
28
+ id,
29
+ rootId: parent?.rootId ?? id,
30
+ kind: options.kind,
31
+ name: options.name,
32
+ parentId: parent?.id,
33
+ depth: (parent?.depth ?? -1) + 1,
34
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
35
+ sessionId: options.sessionId ?? parent?.sessionId,
36
+ taskId: options.taskId ?? parent?.taskId,
37
+ step: options.step ?? parent?.step,
38
+ attributes: cloneAttributes(options.attributes ?? {})
39
+ };
40
+ }
41
+ function runWithScope(scope, fn) {
42
+ return Promise.resolve(scopeStore.run(scope, fn));
43
+ }
44
+
45
+ // src/scope/run.ts
46
+ function currentScope() {
47
+ const scope = getStoredScope();
48
+ return scope ? cloneScope(scope) : void 0;
49
+ }
50
+ function snapshotScope(scope = getStoredScope()) {
51
+ return scope ? cloneScope(scope) : void 0;
52
+ }
53
+ function withinScope(options, fn) {
54
+ return runWithScope(buildScope(options, getStoredScope()), fn);
55
+ }
56
+ function restoreScope(snapshot, fn) {
57
+ if (!snapshot) {
58
+ return Promise.resolve(fn());
59
+ }
60
+ return runWithScope(cloneScope(snapshot), fn);
61
+ }
62
+ async function* streamWithinScope(options, iterable) {
63
+ const scope = buildScope(options, getStoredScope());
64
+ const iterator = await runWithScope(scope, () => iterable[Symbol.asyncIterator]());
65
+ try {
66
+ while (true) {
67
+ const next = await runWithScope(scope, () => iterator.next());
68
+ if (next.done) {
69
+ return next.value;
70
+ }
71
+ yield next.value;
72
+ }
73
+ } finally {
74
+ const returnFn = iterator.return?.bind(iterator);
75
+ if (returnFn) {
76
+ await runWithScope(scope, () => returnFn(void 0));
77
+ }
78
+ }
79
+ }
80
+
81
+ // src/types/compaction.ts
82
+ var PRUNE_PROTECTED_TOOLS = ["skill"];
83
+
84
+ // src/tracking/file-tracking.ts
85
+ function extractFilePathsFromArgs(args, meta) {
86
+ if (!meta.pathArgs || meta.pathArgs.length === 0) {
87
+ return [];
88
+ }
89
+ const paths = [];
90
+ for (const argName of meta.pathArgs) {
91
+ const value = args[argName];
92
+ if (typeof value === "string") {
93
+ paths.push(value);
94
+ } else if (Array.isArray(value)) {
95
+ for (const item of value) {
96
+ if (typeof item === "string") {
97
+ paths.push(item);
98
+ }
99
+ }
100
+ }
101
+ }
102
+ return paths;
103
+ }
104
+ function shouldCaptureBaseline(meta) {
105
+ return meta.operationType !== "read";
106
+ }
107
+
108
+ // src/types/messages.ts
109
+ function accumulateUsage(current, next) {
110
+ if (!next) return current;
111
+ if (!current) {
112
+ return {
113
+ inputTokens: next.inputTokens ?? 0,
114
+ outputTokens: next.outputTokens ?? 0,
115
+ totalTokens: next.totalTokens ?? 0,
116
+ cacheReadTokens: (next.cacheReadTokens ?? 0) || void 0,
117
+ cacheWriteTokens: (next.cacheWriteTokens ?? 0) || void 0
118
+ };
119
+ }
120
+ const cacheRead = (current.cacheReadTokens ?? 0) + (next.cacheReadTokens ?? 0);
121
+ const cacheWrite = (current.cacheWriteTokens ?? 0) + (next.cacheWriteTokens ?? 0);
122
+ return {
123
+ inputTokens: (current.inputTokens ?? 0) + (next.inputTokens ?? 0),
124
+ outputTokens: (current.outputTokens ?? 0) + (next.outputTokens ?? 0),
125
+ totalTokens: (current.totalTokens ?? 0) + (next.totalTokens ?? 0),
126
+ cacheReadTokens: cacheRead || void 0,
127
+ cacheWriteTokens: cacheWrite || void 0
128
+ };
129
+ }
130
+
131
+ // src/tool/executor.ts
132
+ import { z } from "zod";
133
+ function parseToolParams(toolName, initialized, params) {
134
+ try {
135
+ return initialized.parameters.parse(params);
136
+ } catch (error) {
137
+ if (error instanceof z.ZodError && initialized.formatValidationError) {
138
+ throw new Error(initialized.formatValidationError(error), {
139
+ cause: error
140
+ });
141
+ }
142
+ throw new Error(
143
+ `The ${toolName} tool was called with invalid arguments: ${error}.
144
+ Please rewrite the input so it satisfies the expected schema.`,
145
+ { cause: error }
146
+ );
147
+ }
148
+ }
149
+ async function executeAgentToolCall(options) {
150
+ const toolCallId = options.toolCallId ?? options.messageID;
151
+ return withinScope(
152
+ {
153
+ kind: "tool",
154
+ name: "tool-call",
155
+ sessionId: options.sessionID,
156
+ attributes: {
157
+ toolName: options.toolName,
158
+ messageId: options.messageID,
159
+ toolCallId,
160
+ agent: options.agent ?? "default"
161
+ }
162
+ },
163
+ async () => {
164
+ const initialized = options.initialized ?? await options.tool.init({ cwd: options.cwd });
165
+ const ctx = {
166
+ cwd: options.cwd,
167
+ abort: options.abort,
168
+ sessionID: options.sessionID,
169
+ ...options.turnID ? { turnID: options.turnID } : {},
170
+ messageID: options.messageID,
171
+ agent: options.agent ?? "default",
172
+ scope: snapshotScope(),
173
+ ...options.host ? { host: options.host } : {},
174
+ ...options.humanInputController ? { humanInputController: options.humanInputController } : {},
175
+ ...options.turnTracker ? { turnTracker: options.turnTracker } : {},
176
+ ...options.onEvent ? { emitEvent: options.onEvent } : {},
177
+ ...initialized.capabilities ? { toolCapabilities: initialized.capabilities } : {},
178
+ ...initialized.hostRequirements ? { hostRequirements: initialized.hostRequirements } : {},
179
+ ...initialized.permissionPatterns ? { permissionPatterns: initialized.permissionPatterns } : {},
180
+ extra: {
181
+ toolCallId
182
+ }
183
+ };
184
+ if (requiresToolHost(initialized.hostRequirements) && !options.host) {
185
+ return {
186
+ output: `Tool "${options.toolName}" requires an execution host, but none was configured.`,
187
+ capabilities: initialized.capabilities
188
+ };
189
+ }
190
+ const parsedParams = parseToolParams(
191
+ options.toolName,
192
+ initialized,
193
+ options.params
194
+ );
195
+ if (initialized.validate) {
196
+ const check = await initialized.validate(parsedParams, ctx);
197
+ if (!check.ok) {
198
+ return {
199
+ output: `Input validation failed for ${options.toolName}: ${check.reason}`,
200
+ capabilities: initialized.capabilities
201
+ };
202
+ }
203
+ }
204
+ let effectiveParams = parsedParams;
205
+ if (options.middleware?.hasMiddleware) {
206
+ const decision = await options.middleware.runBeforeToolCall(
207
+ options.toolName,
208
+ parsedParams,
209
+ ctx
210
+ );
211
+ if (decision.action === "deny") {
212
+ return {
213
+ output: decision.reason ?? formatApprovalDeniedReason(options.toolName),
214
+ ...decision.correction ? {
215
+ metadata: {
216
+ approvalCorrection: decision.correction
217
+ }
218
+ } : {},
219
+ capabilities: initialized.capabilities
220
+ };
221
+ }
222
+ if (decision.args !== void 0) {
223
+ effectiveParams = parseToolParams(
224
+ options.toolName,
225
+ initialized,
226
+ decision.args
227
+ );
228
+ if (initialized.validate) {
229
+ const check = await initialized.validate(effectiveParams, ctx);
230
+ if (!check.ok) {
231
+ return {
232
+ output: `Input validation failed for ${options.toolName}: ${check.reason}`,
233
+ capabilities: initialized.capabilities
234
+ };
235
+ }
236
+ }
237
+ }
238
+ }
239
+ if (options.turnTracker && initialized.fileOps && shouldCaptureBaseline(initialized.fileOps)) {
240
+ const paths = extractFilePathsFromArgs(
241
+ effectiveParams,
242
+ initialized.fileOps
243
+ );
244
+ for (const path of paths) {
245
+ await options.turnTracker.beforeWrite(path);
246
+ }
247
+ }
248
+ const result = await initialized.execute(effectiveParams, ctx);
249
+ const metadata = result.metadata ?? {};
250
+ if (options.middleware?.hasMiddleware) {
251
+ const transformed = await options.middleware.runAfterToolCall(
252
+ options.toolName,
253
+ effectiveParams,
254
+ { ...result, metadata },
255
+ ctx
256
+ );
257
+ const finalOutput = transformed.supplement ? `${transformed.output}
258
+
259
+ ${transformed.supplement}` : transformed.output;
260
+ return {
261
+ output: finalOutput,
262
+ title: transformed.title,
263
+ metadata: transformed.metadata ?? {},
264
+ capabilities: initialized.capabilities
265
+ };
266
+ }
267
+ return {
268
+ output: result.output,
269
+ title: result.title,
270
+ metadata,
271
+ capabilities: initialized.capabilities
272
+ };
273
+ }
274
+ );
275
+ }
276
+
277
+ export {
278
+ currentScope,
279
+ snapshotScope,
280
+ withinScope,
281
+ restoreScope,
282
+ streamWithinScope,
283
+ PRUNE_PROTECTED_TOOLS,
284
+ extractFilePathsFromArgs,
285
+ shouldCaptureBaseline,
286
+ accumulateUsage,
287
+ executeAgentToolCall
288
+ };
@@ -1,4 +1,4 @@
1
- // src/presets/builtins.ts
1
+ // src/profiles/builtins.ts
2
2
  var explore = {
3
3
  name: "explore",
4
4
  description: "Read-only exploration mode for understanding content",
@@ -158,7 +158,7 @@ Guidelines:
158
158
  maxSteps: 10,
159
159
  reasoningLevel: "low"
160
160
  };
161
- var Presets = {
161
+ var Profiles = {
162
162
  explore,
163
163
  plan,
164
164
  review,
@@ -176,5 +176,5 @@ export {
176
176
  careful,
177
177
  code,
178
178
  watch,
179
- Presets
179
+ Profiles
180
180
  };
@@ -0,0 +1,58 @@
1
+ // src/middleware/types.ts
2
+ function isBlockedModelCall(value) {
3
+ return "block" in value && value.block === true;
4
+ }
5
+
6
+ // src/agent/defaults.ts
7
+ var DEFAULT_SYSTEM_PROMPT = `You are a capable AI assistant with access to tools.
8
+
9
+ Think step by step about what you need to do.
10
+ Use the available tools to accomplish tasks.
11
+ Verify your results after each action.
12
+
13
+ If a tool fails, try an alternative approach \u2014 do not give up after a single error.
14
+ Keep working until the task is fully resolved or you have exhausted all options.`;
15
+ var DEFAULT_AGENT_NAME = "agent";
16
+ var DEFAULT_MAX_STEPS = 50;
17
+ var DEFAULT_MAX_TOKENS = 32e3;
18
+ function resolveAgentDefaults(context, providers) {
19
+ let merged = {
20
+ systemPrompt: DEFAULT_SYSTEM_PROMPT,
21
+ maxSteps: DEFAULT_MAX_STEPS,
22
+ maxOutputTokens: DEFAULT_MAX_TOKENS
23
+ };
24
+ if (providers) {
25
+ for (const provider of providers) {
26
+ const overrides = provider(context);
27
+ if (overrides) {
28
+ merged = {
29
+ systemPrompt: overrides.systemPrompt ?? merged.systemPrompt,
30
+ maxSteps: overrides.maxSteps ?? merged.maxSteps,
31
+ maxOutputTokens: overrides.maxOutputTokens ?? merged.maxOutputTokens
32
+ };
33
+ }
34
+ }
35
+ }
36
+ return merged;
37
+ }
38
+ function sandboxDefaultsProvider(context) {
39
+ const sandbox = context.sandbox;
40
+ if (!sandbox) {
41
+ return void 0;
42
+ }
43
+ const managed = sandbox.metadata?.managed === true;
44
+ if (managed) {
45
+ return { maxSteps: 100 };
46
+ }
47
+ return void 0;
48
+ }
49
+
50
+ export {
51
+ isBlockedModelCall,
52
+ DEFAULT_SYSTEM_PROMPT,
53
+ DEFAULT_AGENT_NAME,
54
+ DEFAULT_MAX_STEPS,
55
+ DEFAULT_MAX_TOKENS,
56
+ resolveAgentDefaults,
57
+ sandboxDefaultsProvider
58
+ };
@@ -1,16 +1,23 @@
1
1
  import {
2
- executeAgentToolCall
3
- } from "./chunk-H3FUYU52.js";
2
+ executeAgentToolCall,
3
+ snapshotScope
4
+ } from "./chunk-5NVVNXPQ.js";
4
5
  import {
5
6
  LLMError,
6
7
  isRetryable
7
- } from "./chunk-4QFNWPIF.js";
8
+ } from "./chunk-N3VX7FEE.js";
8
9
  import {
9
- snapshotScope
10
- } from "./chunk-N7P4PN3O.js";
10
+ buildReasoningOptionsSync,
11
+ supportsReasoningSync
12
+ } from "./chunk-RN6WZEUF.js";
11
13
  import {
12
- buildReasoningOptionsSync
13
- } from "./chunk-UDCZ673N.js";
14
+ DEFAULT_MAX_STEPS,
15
+ DEFAULT_MAX_TOKENS,
16
+ isBlockedModelCall
17
+ } from "./chunk-CJI7PVS2.js";
18
+ import {
19
+ formatApprovalDeniedReason
20
+ } from "./chunk-V4RFNEET.js";
14
21
 
15
22
  // src/inference/toolset.ts
16
23
  import { tool, zodSchema } from "ai";
@@ -19,26 +26,58 @@ async function buildToolSet(options) {
19
26
  const executionMode = options.executionMode ?? "auto";
20
27
  for (const [id, info] of Object.entries(options.tools)) {
21
28
  const initialized = await info.init({ cwd: options.cwd });
22
- toolSet[id] = executionMode === "auto" ? tool({
23
- description: initialized.description,
24
- inputSchema: zodSchema(initialized.parameters),
25
- execute: async (params) => (await executeAgentToolCall({
26
- toolName: id,
27
- tool: info,
28
- initialized,
29
- params,
30
- cwd: options.cwd,
31
- abort: options.abort,
32
- sessionID: options.sessionID,
33
- messageID: options.messageID,
34
- ...options.host ? { host: options.host } : {},
35
- ...options.turnTracker ? { turnTracker: options.turnTracker } : {},
36
- ...options.middleware ? { middleware: options.middleware } : {}
37
- })).output
38
- }) : tool({
39
- description: initialized.description,
40
- inputSchema: zodSchema(initialized.parameters)
41
- });
29
+ const sdkPassthrough = {};
30
+ if (initialized.title !== void 0) sdkPassthrough.title = initialized.title;
31
+ if (initialized.strict !== void 0) sdkPassthrough.strict = initialized.strict;
32
+ if (initialized.inputExamples !== void 0) {
33
+ sdkPassthrough.inputExamples = initialized.inputExamples;
34
+ }
35
+ if (initialized.toModelOutput !== void 0) {
36
+ sdkPassthrough.toModelOutput = initialized.toModelOutput;
37
+ }
38
+ if (executionMode === "auto") {
39
+ toolSet[id] = tool({
40
+ description: initialized.description,
41
+ inputSchema: zodSchema(initialized.parameters),
42
+ ...sdkPassthrough,
43
+ execute: async (params, sdkOptions) => {
44
+ const executed = await executeAgentToolCall({
45
+ toolName: id,
46
+ tool: info,
47
+ initialized,
48
+ params,
49
+ cwd: options.cwd,
50
+ abort: options.abort,
51
+ sessionID: options.sessionID,
52
+ turnID: options.turnID,
53
+ messageID: options.messageID,
54
+ toolCallId: sdkOptions.toolCallId,
55
+ ...options.host ? { host: options.host } : {},
56
+ ...options.humanInputController ? { humanInputController: options.humanInputController } : {},
57
+ ...options.turnTracker ? { turnTracker: options.turnTracker } : {},
58
+ ...options.middleware ? { middleware: options.middleware } : {},
59
+ ...options.onEvent ? { onEvent: options.onEvent } : {}
60
+ });
61
+ if (!executed.metadata?.approvalCorrection) {
62
+ return executed.output;
63
+ }
64
+ const structured = {
65
+ __cuylabsAgentToolResult: true,
66
+ output: executed.output,
67
+ metadata: executed.metadata
68
+ };
69
+ return structured;
70
+ }
71
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ });
73
+ } else {
74
+ toolSet[id] = tool({
75
+ description: initialized.description,
76
+ inputSchema: zodSchema(initialized.parameters),
77
+ ...sdkPassthrough
78
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
+ });
80
+ }
42
81
  }
43
82
  return toolSet;
44
83
  }
@@ -95,7 +134,7 @@ function mergeProviderOptions(base, override) {
95
134
  return merged;
96
135
  }
97
136
  function wrapMcpToolsForMiddleware(options) {
98
- const { tools, middleware, cwd, sessionID, abort, agent } = options;
137
+ const { tools, middleware, cwd, sessionID, turnID, abort, agent } = options;
99
138
  if (!middleware?.hasMiddleware) {
100
139
  return tools;
101
140
  }
@@ -112,6 +151,7 @@ function wrapMcpToolsForMiddleware(options) {
112
151
  cwd,
113
152
  abort: execOptions.abortSignal ?? abort,
114
153
  sessionID,
154
+ ...turnID ? { turnID } : {},
115
155
  messageID: execOptions.toolCallId,
116
156
  agent: agent ?? "default",
117
157
  scope: snapshotScope(),
@@ -127,7 +167,7 @@ function wrapMcpToolsForMiddleware(options) {
127
167
  ctx
128
168
  );
129
169
  if (decision.action === "deny") {
130
- return decision.reason ?? `Tool call denied: ${toolName}`;
170
+ return decision.reason ?? formatApprovalDeniedReason(toolName);
131
171
  }
132
172
  const result = tool2.execute(params, execOptions);
133
173
  if (isAsyncIterable(result)) {
@@ -247,14 +287,11 @@ function shouldRetry(error, attempt, maxAttempts = DEFAULT_RETRY_CONFIG.maxAttem
247
287
  return isRetryable(error);
248
288
  }
249
289
 
250
- // src/inference/types.ts
251
- var DEFAULT_MAX_OUTPUT_TOKENS = 32e3;
252
- var OUTPUT_TOKEN_MAX = DEFAULT_MAX_OUTPUT_TOKENS;
253
-
254
290
  // src/inference/stream.ts
255
291
  function buildModelCallContext(input) {
256
292
  return {
257
293
  sessionID: input.sessionID,
294
+ turnID: input.turnID,
258
295
  step: input.step ?? 1,
259
296
  cwd: input.cwd,
260
297
  abort: input.abort,
@@ -295,9 +332,6 @@ function applyModelCallInput(target, modelCall) {
295
332
  target.toolExecutionMode = modelCall.toolExecutionMode;
296
333
  target.activeModelCall = modelCall;
297
334
  }
298
- function isBlockedModelCall(value) {
299
- return "block" in value && value.block === true;
300
- }
301
335
  async function resolveModelCallInput(input) {
302
336
  if (!input.middleware?.hasMiddleware) {
303
337
  const current = buildModelCallInput(input);
@@ -377,10 +411,12 @@ async function callStreamTextWithOtelContext(options) {
377
411
  system: systemParam,
378
412
  messages: input.messages,
379
413
  tools: allTools,
380
- stopWhen: stepCountIs(input.maxSteps ?? 50),
381
- maxOutputTokens: input.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
382
- temperature: input.temperature,
383
- topP: input.topP,
414
+ ...input.toolChoice ? { toolChoice: input.toolChoice } : {},
415
+ ...input.activeTools ? { activeTools: input.activeTools } : {},
416
+ stopWhen: stepCountIs(input.maxSteps ?? DEFAULT_MAX_STEPS),
417
+ maxOutputTokens: input.maxOutputTokens ?? DEFAULT_MAX_TOKENS,
418
+ ...input.temperature !== void 0 && !supportsReasoningSync(input.model) ? { temperature: input.temperature } : {},
419
+ ...input.topP !== void 0 && !supportsReasoningSync(input.model) ? { topP: input.topP } : {},
384
420
  abortSignal: input.abort,
385
421
  providerOptions: mergedProviderOptions,
386
422
  experimental_telemetry: input.telemetry,
@@ -418,7 +454,10 @@ async function callStreamTextWithOtelContext(options) {
418
454
  });
419
455
  }
420
456
  });
421
- const otelCtx = input.middleware?.getOtelContext(input.sessionID);
457
+ const otelCtx = input.middleware?.getOtelContext(input.sessionID, {
458
+ sessionId: input.sessionID,
459
+ ...input.turnID ? { turnId: input.turnID } : {}
460
+ });
422
461
  if (!otelCtx) {
423
462
  return callStreamText();
424
463
  }
@@ -463,11 +502,14 @@ async function stream(input) {
463
502
  tools: input.tools,
464
503
  cwd: input.cwd,
465
504
  sessionID: input.sessionID,
505
+ turnID: input.turnID,
466
506
  messageID,
467
507
  abort: input.abort,
468
508
  turnTracker: input.turnTracker,
469
509
  host: input.host,
510
+ humanInputController: input.humanInputController,
470
511
  middleware: input.middleware,
512
+ onEvent: input.onEvent,
471
513
  executionMode: input.toolExecutionMode
472
514
  });
473
515
  const mcpToolSet = wrapMcpToolsForMiddleware({
@@ -475,6 +517,7 @@ async function stream(input) {
475
517
  middleware: input.middleware,
476
518
  cwd: input.cwd,
477
519
  sessionID: input.sessionID,
520
+ turnID: input.turnID,
478
521
  abort: input.abort
479
522
  });
480
523
  const allTools = {
@@ -512,16 +555,75 @@ async function streamStep(input) {
512
555
  });
513
556
  }
514
557
 
558
+ // src/inference/model-messages.ts
559
+ function buildApprovalCorrectionPrompt(correction) {
560
+ const lines = [
561
+ `Human approval denied the previous ${correction.tool} tool call.`,
562
+ `Treat this as corrective guidance and revise the plan before attempting another action.`,
563
+ `Reason: ${correction.reason}`
564
+ ];
565
+ if (correction.feedback) {
566
+ lines.push(`Feedback: ${correction.feedback}`);
567
+ }
568
+ return {
569
+ role: "system",
570
+ content: lines.join("\n")
571
+ };
572
+ }
573
+ function convertAgentMessagesToModelMessages(messages) {
574
+ return messages.flatMap((message) => {
575
+ switch (message.role) {
576
+ case "user":
577
+ return [{ role: "user", content: message.content }];
578
+ case "assistant": {
579
+ if (message.toolCalls && message.toolCalls.length > 0) {
580
+ const toolCallParts = message.toolCalls.map(
581
+ (toolCall) => ({
582
+ type: "tool-call",
583
+ toolCallId: toolCall.toolCallId,
584
+ toolName: toolCall.toolName,
585
+ input: toolCall.args
586
+ })
587
+ );
588
+ return [{ role: "assistant", content: toolCallParts }];
589
+ }
590
+ return [{ role: "assistant", content: message.content }];
591
+ }
592
+ case "tool":
593
+ return [
594
+ {
595
+ role: "tool",
596
+ content: [
597
+ {
598
+ type: "tool-result",
599
+ toolCallId: message.toolCallId ?? "",
600
+ toolName: message.toolName ?? "",
601
+ output: {
602
+ type: "text",
603
+ value: typeof message.result === "string" ? message.result : JSON.stringify(message.result)
604
+ }
605
+ }
606
+ ]
607
+ },
608
+ ...message.metadata?.approvalCorrection ? [buildApprovalCorrectionPrompt(message.metadata.approvalCorrection)] : []
609
+ ];
610
+ case "system":
611
+ return [{ role: "system", content: message.content }];
612
+ }
613
+ });
614
+ }
615
+
515
616
  // src/inference/index.ts
516
617
  var Inference = {
618
+ buildModelCallContext,
517
619
  buildToolSet,
518
620
  stream,
519
621
  streamOnce,
520
622
  streamStep
521
623
  };
522
- var LLM = Inference;
523
624
 
524
625
  export {
626
+ convertAgentMessagesToModelMessages,
525
627
  buildToolSet,
526
628
  DEFAULT_RETRY_CONFIG,
527
629
  createRetryState,
@@ -530,11 +632,9 @@ export {
530
632
  withRetry,
531
633
  createRetryHandler,
532
634
  shouldRetry,
533
- DEFAULT_MAX_OUTPUT_TOKENS,
534
- OUTPUT_TOKEN_MAX,
635
+ buildModelCallContext,
535
636
  stream,
536
637
  streamOnce,
537
638
  streamStep,
538
- Inference,
539
- LLM
639
+ Inference
540
640
  };