@codebolt/agent 6.1.20 → 6.1.22

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 (54) hide show
  1. package/README.md +1 -0
  2. package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.js +11 -15
  3. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.d.ts +0 -1
  4. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +16 -33
  5. package/dist/processor-pieces/messageModifiers/capabilityContextModifier.js +3 -2
  6. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.d.ts +8 -0
  7. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.js +150 -27
  8. package/dist/processor-pieces/messageModifiers/chatRecordingModifier.js +3 -3
  9. package/dist/processor-pieces/messageModifiers/contextAssemblyModifier.js +18 -12
  10. package/dist/processor-pieces/messageModifiers/directoryContextModifier.d.ts +1 -0
  11. package/dist/processor-pieces/messageModifiers/directoryContextModifier.js +15 -15
  12. package/dist/processor-pieces/messageModifiers/environmentContextModifier.d.ts +1 -0
  13. package/dist/processor-pieces/messageModifiers/environmentContextModifier.js +48 -2
  14. package/dist/processor-pieces/messageModifiers/ideContextModifier.js +3 -2
  15. package/dist/processor-pieces/messageModifiers/index.d.ts +1 -0
  16. package/dist/processor-pieces/messageModifiers/index.js +3 -1
  17. package/dist/processor-pieces/messageModifiers/memoryImportModifier.js +9 -15
  18. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +17 -20
  19. package/dist/processor-pieces/messageModifiers/toolManifestPromptModifier.d.ts +18 -0
  20. package/dist/processor-pieces/messageModifiers/toolManifestPromptModifier.js +57 -0
  21. package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.js +8 -19
  22. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.d.ts +1 -1
  23. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.js +28 -20
  24. package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.js +3 -3
  25. package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.js +2 -2
  26. package/dist/processor-pieces/utils/messageModifierHelper.js +3 -3
  27. package/dist/types/libFunctionTypes.d.ts +139 -7
  28. package/dist/unified/agent/agent.d.ts +13 -0
  29. package/dist/unified/agent/agent.js +180 -19
  30. package/dist/unified/agent/tools.d.ts +14 -0
  31. package/dist/unified/agent/tools.js +82 -51
  32. package/dist/unified/base/agentStep.d.ts +2 -1
  33. package/dist/unified/base/agentStep.js +47 -16
  34. package/dist/unified/base/initialPromptGenerator.d.ts +2 -0
  35. package/dist/unified/base/initialPromptGenerator.js +42 -19
  36. package/dist/unified/base/promptContext.d.ts +3 -0
  37. package/dist/unified/base/promptContext.js +193 -15
  38. package/dist/unified/base/responseExecutor.d.ts +6 -0
  39. package/dist/unified/base/responseExecutor.js +256 -69
  40. package/dist/unified/index.d.ts +1 -0
  41. package/dist/unified/index.js +3 -1
  42. package/dist/unified/services/CompressionCoordinator.js +9 -9
  43. package/dist/unified/services/compaction/autoCompact.d.ts +2 -1
  44. package/dist/unified/services/compaction/autoCompact.js +19 -11
  45. package/dist/unified/services/compaction/compactionOrchestrator.d.ts +1 -0
  46. package/dist/unified/services/compaction/compactionOrchestrator.js +8 -0
  47. package/dist/unified/services/compaction/contextCollapse.d.ts +2 -1
  48. package/dist/unified/services/compaction/contextCollapse.js +17 -9
  49. package/dist/unified/services/compaction/reactiveCompact.d.ts +3 -0
  50. package/dist/unified/services/compaction/reactiveCompact.js +17 -8
  51. package/dist/unified/types/libTypes.d.ts +189 -10
  52. package/dist/unified/utils/agentToolLoader.d.ts +17 -1
  53. package/dist/unified/utils/agentToolLoader.js +182 -31
  54. package/package.json +5 -1
@@ -224,20 +224,152 @@ export interface EmitAgentEventResponse {
224
224
  };
225
225
  error?: string;
226
226
  }
227
+ export type ToolSourceType = 'built-in' | 'mcp' | 'plugin' | 'project-local' | 'agent-local' | 'unknown';
228
+ export interface ToolNamespace {
229
+ namespace: string;
230
+ sourceType?: ToolSourceType;
231
+ sourceId?: string;
232
+ displayName?: string;
233
+ toolCount?: number;
234
+ }
235
+ export interface ToolSource {
236
+ sourceId: string;
237
+ sourceType: ToolSourceType;
238
+ displayName?: string;
239
+ namespaces?: string[];
240
+ toolCount?: number;
241
+ }
242
+ export interface RuntimeToolDescriptor {
243
+ name: string;
244
+ toolName: string;
245
+ namespace: string;
246
+ sourceType: ToolSourceType;
247
+ sourceId?: string;
248
+ displayName?: string;
249
+ description?: string;
250
+ inputSchema: Record<string, unknown>;
251
+ outputSchema?: Record<string, unknown>;
252
+ metadata?: Record<string, unknown>;
253
+ }
227
254
  /**
228
255
  * Interface for codebolt API functionality
229
256
  */
230
257
  export interface CodeboltAPI {
231
- mcp: {
232
- listMcpFromServers: (servers: string[]) => Promise<{
233
- data: OpenAITool[];
258
+ tools?: {
259
+ listBuiltInTools: (options?: {
260
+ namespace?: string;
261
+ grep?: string;
262
+ limit?: number;
263
+ }) => Promise<{
264
+ data: {
265
+ tools: RuntimeToolDescriptor[];
266
+ };
267
+ }>;
268
+ listExternalTools: (options?: {
269
+ namespace?: string;
270
+ sourceType?: ToolSourceType;
271
+ sourceId?: string;
272
+ grep?: string;
273
+ limit?: number;
274
+ }) => Promise<{
275
+ data: {
276
+ tools: RuntimeToolDescriptor[];
277
+ };
278
+ }>;
279
+ listRuntimeTools: (options?: {
280
+ includeBuiltIn?: boolean;
281
+ includeExternal?: boolean;
282
+ includeAgentLocal?: boolean;
283
+ agentLocalTools?: Array<OpenAITool | RuntimeToolDescriptor>;
284
+ namespace?: string;
285
+ sourceType?: ToolSourceType;
286
+ sourceId?: string;
287
+ grep?: string;
288
+ limit?: number;
289
+ }) => Promise<{
290
+ data: {
291
+ tools: RuntimeToolDescriptor[];
292
+ };
234
293
  }>;
235
- getTools: (mcps: any[]) => Promise<{
236
- data: OpenAITool[];
294
+ listToolNamespaces: (options?: {
295
+ includeBuiltIn?: boolean;
296
+ includeExternal?: boolean;
297
+ includeAgentLocal?: boolean;
298
+ agentLocalTools?: Array<OpenAITool | RuntimeToolDescriptor>;
299
+ namespace?: string;
300
+ sourceType?: ToolSourceType;
301
+ sourceId?: string;
302
+ grep?: string;
303
+ limit?: number;
304
+ }) => Promise<{
305
+ data: {
306
+ namespaces: ToolNamespace[];
307
+ };
237
308
  }>;
238
- executeTool: (toolboxName: string, actualToolName: string, toolInput: any) => Promise<{
239
- data: any;
309
+ listToolsByNamespace: (namespace: string, options?: {
310
+ includeBuiltIn?: boolean;
311
+ includeExternal?: boolean;
312
+ includeAgentLocal?: boolean;
313
+ agentLocalTools?: Array<OpenAITool | RuntimeToolDescriptor>;
314
+ sourceType?: ToolSourceType;
315
+ sourceId?: string;
316
+ grep?: string;
317
+ limit?: number;
318
+ }) => Promise<{
319
+ data: {
320
+ tools: RuntimeToolDescriptor[];
321
+ };
240
322
  }>;
323
+ listToolSources: (options?: {
324
+ includeBuiltIn?: boolean;
325
+ includeExternal?: boolean;
326
+ includeAgentLocal?: boolean;
327
+ agentLocalTools?: Array<OpenAITool | RuntimeToolDescriptor>;
328
+ namespace?: string;
329
+ sourceType?: ToolSourceType;
330
+ sourceId?: string;
331
+ grep?: string;
332
+ limit?: number;
333
+ }) => Promise<{
334
+ data: {
335
+ sources: ToolSource[];
336
+ };
337
+ }>;
338
+ listToolsBySource: (sourceId: string, options?: {
339
+ includeBuiltIn?: boolean;
340
+ includeExternal?: boolean;
341
+ includeAgentLocal?: boolean;
342
+ agentLocalTools?: Array<OpenAITool | RuntimeToolDescriptor>;
343
+ namespace?: string;
344
+ sourceType?: ToolSourceType;
345
+ grep?: string;
346
+ limit?: number;
347
+ }) => Promise<{
348
+ data: {
349
+ tools: RuntimeToolDescriptor[];
350
+ };
351
+ }>;
352
+ getRuntimeTool: (name: string) => Promise<{
353
+ data: {
354
+ tool?: RuntimeToolDescriptor;
355
+ };
356
+ }>;
357
+ execute: (toolName: string, toolInput?: any, options?: {
358
+ namespace?: string;
359
+ sourceId?: string;
360
+ }) => Promise<{
361
+ data?: any;
362
+ result?: any;
363
+ }>;
364
+ };
365
+ mcp: {
366
+ getEnabledMCPServers: () => Promise<unknown>;
367
+ getLocalMCPServers: () => Promise<unknown>;
368
+ getMentionedMCPServers: (userMessage: unknown) => Promise<unknown>;
369
+ searchAvailableMCPServers: (query: string) => Promise<unknown>;
370
+ configureMCPServer: (name: string, config: Record<string, unknown>) => Promise<unknown>;
371
+ getMcpList: () => Promise<unknown>;
372
+ getEnabledMcps: () => Promise<unknown>;
241
373
  };
242
374
  fs: {
243
375
  readFile: (filepath: string) => Promise<string>;
@@ -5,6 +5,7 @@ import type { CompactionOrchestratorOptions } from "../services/compaction/types
5
5
  export interface AgentOptions extends AgentConfig {
6
6
  context?: ProcessedMessage;
7
7
  allowedTools?: string[];
8
+ llmRole?: string;
8
9
  compaction?: CompactionOrchestratorOptions;
9
10
  loopDetectionService?: LoopDetectionService;
10
11
  maxTurns?: number;
@@ -55,10 +56,14 @@ export declare class Agent implements AgentInterface {
55
56
  private readonly compactionOrchestrator;
56
57
  private readonly loopDetectionService;
57
58
  private readonly maxTurns;
59
+ private readonly llmRole;
58
60
  private readonly localToolSchemas;
59
61
  private readonly localToolsByExecutionName;
62
+ private readonly runtimeToolSetId;
60
63
  constructor(config: AgentOptions);
61
64
  run(message: string | FlatUserMessage, options?: ProcessedMessage | AgentRunOptions): Promise<AgentRunResult>;
65
+ private registerRuntimeToolsForSearch;
66
+ private unregisterRuntimeToolsForSearch;
62
67
  processMessage(message: string | FlatUserMessage, options?: ProcessedMessage | AgentRunOptions): Promise<AgentRunResult>;
63
68
  execute(reqMessage: FlatUserMessage): Promise<{
64
69
  success: boolean;
@@ -72,8 +77,16 @@ export declare class Agent implements AgentInterface {
72
77
  getPreToolCallProcessors(): PreToolCallProcessor[];
73
78
  getPostToolCallProcessors(): PostToolCallProcessor[];
74
79
  private resolveRunContext;
80
+ private getResumeMessageModifiers;
81
+ private normalizeLLMRole;
75
82
  private isProcessedMessage;
76
83
  private applyCompaction;
84
+ private hydratePromptFromServerCompaction;
85
+ private isServerCompactionCurrent;
86
+ private extractCurrentRunMessages;
87
+ private isCurrentRunUserMessage;
88
+ private extractServerCompactedMessages;
89
+ private isServerCompactedMessage;
77
90
  private tryRecoverPrompt;
78
91
  private refreshAvailableTools;
79
92
  private getAllowedToolNames;
@@ -1,7 +1,12 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.Agent = void 0;
4
7
  exports.createAgent = createAgent;
8
+ const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
9
+ const crypto_1 = require("crypto");
5
10
  const base_1 = require("../base");
6
11
  const agentStep_1 = require("../base/agentStep");
7
12
  const responseExecutor_1 = require("../base/responseExecutor");
@@ -95,7 +100,7 @@ function collectProcessors(fromNested, fromTopLevel) {
95
100
  }
96
101
  class Agent {
97
102
  constructor(config) {
98
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
103
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
99
104
  const localToolRegistry = (0, agentToolLoader_1.createAgentLocalToolRegistry)(config.tools || []);
100
105
  const includeDefaultModifiers = (_b = (_a = config.includeDefaultModifiers) !== null && _a !== void 0 ? _a : config.defaultProcessors) !== null && _b !== void 0 ? _b : true;
101
106
  const includeDefaultProcessors = (_d = (_c = config.includeDefaultProcessors) !== null && _c !== void 0 ? _c : config.defaultProcessors) !== null && _d !== void 0 ? _d : true;
@@ -108,27 +113,39 @@ class Agent {
108
113
  this.baseSystemPrompt = config.instructions || DEFAULT_SYSTEM_PROMPT;
109
114
  this.context = config.context;
110
115
  this.allowedTools = config.allowedTools;
116
+ this.llmRole = this.normalizeLLMRole(config.llmRole);
111
117
  this.messageModifiers = mergeProcessors(defaultMessageModifiers, customMessageModifiers);
112
118
  this.preInferenceProcessors = mergeProcessors(includeDefaultProcessors ? createDefaultPreInferenceProcessors() : [], collectProcessors((_f = config.processors) === null || _f === void 0 ? void 0 : _f.preInferenceProcessors, config.preInferenceProcessors));
113
119
  this.postInferenceProcessors = mergeProcessors(includeDefaultProcessors ? createDefaultPostInferenceProcessors() : [], collectProcessors((_g = config.processors) === null || _g === void 0 ? void 0 : _g.postInferenceProcessors, config.postInferenceProcessors));
114
120
  this.preToolCallProcessors = mergeProcessors(includeDefaultProcessors ? createDefaultPreToolCallProcessors() : [], collectProcessors((_h = config.processors) === null || _h === void 0 ? void 0 : _h.preToolCallProcessors, config.preToolCallProcessors));
115
121
  this.postToolCallProcessors = mergeProcessors(includeDefaultProcessors ? createDefaultPostToolCallProcessors() : [], collectProcessors((_j = config.processors) === null || _j === void 0 ? void 0 : _j.postToolCallProcessors, config.postToolCallProcessors));
116
- this.compactionOrchestrator = new compactionOrchestrator_1.CompactionOrchestrator(config.compaction);
122
+ const compactionLLMRole = (_l = this.normalizeLLMRole((_k = config.compaction) === null || _k === void 0 ? void 0 : _k.llmRole)) !== null && _l !== void 0 ? _l : this.llmRole;
123
+ this.compactionOrchestrator = new compactionOrchestrator_1.CompactionOrchestrator({
124
+ ...config.compaction,
125
+ ...(compactionLLMRole ? { llmRole: compactionLLMRole } : {}),
126
+ });
117
127
  this.loopDetectionService = config.loopDetectionService;
118
- this.maxTurns = (_l = (_k = config.maxTurns) !== null && _k !== void 0 ? _k : config.maxIterations) !== null && _l !== void 0 ? _l : 25;
128
+ this.maxTurns = (_o = (_m = config.maxTurns) !== null && _m !== void 0 ? _m : config.maxIterations) !== null && _o !== void 0 ? _o : 25;
119
129
  this.localToolSchemas = localToolRegistry.schemas;
120
130
  this.localToolsByExecutionName = localToolRegistry.byExecutionName;
131
+ this.runtimeToolSetId = `agent-${(0, crypto_1.randomUUID)()}`;
121
132
  }
122
133
  async run(message, options) {
123
134
  var _a, _b;
124
135
  try {
136
+ await this.registerRuntimeToolsForSearch();
125
137
  const reqMessage = typeof message === 'string'
126
138
  ? createDefaultUserMessage(message)
127
139
  : message;
128
140
  let prompt;
129
141
  const contextToUse = this.resolveRunContext(options);
130
142
  if (contextToUse) {
131
- prompt = contextToUse;
143
+ const promptGenerator = new base_1.InitialPromptGenerator({
144
+ processors: this.getResumeMessageModifiers(),
145
+ initialPrompt: contextToUse,
146
+ enableLogging: this.enableLogging
147
+ });
148
+ prompt = await promptGenerator.processMessage(reqMessage);
132
149
  }
133
150
  else {
134
151
  const promptGenerator = new base_1.InitialPromptGenerator({
@@ -138,6 +155,7 @@ class Agent {
138
155
  });
139
156
  prompt = await promptGenerator.processMessage(reqMessage);
140
157
  }
158
+ prompt = await this.hydratePromptFromServerCompaction(reqMessage, prompt);
141
159
  let completed = false;
142
160
  let turnNumber = 0;
143
161
  let finalMessage;
@@ -152,7 +170,8 @@ class Agent {
152
170
  prompt = await this.refreshAvailableTools(reqMessage, prompt);
153
171
  const agentStep = new agentStep_1.AgentStep({
154
172
  preInferenceProcessors: this.preInferenceProcessors,
155
- postInferenceProcessors: this.postInferenceProcessors
173
+ postInferenceProcessors: this.postInferenceProcessors,
174
+ ...(this.llmRole ? { llmRole: this.llmRole } : {}),
156
175
  });
157
176
  let stepResult;
158
177
  while (!stepResult) {
@@ -224,6 +243,37 @@ class Agent {
224
243
  error: errorMessage
225
244
  };
226
245
  }
246
+ finally {
247
+ await this.unregisterRuntimeToolsForSearch();
248
+ }
249
+ }
250
+ async registerRuntimeToolsForSearch() {
251
+ var _a, _b;
252
+ if (this.localToolSchemas.length === 0) {
253
+ return;
254
+ }
255
+ try {
256
+ await ((_b = (_a = codeboltjs_1.default.searchableAssets) === null || _a === void 0 ? void 0 : _a.registerRuntimeTools) === null || _b === void 0 ? void 0 : _b.call(_a, this.runtimeToolSetId, this.localToolSchemas));
257
+ }
258
+ catch (error) {
259
+ if (this.enableLogging) {
260
+ console.error('[Agent] Failed to register runtime tools for search:', error);
261
+ }
262
+ }
263
+ }
264
+ async unregisterRuntimeToolsForSearch() {
265
+ var _a, _b;
266
+ if (this.localToolSchemas.length === 0) {
267
+ return;
268
+ }
269
+ try {
270
+ await ((_b = (_a = codeboltjs_1.default.searchableAssets) === null || _a === void 0 ? void 0 : _a.unregisterRuntimeTools) === null || _b === void 0 ? void 0 : _b.call(_a, this.runtimeToolSetId));
271
+ }
272
+ catch (error) {
273
+ if (this.enableLogging) {
274
+ console.error('[Agent] Failed to unregister runtime tools for search:', error);
275
+ }
276
+ }
227
277
  }
228
278
  async processMessage(message, options) {
229
279
  return this.run(message, options);
@@ -259,6 +309,13 @@ class Agent {
259
309
  }
260
310
  return (_c = (_b = (_a = options.state) === null || _a === void 0 ? void 0 : _a.prompt) !== null && _b !== void 0 ? _b : options.context) !== null && _c !== void 0 ? _c : this.context;
261
311
  }
312
+ getResumeMessageModifiers() {
313
+ return this.messageModifiers.filter((modifier) => { var _a; return ((_a = modifier.constructor) === null || _a === void 0 ? void 0 : _a.name) !== 'ChatHistoryMessageModifier'; });
314
+ }
315
+ normalizeLLMRole(llmRole) {
316
+ const normalized = llmRole === null || llmRole === void 0 ? void 0 : llmRole.trim();
317
+ return normalized ? normalized : undefined;
318
+ }
262
319
  isProcessedMessage(value) {
263
320
  return 'message' in value && 'metadata' in value;
264
321
  }
@@ -280,6 +337,111 @@ class Agent {
280
337
  },
281
338
  };
282
339
  }
340
+ async hydratePromptFromServerCompaction(requestMessage, prompt) {
341
+ if (!requestMessage.threadId) {
342
+ return prompt;
343
+ }
344
+ try {
345
+ const response = await codeboltjs_1.default.thread.getThreadContextCompacted({
346
+ threadId: requestMessage.threadId,
347
+ });
348
+ if (!this.isServerCompactionCurrent(response === null || response === void 0 ? void 0 : response.context)) {
349
+ return prompt;
350
+ }
351
+ const compactedMessages = this.extractServerCompactedMessages(response === null || response === void 0 ? void 0 : response.compactedContext);
352
+ if (compactedMessages.length === 0) {
353
+ return prompt;
354
+ }
355
+ const currentRunMessages = this.extractCurrentRunMessages(requestMessage, prompt);
356
+ return {
357
+ ...(0, promptContext_1.replaceTranscriptMessages)(prompt, [
358
+ ...compactedMessages,
359
+ ...currentRunMessages,
360
+ ]),
361
+ metadata: {
362
+ ...prompt.metadata,
363
+ serverCompaction: {
364
+ threadId: requestMessage.threadId,
365
+ timestamp: new Date().toISOString(),
366
+ messageCount: compactedMessages.length,
367
+ currentRunMessageCount: currentRunMessages.length,
368
+ },
369
+ },
370
+ };
371
+ }
372
+ catch (error) {
373
+ if (this.enableLogging) {
374
+ console.error('[Agent] Failed to hydrate prompt from server compaction:', error);
375
+ }
376
+ return prompt;
377
+ }
378
+ }
379
+ isServerCompactionCurrent(context) {
380
+ if (!context || typeof context !== 'object') {
381
+ return true;
382
+ }
383
+ const metadata = context.metadata;
384
+ if (!metadata || typeof metadata !== 'object') {
385
+ return true;
386
+ }
387
+ const messageCount = Number(metadata.messageCount);
388
+ const lastCompactionMessageCount = Number(metadata.lastCompactionMessageCount);
389
+ if (!Number.isFinite(messageCount) || !Number.isFinite(lastCompactionMessageCount)) {
390
+ return true;
391
+ }
392
+ return messageCount <= lastCompactionMessageCount;
393
+ }
394
+ extractCurrentRunMessages(requestMessage, prompt) {
395
+ const transcriptMessages = (0, promptContext_1.getTranscriptMessages)(prompt);
396
+ const lastMessage = transcriptMessages[transcriptMessages.length - 1];
397
+ if (!lastMessage || lastMessage.role !== 'user') {
398
+ return [];
399
+ }
400
+ const requestedContent = requestMessage.userMessage || '';
401
+ if (!this.isCurrentRunUserMessage(lastMessage, requestedContent)) {
402
+ return [];
403
+ }
404
+ return [{ ...lastMessage }];
405
+ }
406
+ isCurrentRunUserMessage(message, requestedContent) {
407
+ if (typeof message.content === 'string') {
408
+ return message.content === requestedContent ||
409
+ message.content.startsWith(`${requestedContent}\n\n`);
410
+ }
411
+ if (!Array.isArray(message.content)) {
412
+ return false;
413
+ }
414
+ const firstTextPart = message.content.find((part) => !!part &&
415
+ typeof part === 'object' &&
416
+ !Array.isArray(part) &&
417
+ part.type === 'text' &&
418
+ typeof part.text === 'string');
419
+ return (firstTextPart === null || firstTextPart === void 0 ? void 0 : firstTextPart.text) === requestedContent ||
420
+ (firstTextPart === null || firstTextPart === void 0 ? void 0 : firstTextPart.text.startsWith(`${requestedContent}\n\n`)) ||
421
+ (requestedContent.length === 0 && (firstTextPart === null || firstTextPart === void 0 ? void 0 : firstTextPart.text) === 'Please use the attached image.');
422
+ }
423
+ extractServerCompactedMessages(compactedContext) {
424
+ var _a;
425
+ const data = typeof compactedContext === 'object' && compactedContext !== null
426
+ ? compactedContext.data
427
+ : undefined;
428
+ const messages = typeof data === 'object' && data !== null
429
+ ? ((_a = data.input) !== null && _a !== void 0 ? _a : data.messages)
430
+ : undefined;
431
+ if (!Array.isArray(messages)) {
432
+ return [];
433
+ }
434
+ return messages
435
+ .filter((message) => this.isServerCompactedMessage(message))
436
+ .map((message) => ({ ...message }));
437
+ }
438
+ isServerCompactedMessage(value) {
439
+ if (!value || typeof value !== 'object') {
440
+ return false;
441
+ }
442
+ const message = value;
443
+ return typeof message.role === 'string' && message.content !== undefined;
444
+ }
283
445
  async tryRecoverPrompt(prompt, error) {
284
446
  const errorMessage = error instanceof Error ? error.message : String(error);
285
447
  if (!this.compactionOrchestrator.getReactiveLayer().isRecoverableError(errorMessage)) {
@@ -370,35 +532,34 @@ class Agent {
370
532
  return this.allowedTools;
371
533
  }
372
534
  getRecoverableResponseError(response) {
373
- var _a, _b, _c, _d;
535
+ var _a;
374
536
  const reactiveLayer = this.compactionOrchestrator.getReactiveLayer();
375
537
  const candidateMessages = this.collectResponseMessages(response);
376
538
  const recoverableMessage = candidateMessages.find((message) => reactiveLayer.isRecoverableError(message));
377
539
  if (recoverableMessage) {
378
540
  return recoverableMessage;
379
541
  }
380
- const finishReasons = [
381
- response.finish_reason,
382
- ...((_a = response.choices) !== null && _a !== void 0 ? _a : []).map((choice) => choice.finish_reason),
383
- ].filter((reason) => typeof reason === 'string');
542
+ const finishReasons = [response.finish_reason].filter((reason) => typeof reason === 'string');
384
543
  const hasLengthFinishReason = finishReasons.some((reason) => reason.toLowerCase() === 'length');
385
- const hasToolCalls = ((_c = (_b = response.tool_calls) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) > 0 ||
386
- ((_d = response.choices) !== null && _d !== void 0 ? _d : []).some((choice) => { var _a, _b, _c; return ((_c = (_b = (_a = choice.message) === null || _a === void 0 ? void 0 : _a.tool_calls) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) > 0; });
544
+ const hasToolCalls = ((_a = response.items) !== null && _a !== void 0 ? _a : []).some((item) => (item === null || item === void 0 ? void 0 : item.type) === 'function_call');
387
545
  if (hasLengthFinishReason && candidateMessages.length === 0 && !hasToolCalls) {
388
546
  return 'Too many tokens or token limit reached before producing usable output.';
389
547
  }
390
548
  return null;
391
549
  }
392
550
  collectResponseMessages(response) {
393
- var _a, _b;
551
+ var _a;
394
552
  const messages = [];
395
- if (typeof response.content === 'string' && response.content.trim().length > 0) {
396
- messages.push(response.content.trim());
553
+ const outputText = response.output_text || response.content;
554
+ if (typeof outputText === 'string' && outputText.trim().length > 0) {
555
+ messages.push(outputText.trim());
397
556
  }
398
- for (const choice of (_a = response.choices) !== null && _a !== void 0 ? _a : []) {
399
- if (typeof ((_b = choice.message) === null || _b === void 0 ? void 0 : _b.content) === 'string' &&
400
- choice.message.content.trim().length > 0) {
401
- messages.push(choice.message.content.trim());
557
+ for (const item of (_a = response.items) !== null && _a !== void 0 ? _a : []) {
558
+ if ((item === null || item === void 0 ? void 0 : item.type) === 'message' && item.role === 'assistant') {
559
+ const content = item.content;
560
+ if (typeof content === 'string' && content.trim().length > 0) {
561
+ messages.push(content.trim());
562
+ }
402
563
  }
403
564
  }
404
565
  return messages;
@@ -31,6 +31,20 @@ export declare class Tool implements ToolInterface {
31
31
  * @returns OpenAI function specification
32
32
  */
33
33
  toOpenAITool(): OpenAITool;
34
+ private getZodDef;
35
+ private getZodTypeName;
36
+ private getZodDescription;
37
+ private applyDescription;
38
+ private withDescriptionFrom;
39
+ private getObjectShape;
40
+ /**
41
+ * Converts a Zod schema to JSON Schema format for OpenAI functions.
42
+ *
43
+ * The converter intentionally checks Zod's schema metadata instead of
44
+ * relying only on instanceof. Local tools are often created in another
45
+ * workspace package with its own zod module instance, which makes
46
+ * instanceof checks fail even though the schema is valid.
47
+ */
34
48
  private zodSchemaToJsonSchema;
35
49
  /**
36
50
  * Converts individual Zod types to JSON Schema