@inkeep/agents-sdk 0.39.5 → 0.40.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 (59) hide show
  1. package/dist/_virtual/rolldown_runtime.js +7 -0
  2. package/dist/agent.d.ts +186 -0
  3. package/dist/agent.js +720 -0
  4. package/dist/agentFullClient.d.ts +22 -0
  5. package/dist/agentFullClient.js +120 -0
  6. package/dist/artifact-component.d.ts +34 -0
  7. package/dist/artifact-component.js +104 -0
  8. package/dist/builderFunctions.d.ts +283 -0
  9. package/dist/builderFunctions.js +327 -0
  10. package/dist/builderFunctionsExperimental.d.ts +24 -0
  11. package/dist/builderFunctionsExperimental.js +27 -0
  12. package/dist/builders.d.ts +111 -0
  13. package/dist/builders.js +52 -0
  14. package/dist/credential-provider.d.ts +176 -0
  15. package/dist/credential-provider.js +237 -0
  16. package/dist/credential-ref.d.ts +60 -0
  17. package/dist/credential-ref.js +33 -0
  18. package/dist/data-component.d.ts +39 -0
  19. package/dist/data-component.js +109 -0
  20. package/dist/environment-settings.d.ts +27 -0
  21. package/dist/environment-settings.js +41 -0
  22. package/dist/external-agent.d.ts +64 -0
  23. package/dist/external-agent.js +156 -0
  24. package/dist/function-tool.d.ts +37 -0
  25. package/dist/function-tool.js +66 -0
  26. package/dist/index.d.ts +19 -1825
  27. package/dist/index.js +19 -4058
  28. package/dist/module-hosted-tool-manager.d.ts +40 -0
  29. package/dist/module-hosted-tool-manager.js +359 -0
  30. package/dist/project.d.ts +214 -0
  31. package/dist/project.js +615 -0
  32. package/dist/projectFullClient.d.ts +23 -0
  33. package/dist/projectFullClient.js +162 -0
  34. package/dist/runner.d.ts +41 -0
  35. package/dist/runner.js +145 -0
  36. package/dist/status-component.d.ts +22 -0
  37. package/dist/status-component.js +36 -0
  38. package/dist/subAgent.d.ts +52 -0
  39. package/dist/subAgent.js +616 -0
  40. package/dist/telemetry-provider.d.ts +218 -0
  41. package/dist/telemetry-provider.js +390 -0
  42. package/dist/tool.d.ts +53 -0
  43. package/dist/tool.js +130 -0
  44. package/dist/types.d.ts +296 -0
  45. package/dist/types.js +39 -0
  46. package/dist/utils/generateIdFromName.d.ts +9 -0
  47. package/dist/utils/generateIdFromName.js +12 -0
  48. package/dist/utils/getFunctionToolDeps.d.ts +17 -0
  49. package/dist/utils/getFunctionToolDeps.js +131 -0
  50. package/dist/utils/tool-normalization.d.ts +42 -0
  51. package/dist/utils/tool-normalization.js +41 -0
  52. package/dist/utils/validateFunction.d.ts +10 -0
  53. package/dist/utils/validateFunction.js +13 -0
  54. package/package.json +11 -16
  55. package/dist/index.cjs +0 -4147
  56. package/dist/index.d.cts +0 -1825
  57. package/dist/index.d.cts.map +0 -1
  58. package/dist/index.d.ts.map +0 -1
  59. package/dist/index.js.map +0 -1
package/dist/tool.js ADDED
@@ -0,0 +1,130 @@
1
+ import { getLogger, normalizeToolSelections } from "@inkeep/agents-core";
2
+
3
+ //#region src/tool.ts
4
+ const logger = getLogger("tool");
5
+ var Tool = class {
6
+ config;
7
+ baseURL;
8
+ tenantId;
9
+ initialized = false;
10
+ projectId;
11
+ constructor(config) {
12
+ this.config = config;
13
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
14
+ this.tenantId = "default";
15
+ this.projectId = "default";
16
+ logger.info({
17
+ Id: this.getId(),
18
+ Name: config.name
19
+ }, "Tool constructor initialized");
20
+ }
21
+ setContext(tenantId, projectId, baseURL) {
22
+ this.tenantId = tenantId;
23
+ this.projectId = projectId;
24
+ if (baseURL) this.baseURL = baseURL;
25
+ }
26
+ getId() {
27
+ return this.config.id;
28
+ }
29
+ getName() {
30
+ return this.config.name;
31
+ }
32
+ getDescription() {
33
+ return this.config.description || "";
34
+ }
35
+ getServerUrl() {
36
+ return this.config.serverUrl;
37
+ }
38
+ getActiveTools() {
39
+ return this.config.activeTools;
40
+ }
41
+ getCredentialReferenceId() {
42
+ return this.config.credential?.id;
43
+ }
44
+ async init(options) {
45
+ if (this.initialized) return;
46
+ try {
47
+ if (!options?.skipDatabaseRegistration) await this.upsertTool();
48
+ logger.info({ toolId: this.getId() }, "Tool initialized successfully");
49
+ this.initialized = true;
50
+ } catch (error) {
51
+ logger.error({
52
+ toolId: this.getId(),
53
+ error: error instanceof Error ? error.message : "Unknown error"
54
+ }, "Failed to initialize tool");
55
+ throw error;
56
+ }
57
+ }
58
+ async upsertTool() {
59
+ const toolDataForUpdate = {
60
+ id: this.getId(),
61
+ name: this.config.name,
62
+ credentialReferenceId: this.config.credential?.id ?? null,
63
+ headers: this.config.headers ?? null,
64
+ imageUrl: this.config.imageUrl,
65
+ config: {
66
+ type: "mcp",
67
+ mcp: {
68
+ server: { url: this.config.serverUrl },
69
+ transport: this.config.transport,
70
+ activeTools: this.config.activeTools
71
+ }
72
+ }
73
+ };
74
+ const toolDataForCreate = { ...toolDataForUpdate };
75
+ logger.info({ toolDataForCreate }, "toolDataForCreate");
76
+ const updateResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/tools/${this.getId()}`, {
77
+ method: "PUT",
78
+ headers: { "Content-Type": "application/json" },
79
+ body: JSON.stringify(toolDataForUpdate)
80
+ });
81
+ logger.info({ updateResponse }, "tool updateResponse");
82
+ if (updateResponse.ok) {
83
+ logger.info({ toolId: this.getId() }, "Tool updated successfully");
84
+ return;
85
+ }
86
+ if (updateResponse.status === 404) {
87
+ logger.info({ toolId: this.getId() }, "Tool not found, creating new tool");
88
+ const createResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/tools`, {
89
+ method: "POST",
90
+ headers: { "Content-Type": "application/json" },
91
+ body: JSON.stringify(toolDataForCreate)
92
+ });
93
+ if (!createResponse.ok) throw new Error(`Failed to create tool: ${createResponse.status}`);
94
+ logger.info({ toolId: this.getId() }, "Tool created successfully");
95
+ return;
96
+ }
97
+ throw new Error(`Failed to update tool: ${updateResponse.status}`);
98
+ }
99
+ /**
100
+ * Creates a new AgentMcpConfig with the given configuration.
101
+ *
102
+ * @param config - The configuration for the AgentMcpConfig
103
+ * @returns A new AgentMcpConfig
104
+ *
105
+ * example:
106
+ * ```typescript
107
+ * const tool = new Tool({
108
+ * id: 'tool-id',
109
+ * name: 'Tool Name',
110
+ * serverUrl: 'https://example.com/mcp',
111
+ * });
112
+ * const agentMcpConfig = tool.with({ selectedTools: ['tool-1', 'tool-2'], headers: { 'Authorization': 'Bearer token' } });
113
+ * ```
114
+ */
115
+ with(config) {
116
+ const { selectedTools, toolPolicies } = normalizeToolSelections(config.selectedTools ?? void 0);
117
+ const isUnspecified = config.selectedTools === void 0 || config.selectedTools === null;
118
+ const resolvedSelectedTools = isUnspecified ? void 0 : selectedTools;
119
+ const resolvedToolPolicies = isUnspecified || Object.keys(toolPolicies).length === 0 ? void 0 : toolPolicies;
120
+ return {
121
+ server: this,
122
+ selectedTools: resolvedSelectedTools,
123
+ headers: config.headers,
124
+ toolPolicies: resolvedToolPolicies
125
+ };
126
+ }
127
+ };
128
+
129
+ //#endregion
130
+ export { Tool };
@@ -0,0 +1,296 @@
1
+ import { ArtifactComponentInterface } from "./artifact-component.js";
2
+ import { Tool } from "./tool.js";
3
+ import { AgentMcpConfig } from "./builders.js";
4
+ import { DataComponentInterface } from "./data-component.js";
5
+ import { ExternalAgentConfig } from "./external-agent.js";
6
+ import { FunctionTool } from "./function-tool.js";
7
+ import { AgentConversationHistoryConfig, AgentStopWhen, ArtifactComponentApiInsert, CredentialReferenceApiInsert, DataComponentApiInsert, FullAgentDefinition, FunctionToolConfig, McpTransportConfig, ModelSettings, StatusUpdateSettings, SubAgentApiInsert, ToolInsert, ToolPolicy } from "@inkeep/agents-core";
8
+ import { z } from "zod";
9
+
10
+ //#region src/types.d.ts
11
+ interface ArtifactComponentWithZodProps {
12
+ id: string;
13
+ name: string;
14
+ description: string;
15
+ props?: z.ZodObject<any>;
16
+ }
17
+ interface DataComponentWithZodProps {
18
+ id: string;
19
+ name: string;
20
+ description: string;
21
+ props?: z.ZodObject<any>;
22
+ }
23
+ /**
24
+ * Tool instance that may have additional metadata attached during agent processing
25
+ */
26
+ type AgentTool = (Tool & {
27
+ selectedTools?: string[];
28
+ headers?: Record<string, string>;
29
+ toolPolicies?: Record<string, ToolPolicy>;
30
+ }) | (FunctionTool & {
31
+ selectedTools?: string[];
32
+ headers?: Record<string, string>;
33
+ toolPolicies?: Record<string, ToolPolicy>;
34
+ });
35
+ interface UserMessage {
36
+ role: 'user';
37
+ content: string;
38
+ }
39
+ interface AssistantMessage {
40
+ role: 'assistant';
41
+ content: string;
42
+ toolCalls?: ToolCall[];
43
+ }
44
+ interface ToolMessage {
45
+ role: 'tool';
46
+ content: string;
47
+ toolCallId: string;
48
+ }
49
+ interface SystemMessage {
50
+ role: 'system';
51
+ content: string;
52
+ }
53
+ type Message = UserMessage | AssistantMessage | ToolMessage | SystemMessage;
54
+ type MessageInput = string | string[] | Message | Message[];
55
+ interface ToolCall {
56
+ id: string;
57
+ type: 'function';
58
+ function: {
59
+ name: string;
60
+ arguments: string;
61
+ };
62
+ }
63
+ interface ToolResult {
64
+ id: string;
65
+ result: any;
66
+ error?: string;
67
+ }
68
+ type AllDelegateInputInterface = SubAgentInterface | subAgentExternalAgentInterface | ExternalAgentInterface | AgentInterface | subAgentTeamAgentInterface;
69
+ type AllDelegateOutputInterface = SubAgentInterface | subAgentExternalAgentInterface | subAgentTeamAgentInterface;
70
+ type SubAgentCanUseType = Tool | AgentMcpConfig | FunctionTool;
71
+ interface SubAgentConfig extends Omit<SubAgentApiInsert, 'projectId'> {
72
+ type?: 'internal';
73
+ canUse?: () => SubAgentCanUseType[];
74
+ canTransferTo?: () => SubAgentInterface[];
75
+ canDelegateTo?: () => AllDelegateInputInterface[];
76
+ dataComponents?: () => (DataComponentApiInsert | DataComponentInterface | DataComponentWithZodProps)[];
77
+ artifactComponents?: () => (ArtifactComponentApiInsert | ArtifactComponentInterface | ArtifactComponentWithZodProps)[];
78
+ conversationHistoryConfig?: AgentConversationHistoryConfig;
79
+ }
80
+ interface ToolConfig extends ToolInsert {
81
+ execute: (params: any) => Promise<any>;
82
+ parameters?: Record<string, any>;
83
+ schema?: z.ZodJSONSchema;
84
+ }
85
+ interface ServerConfig {
86
+ type: string;
87
+ version?: string;
88
+ }
89
+ interface MCPToolConfig {
90
+ id: string;
91
+ name: string;
92
+ tenantId?: string;
93
+ description?: string;
94
+ credential?: CredentialReferenceApiInsert;
95
+ server?: ServerConfig;
96
+ serverUrl: string;
97
+ toolName?: string;
98
+ activeTools?: string[];
99
+ headers?: Record<string, string>;
100
+ mcpType?: 'nango' | 'generic';
101
+ transport?: McpTransportConfig;
102
+ imageUrl?: string;
103
+ }
104
+ interface FetchDefinitionConfig {
105
+ id: string;
106
+ name?: string;
107
+ trigger: 'initialization' | 'invocation';
108
+ url: string;
109
+ method?: string;
110
+ headers?: Record<string, string>;
111
+ body?: Record<string, unknown>;
112
+ transform?: string;
113
+ responseSchema?: z.ZodSchema<any>;
114
+ defaultValue?: unknown;
115
+ timeout?: number;
116
+ credential?: CredentialReferenceApiInsert;
117
+ }
118
+ interface RequestSchemaDefinition {
119
+ body?: z.ZodSchema<any>;
120
+ headers?: z.ZodSchema<any>;
121
+ query?: z.ZodSchema<any>;
122
+ params?: z.ZodSchema<any>;
123
+ }
124
+ interface RequestSchemaConfig {
125
+ schemas: RequestSchemaDefinition;
126
+ optional?: ('body' | 'headers' | 'query' | 'params')[];
127
+ }
128
+ interface TransferConfig {
129
+ agent: SubAgentInterface;
130
+ description?: string;
131
+ condition?: (context: any) => boolean;
132
+ }
133
+ interface GenerateOptions {
134
+ maxTurns?: number;
135
+ maxSteps?: number;
136
+ temperature?: number;
137
+ toolChoice?: 'auto' | 'none' | string;
138
+ resourceId?: string;
139
+ conversationId?: string;
140
+ stream?: boolean;
141
+ customBodyParams?: Record<string, unknown>;
142
+ }
143
+ interface AgentResponse {
144
+ id?: string;
145
+ text: string;
146
+ toolCalls?: ToolCall[];
147
+ transfer?: TransferConfig;
148
+ finishReason: 'completed' | 'tool_calls' | 'transfer' | 'max_turns' | 'error';
149
+ usage?: {
150
+ inputTokens: number;
151
+ outputTokens: number;
152
+ totalTokens?: number;
153
+ };
154
+ metadata?: Record<string, any>;
155
+ }
156
+ interface StreamResponse {
157
+ textStream?: AsyncGenerator<string>;
158
+ eventStream?: AsyncGenerator<StreamEvent>;
159
+ }
160
+ interface StreamEvent {
161
+ type: 'text' | 'tool_call' | 'transfer' | 'error' | 'done';
162
+ data: any;
163
+ timestamp: Date;
164
+ }
165
+ interface RunResult {
166
+ finalOutput: string;
167
+ agent: SubAgentInterface;
168
+ turnCount: number;
169
+ usage?: {
170
+ inputTokens: number;
171
+ outputTokens: number;
172
+ totalTokens?: number;
173
+ };
174
+ metadata?: {
175
+ toolCalls: ToolCall[];
176
+ transfers: TransferConfig[];
177
+ };
178
+ }
179
+ interface AgentConfig {
180
+ id: string;
181
+ name?: string;
182
+ description?: string;
183
+ defaultSubAgent: SubAgentInterface;
184
+ subAgents?: () => SubAgentInterface[];
185
+ contextConfig?: any;
186
+ credentials?: () => CredentialReferenceApiInsert[];
187
+ stopWhen?: AgentStopWhen;
188
+ prompt?: string;
189
+ models?: {
190
+ base?: ModelSettings;
191
+ structuredOutput?: ModelSettings;
192
+ summarizer?: ModelSettings;
193
+ };
194
+ statusUpdates?: StatusUpdateSettings;
195
+ }
196
+ declare class AgentError extends Error {
197
+ code?: string | undefined;
198
+ details?: any | undefined;
199
+ constructor(message: string, code?: string | undefined, details?: any | undefined);
200
+ }
201
+ declare class MaxTurnsExceededError extends AgentError {
202
+ constructor(maxTurns: number);
203
+ }
204
+ declare class ToolExecutionError extends AgentError {
205
+ constructor(toolName: string, originalError: Error);
206
+ }
207
+ declare class TransferError extends AgentError {
208
+ constructor(sourceAgent: string, targetAgent: string, reason: string);
209
+ }
210
+ interface SubAgentInterface {
211
+ config: SubAgentConfig;
212
+ type: 'internal';
213
+ init(): Promise<void>;
214
+ getId(): string;
215
+ getName(): string;
216
+ getDescription(): string;
217
+ getInstructions(): string;
218
+ getTools(): Record<string, AgentTool>;
219
+ getTransfers(): SubAgentInterface[];
220
+ getDelegates(): AllDelegateOutputInterface[];
221
+ getSubAgentDelegates(): SubAgentInterface[];
222
+ getExternalAgentDelegates(): subAgentExternalAgentInterface[];
223
+ getDataComponents(): DataComponentApiInsert[];
224
+ getArtifactComponents(): ArtifactComponentApiInsert[];
225
+ setContext(tenantId: string, projectId: string, baseURL?: string): void;
226
+ addTool(name: string, tool: any): void;
227
+ addTransfer(...agents: SubAgentInterface[]): void;
228
+ addDelegate(...agents: AllDelegateInputInterface[]): void;
229
+ }
230
+ interface ExternalAgentInterface {
231
+ config: ExternalAgentConfig;
232
+ type: 'external';
233
+ init(): Promise<void>;
234
+ getId(): string;
235
+ getName(): string;
236
+ getDescription(): string;
237
+ getBaseUrl(): string;
238
+ setContext?(tenantId: string, projectId: string): void;
239
+ with(options: {
240
+ headers?: Record<string, string>;
241
+ }): subAgentExternalAgentInterface;
242
+ getCredentialReferenceId(): string | undefined;
243
+ getCredentialReference(): CredentialReferenceApiInsert | undefined;
244
+ }
245
+ type subAgentExternalAgentInterface = {
246
+ externalAgent: ExternalAgentInterface;
247
+ headers?: Record<string, string>;
248
+ };
249
+ type subAgentTeamAgentInterface = {
250
+ agent: AgentInterface;
251
+ headers?: Record<string, string>;
252
+ };
253
+ interface AgentInterface {
254
+ init(): Promise<void>;
255
+ setConfig(tenantId: string, projectId: string, apiUrl: string): void;
256
+ getId(): string;
257
+ getName(): string;
258
+ getDescription(): string | undefined;
259
+ getTenantId(): string;
260
+ generate(input: MessageInput, options?: GenerateOptions): Promise<string>;
261
+ stream(input: MessageInput, options?: GenerateOptions): Promise<StreamResponse>;
262
+ generateStream(input: MessageInput, options?: GenerateOptions): Promise<StreamResponse>;
263
+ getDefaultSubAgent(): SubAgentInterface | undefined;
264
+ getSubAgent(name: string): SubAgentInterface | undefined;
265
+ getSubAgents(): SubAgentInterface[];
266
+ toFullAgentDefinition(): Promise<FullAgentDefinition>;
267
+ with(options: {
268
+ headers?: Record<string, string>;
269
+ }): subAgentTeamAgentInterface;
270
+ }
271
+ interface BuilderToolConfig {
272
+ name: string;
273
+ description: string;
274
+ config: {
275
+ type: 'mcp';
276
+ mcp: {
277
+ server: {
278
+ url: string;
279
+ };
280
+ };
281
+ };
282
+ parameters?: Record<string, any>;
283
+ }
284
+ interface BuilderRelationConfig {
285
+ targetAgent: string;
286
+ relationType: 'transfer' | 'delegate';
287
+ }
288
+ interface BuilderAgentConfig {
289
+ name: string;
290
+ description: string;
291
+ instructions: string;
292
+ tools: BuilderToolConfig[];
293
+ relations?: BuilderRelationConfig[];
294
+ }
295
+ //#endregion
296
+ export { AgentConfig, AgentError, AgentInterface, AgentResponse, AgentTool, AllDelegateInputInterface, AllDelegateOutputInterface, ArtifactComponentWithZodProps, AssistantMessage, BuilderAgentConfig, BuilderRelationConfig, BuilderToolConfig, DataComponentWithZodProps, ExternalAgentInterface, FetchDefinitionConfig, type FunctionToolConfig, GenerateOptions, MCPToolConfig, MaxTurnsExceededError, Message, MessageInput, type ModelSettings, RequestSchemaConfig, RequestSchemaDefinition, RunResult, ServerConfig, StreamEvent, StreamResponse, SubAgentCanUseType, SubAgentConfig, SubAgentInterface, SystemMessage, ToolCall, ToolConfig, ToolExecutionError, ToolMessage, ToolResult, TransferConfig, TransferError, UserMessage, subAgentExternalAgentInterface, subAgentTeamAgentInterface };
package/dist/types.js ADDED
@@ -0,0 +1,39 @@
1
+ //#region src/types.ts
2
+ var AgentError = class extends Error {
3
+ constructor(message, code, details) {
4
+ super(message);
5
+ this.code = code;
6
+ this.details = details;
7
+ this.name = "AgentError";
8
+ }
9
+ };
10
+ var MaxTurnsExceededError = class extends AgentError {
11
+ constructor(maxTurns) {
12
+ super(`Maximum turns (${maxTurns}) exceeded`);
13
+ this.code = "MAX_TURNS_EXCEEDED";
14
+ }
15
+ };
16
+ var ToolExecutionError = class extends AgentError {
17
+ constructor(toolName, originalError) {
18
+ super(`Tool '${toolName}' execution failed: ${originalError.message}`);
19
+ this.code = "TOOL_EXECUTION_ERROR";
20
+ this.details = {
21
+ toolName,
22
+ originalError
23
+ };
24
+ }
25
+ };
26
+ var TransferError = class extends AgentError {
27
+ constructor(sourceAgent, targetAgent, reason) {
28
+ super(`Transfer from '${sourceAgent}' to '${targetAgent}' failed: ${reason}`);
29
+ this.code = "TRANSFER_ERROR";
30
+ this.details = {
31
+ sourceAgent,
32
+ targetAgent,
33
+ reason
34
+ };
35
+ }
36
+ };
37
+
38
+ //#endregion
39
+ export { AgentError, MaxTurnsExceededError, ToolExecutionError, TransferError };
@@ -0,0 +1,9 @@
1
+ //#region src/utils/generateIdFromName.d.ts
2
+ /**
3
+ * Generates a kebab-case ID from a name string
4
+ * @param name - The name to convert
5
+ * @returns A kebab-case ID
6
+ */
7
+ declare function generateIdFromName(name: string): string;
8
+ //#endregion
9
+ export { generateIdFromName };
@@ -0,0 +1,12 @@
1
+ //#region src/utils/generateIdFromName.ts
2
+ /**
3
+ * Generates a kebab-case ID from a name string
4
+ * @param name - The name to convert
5
+ * @returns A kebab-case ID
6
+ */
7
+ function generateIdFromName(name) {
8
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
9
+ }
10
+
11
+ //#endregion
12
+ export { generateIdFromName };
@@ -0,0 +1,17 @@
1
+ //#region src/utils/getFunctionToolDeps.d.ts
2
+ declare const getFunctionToolDeps: (name: string, code: string) => Record<string, string | false>;
3
+ type VersionResult = {
4
+ exact: string;
5
+ } | {
6
+ range: string;
7
+ unresolved: true;
8
+ };
9
+ type ToolManifest = {
10
+ dependencies: Record<string, string | false>;
11
+ warnings: string[];
12
+ };
13
+ declare function collectDepsFromCodeTS(code: string): Set<string>;
14
+ declare function resolveInstalledVersion(pkg: string, projectRoot: string): VersionResult | null;
15
+ declare function buildToolManifestFromCodeTS(code: string, projectRoot?: string): ToolManifest;
16
+ //#endregion
17
+ export { ToolManifest, buildToolManifestFromCodeTS, collectDepsFromCodeTS, getFunctionToolDeps, resolveInstalledVersion };
@@ -0,0 +1,131 @@
1
+ import { builtinModules } from "node:module";
2
+ import { getLogger } from "@inkeep/agents-core";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import * as lockfile from "@yarnpkg/lockfile";
6
+ import * as yaml from "js-yaml";
7
+ import ts from "typescript";
8
+
9
+ //#region src/utils/getFunctionToolDeps.ts
10
+ const logger = getLogger("function-tool");
11
+ const getFunctionToolDeps = (name, code) => {
12
+ const { dependencies, warnings } = buildToolManifestFromCodeTS(code);
13
+ if (warnings.length > 0) logger.warn({ warnings }, `FunctionTool dependencies warnings for ${name}`);
14
+ return dependencies;
15
+ };
16
+ const NODE_BUILTINS = new Set(builtinModules.concat(builtinModules.map((m) => `node:${m}`)));
17
+ const isExternal = (spec) => !spec.startsWith(".") && !spec.startsWith("/") && !NODE_BUILTINS.has(spec);
18
+ const collapseSubpath = (spec) => {
19
+ if (spec.startsWith("@")) {
20
+ const [scope, name] = spec.split("/");
21
+ return `${scope}/${name ?? ""}`;
22
+ }
23
+ return spec.split("/")[0];
24
+ };
25
+ const readJSON = (p) => JSON.parse(fs.readFileSync(p, "utf8"));
26
+ const findUp = (start, file) => {
27
+ let dir = path.resolve(start);
28
+ if (fs.existsSync(dir) && fs.statSync(dir).isFile()) dir = path.dirname(dir);
29
+ for (;;) {
30
+ const candidate = path.join(dir, file);
31
+ if (fs.existsSync(candidate)) return candidate;
32
+ const parent = path.dirname(dir);
33
+ if (parent === dir) return null;
34
+ dir = parent;
35
+ }
36
+ };
37
+ function collectDepsFromCodeTS(code) {
38
+ const info = ts.preProcessFile(code, true, true);
39
+ const add = /* @__PURE__ */ new Set();
40
+ const push = (spec) => {
41
+ if (isExternal(spec)) add.add(collapseSubpath(spec));
42
+ };
43
+ for (const f of info.importedFiles) {
44
+ const spec = f.fileName;
45
+ if (spec) push(spec);
46
+ }
47
+ const requireLike = /(?:require|import)\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
48
+ let m;
49
+ while (m = requireLike.exec(code)) push(m[2]);
50
+ return add;
51
+ }
52
+ function resolveInstalledVersion(pkg, projectRoot) {
53
+ const pnpmLock = findUp(projectRoot, "pnpm-lock.yaml");
54
+ if (pnpmLock) {
55
+ const pkgs = yaml.load(fs.readFileSync(pnpmLock, "utf8"))?.packages ?? {};
56
+ for (const key of Object.keys(pkgs)) if (key.startsWith(`${pkg}@`)) {
57
+ const ver = key.slice(key.indexOf("@") + 1);
58
+ if (ver) return { exact: String(ver) };
59
+ }
60
+ }
61
+ const npmLock = findUp(projectRoot, "package-lock.json");
62
+ if (npmLock) {
63
+ const lock = readJSON(npmLock);
64
+ if (lock.packages?.[`node_modules/${pkg}`]?.version) return { exact: String(lock.packages[`node_modules/${pkg}`].version) };
65
+ if (lock.dependencies?.[pkg]?.version) return { exact: String(lock.dependencies[pkg].version) };
66
+ }
67
+ const yarnLock = findUp(projectRoot, "yarn.lock");
68
+ if (yarnLock) {
69
+ const parsed = lockfile.parse(fs.readFileSync(yarnLock, "utf8"));
70
+ if (parsed.type === "success") {
71
+ for (const [key, val] of Object.entries(parsed.object)) if (key === pkg || key.startsWith(`${pkg}@`)) {
72
+ const ver = val.version;
73
+ if (ver) return { exact: String(ver) };
74
+ }
75
+ }
76
+ }
77
+ const host = {
78
+ fileExists: fs.existsSync,
79
+ readFile: (p) => fs.readFileSync(p, "utf8"),
80
+ realpath: (p) => fs.realpathSync.native?.(p) ?? fs.realpathSync(p),
81
+ directoryExists: (d) => {
82
+ try {
83
+ return fs.statSync(d).isDirectory();
84
+ } catch {
85
+ return false;
86
+ }
87
+ },
88
+ getCurrentDirectory: () => projectRoot,
89
+ getDirectories: (d) => fs.readdirSync(d, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name)
90
+ };
91
+ const pkgJsonPath = ts.resolveModuleName(`${pkg}/package.json`, path.join(projectRoot, "__fake.ts"), {}, host, ts.ModuleKind.NodeNext)?.resolvedModule?.resolvedFileName ?? findUp(path.join(projectRoot, "node_modules", pkg), "package.json");
92
+ if (pkgJsonPath && fs.existsSync(pkgJsonPath)) try {
93
+ const version = readJSON(pkgJsonPath).version;
94
+ if (version) return { exact: String(version) };
95
+ } catch {}
96
+ const hostPkg = findUp(projectRoot, "package.json");
97
+ if (hostPkg) {
98
+ const hostJson = readJSON(hostPkg);
99
+ const range = hostJson.dependencies?.[pkg] ?? hostJson.devDependencies?.[pkg] ?? hostJson.optionalDependencies?.[pkg];
100
+ if (range) return {
101
+ range: String(range),
102
+ unresolved: true
103
+ };
104
+ }
105
+ return null;
106
+ }
107
+ function buildToolManifestFromCodeTS(code, projectRoot = process.cwd()) {
108
+ const deps = collectDepsFromCodeTS(code);
109
+ const warnings = [];
110
+ const dependencies = {};
111
+ for (const pkg of deps) try {
112
+ const v = resolveInstalledVersion(pkg, projectRoot);
113
+ if (!v) {
114
+ warnings.push(`Could not resolve version for "${pkg}"`);
115
+ continue;
116
+ }
117
+ if ("unresolved" in v) {
118
+ warnings.push(`Using range for "${pkg}" -> ${v.range} (no lockfile / not installed)`);
119
+ dependencies[pkg] = v.range;
120
+ } else dependencies[pkg] = v.exact;
121
+ } catch {
122
+ dependencies[pkg] = false;
123
+ }
124
+ return {
125
+ dependencies,
126
+ warnings
127
+ };
128
+ }
129
+
130
+ //#endregion
131
+ export { buildToolManifestFromCodeTS, collectDepsFromCodeTS, getFunctionToolDeps, resolveInstalledVersion };
@@ -0,0 +1,42 @@
1
+ import { Tool } from "../tool.js";
2
+ import { AgentMcpConfig } from "../builders.js";
3
+ import { SubAgentCanUseType } from "../types.js";
4
+ import { ToolPolicy } from "@inkeep/agents-core";
5
+
6
+ //#region src/utils/tool-normalization.d.ts
7
+
8
+ /**
9
+ * Type guard to check if a value is an AgentMcpConfig
10
+ */
11
+ declare function isAgentMcpConfig(value: unknown): value is AgentMcpConfig;
12
+ /**
13
+ * Type guard to check if a value is a Tool instance
14
+ */
15
+ declare function isTool(value: unknown): value is Tool;
16
+ /**
17
+ * Type guard to narrow down AgentCanUseType
18
+ */
19
+ declare function isAgentCanUseType(value: unknown): value is SubAgentCanUseType;
20
+ /**
21
+ * Normalized tool representation with proper typing
22
+ */
23
+ interface NormalizedToolInfo {
24
+ /** The underlying Tool instance */
25
+ tool: Tool;
26
+ /** The tool ID */
27
+ toolId: string;
28
+ /** Selected tools (only present for AgentMcpConfig) */
29
+ selectedTools?: string[];
30
+ /** Agent-specific headers (only present for AgentMcpConfig) */
31
+ headers?: Record<string, string>;
32
+ /** Per-tool policies like needsApproval (only present for AgentMcpConfig) */
33
+ toolPolicies?: Record<string, ToolPolicy>;
34
+ /** Whether this came from an AgentMcpConfig wrapper */
35
+ isWrapped: boolean;
36
+ }
37
+ /**
38
+ * Safely extracts tool information from AgentCanUseType with proper typing
39
+ */
40
+ declare function normalizeAgentCanUseType(value: SubAgentCanUseType, fallbackName?: string): NormalizedToolInfo;
41
+ //#endregion
42
+ export { NormalizedToolInfo, isAgentCanUseType, isAgentMcpConfig, isTool, normalizeAgentCanUseType };