@librechat/agents 3.1.83 → 3.1.85
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.
- package/dist/cjs/agents/AgentContext.cjs +26 -3
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +1 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +2 -1
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +5 -1
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +3 -2
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/main.cjs +4 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +5 -2
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +26 -24
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +28 -2
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +130 -56
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +7 -5
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +52 -13
- package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ptcTimeout.cjs +56 -0
- package/dist/cjs/tools/ptcTimeout.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +27 -4
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +2 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +5 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +3 -2
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -3
- package/dist/esm/tools/BashExecutor.mjs +6 -3
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +26 -25
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +27 -3
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +131 -58
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +7 -5
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +54 -15
- package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ptcTimeout.mjs +50 -0
- package/dist/esm/tools/ptcTimeout.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +3 -1
- package/dist/types/common/enum.d.ts +2 -1
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +4 -36
- package/dist/types/tools/CodeExecutor.d.ts +5 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +18 -39
- package/dist/types/tools/ptcTimeout.d.ts +25 -0
- package/dist/types/types/tools.d.ts +8 -0
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +32 -3
- package/src/agents/__tests__/AgentContext.test.ts +36 -3
- package/src/common/enum.ts +1 -0
- package/src/events.ts +4 -1
- package/src/graphs/MultiAgentGraph.ts +3 -2
- package/src/graphs/__tests__/composition.smoke.test.ts +84 -2
- package/src/tools/BashExecutor.ts +14 -3
- package/src/tools/BashProgrammaticToolCalling.ts +37 -25
- package/src/tools/CodeExecutor.ts +36 -2
- package/src/tools/ProgrammaticToolCalling.ts +206 -53
- package/src/tools/ToolNode.ts +3 -4
- package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +424 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +31 -1
- package/src/tools/local/LocalProgrammaticToolCalling.ts +94 -13
- package/src/tools/ptcTimeout.ts +89 -0
- package/src/types/tools.ts +12 -0
|
@@ -3,24 +3,63 @@ import { createServer } from 'http';
|
|
|
3
3
|
import { tool } from '@langchain/core/tools';
|
|
4
4
|
import { executeHooks } from '../../hooks/executeHooks.mjs';
|
|
5
5
|
import '../../hooks/createWorkspacePolicyHook.mjs';
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
6
|
+
import { ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, filterToolsByUsage, formatCompletedResponse, ProgrammaticToolCallingSchema, executeTools, normalizeToPythonIdentifier } from '../ProgrammaticToolCalling.mjs';
|
|
7
|
+
import { BashProgrammaticToolCallingDescription, normalizeToBashIdentifier, filterBashToolsByUsage, BashProgrammaticToolCallingSchema } from '../BashProgrammaticToolCalling.mjs';
|
|
8
8
|
import { shellQuote, executeLocalBash, executeLocalCode, getLocalSessionId } from './LocalExecutionEngine.mjs';
|
|
9
9
|
import { Constants } from '../../common/enum.mjs';
|
|
10
10
|
|
|
11
11
|
const DEFAULT_TIMEOUT = 60000;
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
12
|
+
const LOCAL_MIN_TIMEOUT = 1000;
|
|
13
|
+
const LOCAL_MAX_TIMEOUT = 300000;
|
|
14
|
+
function normalizeLocalTimeout(timeoutMs) {
|
|
15
|
+
if (timeoutMs == null || !Number.isFinite(timeoutMs)) {
|
|
16
|
+
return DEFAULT_TIMEOUT;
|
|
17
|
+
}
|
|
18
|
+
return Math.max(LOCAL_MIN_TIMEOUT, Math.floor(timeoutMs));
|
|
19
|
+
}
|
|
20
|
+
function formatLocalTimeout(timeoutMs) {
|
|
21
|
+
return timeoutMs % 1000 === 0
|
|
22
|
+
? `${timeoutMs / 1000} seconds`
|
|
23
|
+
: `${timeoutMs} milliseconds`;
|
|
24
|
+
}
|
|
25
|
+
function createLocalTimeoutSchema(timeoutMs) {
|
|
26
|
+
const defaultTimeout = normalizeLocalTimeout(timeoutMs);
|
|
27
|
+
const maxTimeout = Math.max(LOCAL_MAX_TIMEOUT, defaultTimeout);
|
|
28
|
+
const formattedDefault = formatLocalTimeout(defaultTimeout);
|
|
29
|
+
const formattedMax = formatLocalTimeout(maxTimeout);
|
|
30
|
+
return {
|
|
31
|
+
type: 'integer',
|
|
32
|
+
minimum: LOCAL_MIN_TIMEOUT,
|
|
33
|
+
maximum: maxTimeout,
|
|
34
|
+
default: defaultTimeout,
|
|
35
|
+
description: 'Maximum local execution time in milliseconds. ' +
|
|
36
|
+
`Default: ${formattedDefault}. Max: ${formattedMax}.`,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function createLocalProgrammaticToolCallingSchema(localConfig = {}) {
|
|
40
|
+
return {
|
|
41
|
+
...ProgrammaticToolCallingSchema,
|
|
42
|
+
properties: {
|
|
43
|
+
...ProgrammaticToolCallingSchema.properties,
|
|
44
|
+
timeout: createLocalTimeoutSchema(localConfig.timeoutMs),
|
|
45
|
+
lang: {
|
|
46
|
+
type: 'string',
|
|
47
|
+
enum: ['py', 'python', 'bash', 'sh'],
|
|
48
|
+
default: 'bash',
|
|
49
|
+
description: 'Local engine runtime for orchestration code. Defaults to bash; use py/python for Python orchestration.',
|
|
50
|
+
},
|
|
21
51
|
},
|
|
22
|
-
}
|
|
23
|
-
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function createLocalBashProgrammaticToolCallingSchema(localConfig = {}) {
|
|
55
|
+
return {
|
|
56
|
+
...BashProgrammaticToolCallingSchema,
|
|
57
|
+
properties: {
|
|
58
|
+
...BashProgrammaticToolCallingSchema.properties,
|
|
59
|
+
timeout: createLocalTimeoutSchema(localConfig.timeoutMs),
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
24
63
|
const BRIDGE_AUTH_HEADER = 'x-librechat-bridge-token';
|
|
25
64
|
function constantTimeEquals(a, b) {
|
|
26
65
|
const aBuf = Buffer.from(a, 'utf8');
|
|
@@ -423,7 +462,7 @@ function createLocalProgrammaticToolCallingTool(localConfig = {}) {
|
|
|
423
462
|
}, {
|
|
424
463
|
name: ProgrammaticToolCallingName,
|
|
425
464
|
description: `${ProgrammaticToolCallingDescription}\n\nLocal engine: runs bash by default, or Python when \`lang\` is \`py\` or \`python\`, on the host machine and calls tools through an in-process localhost bridge.`,
|
|
426
|
-
schema:
|
|
465
|
+
schema: createLocalProgrammaticToolCallingSchema(localConfig),
|
|
427
466
|
responseFormat: Constants.CONTENT_AND_ARTIFACT,
|
|
428
467
|
});
|
|
429
468
|
}
|
|
@@ -439,7 +478,7 @@ function createLocalBashProgrammaticToolCallingTool(localConfig = {}) {
|
|
|
439
478
|
}, {
|
|
440
479
|
name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
|
|
441
480
|
description: `${BashProgrammaticToolCallingDescription}\n\nLocal engine: runs this bash orchestration code on the host machine and calls tools through an in-process localhost bridge.`,
|
|
442
|
-
schema:
|
|
481
|
+
schema: createLocalBashProgrammaticToolCallingSchema(localConfig),
|
|
443
482
|
responseFormat: Constants.CONTENT_AND_ARTIFACT,
|
|
444
483
|
});
|
|
445
484
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LocalProgrammaticToolCalling.mjs","sources":["../../../../src/tools/local/LocalProgrammaticToolCalling.ts"],"sourcesContent":["import { randomBytes, randomUUID, timingSafeEqual } from 'crypto';\nimport { createServer } from 'http';\nimport { tool } from '@langchain/core/tools';\nimport type { AddressInfo } from 'net';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { executeHooks } from '@/hooks';\nimport {\n executeTools,\n filterToolsByUsage,\n formatCompletedResponse,\n normalizeToPythonIdentifier,\n ProgrammaticToolCallingName,\n ProgrammaticToolCallingSchema,\n ProgrammaticToolCallingDescription,\n} from '@/tools/ProgrammaticToolCalling';\nimport {\n BashProgrammaticToolCallingSchema,\n BashProgrammaticToolCallingDescription,\n filterBashToolsByUsage,\n normalizeToBashIdentifier,\n} from '@/tools/BashProgrammaticToolCalling';\nimport {\n executeLocalBash,\n executeLocalCode,\n getLocalSessionId,\n shellQuote,\n} from './LocalExecutionEngine';\nimport { Constants } from '@/common';\n\nconst DEFAULT_TIMEOUT = 60000;\nconst LocalProgrammaticToolCallingSchema = {\n ...ProgrammaticToolCallingSchema,\n properties: {\n ...ProgrammaticToolCallingSchema.properties,\n lang: {\n type: 'string',\n enum: ['py', 'python', 'bash', 'sh'],\n default: 'bash',\n description:\n 'Local engine runtime for orchestration code. Defaults to bash; use py/python for Python orchestration.',\n },\n },\n} as const;\n\ntype ToolBridge = {\n url: string;\n token: string;\n close: () => Promise<void>;\n};\n\ntype ToolRequest = {\n id?: string;\n name?: string;\n input?: Record<string, unknown>;\n};\n\nconst BRIDGE_AUTH_HEADER = 'x-librechat-bridge-token';\n\nfunction constantTimeEquals(a: string, b: string): boolean {\n const aBuf = Buffer.from(a, 'utf8');\n const bBuf = Buffer.from(b, 'utf8');\n if (aBuf.length !== bBuf.length) {\n return false;\n }\n return timingSafeEqual(aBuf, bBuf);\n}\n\ntype LocalProgrammaticRuntime = 'python' | 'bash';\n\ntype LocalProgrammaticParams = {\n code: string;\n timeout?: number;\n lang?: string;\n runtime?: string;\n language?: string;\n};\n\ntype ToolFilter = (toolDefs: t.LCTool[], code: string) => t.LCTool[];\n\nfunction resolveRuntime(\n params: LocalProgrammaticParams\n): LocalProgrammaticRuntime {\n const rawRuntime = params.lang ?? params.runtime ?? params.language ?? 'bash';\n return rawRuntime === 'py' || rawRuntime === 'python' ? 'python' : 'bash';\n}\n\nfunction toSerializable(value: unknown): unknown {\n if (value === undefined) {\n return null;\n }\n return value;\n}\n\nasync function readRequestBody(req: IncomingMessage): Promise<ToolRequest> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const raw = Buffer.concat(chunks).toString('utf8');\n if (raw === '') {\n return {};\n }\n return JSON.parse(raw) as ToolRequest;\n}\n\nfunction writeJson(res: ServerResponse, status: number, value: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(value));\n}\n\n/**\n * Run the host's `PreToolUse` hook chain for a single bridge call.\n * Returns the (possibly rewritten) input and a `denyReason` if any\n * matcher returned `decision: 'deny'` or `'ask'`. `'ask'` collapses\n * to deny because the bridge can't raise a LangGraph interrupt from\n * inside an HTTP handler — fail-closed matches the rest of the SDK\n * when HITL is unavailable.\n *\n * @internal Exported for tests so the deny / allow / updatedInput /\n * ask branches can be exercised without standing up the full HTTP\n * bridge.\n */\nexport async function applyPreToolUseHooksForBridge(\n hookContext: t.ProgrammaticHookContext,\n toolName: string,\n toolUseId: string,\n toolInput: Record<string, unknown>\n): Promise<{ input: Record<string, unknown>; denyReason?: string }> {\n if (hookContext.registry == null) {\n return { input: toolInput };\n }\n const result = await executeHooks({\n registry: hookContext.registry,\n input: {\n hook_event_name: 'PreToolUse',\n runId: hookContext.runId,\n threadId: hookContext.threadId,\n agentId: hookContext.agentId,\n toolName,\n toolInput,\n toolUseId,\n stepId: '',\n turn: 0,\n },\n sessionId: hookContext.runId,\n matchQuery: toolName,\n }).catch(() => undefined);\n if (result == null) {\n return { input: toolInput };\n }\n const nextInput =\n result.updatedInput != null\n ? (result.updatedInput as Record<string, unknown>)\n : toolInput;\n if (result.decision === 'deny' || result.decision === 'ask') {\n return {\n input: nextInput,\n denyReason:\n result.reason ??\n (result.decision === 'ask'\n ? `Tool \"${toolName}\" requires human approval; bridge cannot raise an interrupt — denying.`\n : `Tool \"${toolName}\" denied by PreToolUse hook.`),\n };\n }\n return { input: nextInput };\n}\n\nasync function createToolBridge(\n toolMap: t.ToolMap,\n hookContext?: t.ProgrammaticHookContext\n): Promise<ToolBridge> {\n const token = randomBytes(32).toString('hex');\n const server = createServer((req, res) => {\n // `?mode=text` returns the already-serialized result as the body\n // (or the error message at non-2xx). Python/Node callers stay on\n // JSON; bash callers using curl can avoid pulling in a JSON\n // parser dependency (Codex P2 #19 — `python3` was a hard\n // requirement for the bash bridge, breaking minimal containers).\n const url = new URL(req.url ?? '/', 'http://127.0.0.1');\n const isTextMode = url.searchParams.get('mode') === 'text';\n if (req.method !== 'POST' || url.pathname !== '/tool') {\n if (isTextMode) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not found');\n } else {\n writeJson(res, 404, { error: 'Not found' });\n }\n return;\n }\n\n const presented = req.headers[BRIDGE_AUTH_HEADER];\n const presentedToken = Array.isArray(presented) ? presented[0] : presented;\n if (\n typeof presentedToken !== 'string' ||\n !constantTimeEquals(presentedToken, token)\n ) {\n if (isTextMode) {\n res.writeHead(401, { 'Content-Type': 'text/plain' });\n res.end('Unauthorized');\n } else {\n writeJson(res, 401, { error: 'Unauthorized' });\n }\n return;\n }\n\n readRequestBody(req)\n .then(async (body) => {\n if (typeof body.name !== 'string' || body.name === '') {\n const message = 'Tool request is missing a tool name.';\n if (isTextMode) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end(message);\n } else {\n writeJson(res, 400, {\n call_id: body.id ?? 'invalid',\n result: null,\n is_error: true,\n error_message: message,\n });\n }\n return;\n }\n\n const callId = body.id ?? `local_call_${randomUUID()}`;\n let effectiveInput: Record<string, unknown> = body.input ?? {};\n if (hookContext != null) {\n const gate = await applyPreToolUseHooksForBridge(\n hookContext,\n body.name,\n callId,\n effectiveInput\n );\n if (gate.denyReason != null) {\n const denyMsg = gate.denyReason;\n if (isTextMode) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(denyMsg);\n } else {\n writeJson(res, 500, {\n call_id: callId,\n result: null,\n is_error: true,\n error_message: denyMsg,\n });\n }\n return;\n }\n effectiveInput = gate.input;\n }\n\n const [result] = await executeTools(\n [\n {\n id: callId,\n name: body.name,\n input: effectiveInput,\n },\n ],\n toolMap\n );\n\n if (isTextMode) {\n if (result.is_error === true) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(result.error_message ?? `Tool ${body.name} failed`);\n } else {\n const value = toSerializable(result.result);\n const text =\n typeof value === 'string' ? value : JSON.stringify(value);\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end(text);\n }\n return;\n }\n\n writeJson(res, 200, {\n ...result,\n result: toSerializable(result.result),\n });\n })\n .catch((error: Error) => {\n if (isTextMode) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(error.message);\n } else {\n writeJson(res, 500, {\n call_id: 'error',\n result: null,\n is_error: true,\n error_message: error.message,\n });\n }\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', resolve);\n });\n\n const address = server.address() as AddressInfo;\n return {\n url: `http://127.0.0.1:${address.port}/tool`,\n token,\n close: () =>\n new Promise((resolve, reject) => {\n server.close((error) => (error ? reject(error) : resolve()));\n }),\n };\n}\n\nfunction indent(code: string): string {\n return code\n .split('\\n')\n .map((line) => ` ${line}`)\n .join('\\n');\n}\n\nfunction createPythonProgram(\n code: string,\n toolDefs: t.LCTool[],\n bridgeUrl: string,\n bridgeToken: string\n): string {\n const functionDefs = toolDefs\n .map((def) => {\n const pythonName = normalizeToPythonIdentifier(def.name);\n return [\n `async def ${pythonName}(**kwargs):`,\n ` return await __librechat_call_tool(${JSON.stringify(def.name)}, kwargs)`,\n ].join('\\n');\n })\n .join('\\n\\n');\n\n return `\nimport asyncio\nimport json\nimport urllib.request\n\n__LIBRECHAT_TOOL_BRIDGE = ${JSON.stringify(bridgeUrl)}\n__LIBRECHAT_TOOL_TOKEN = ${JSON.stringify(bridgeToken)}\n\nasync def __librechat_call_tool(name, payload):\n body = json.dumps({\"name\": name, \"input\": payload}).encode(\"utf-8\")\n headers = {\n \"Content-Type\": \"application/json\",\n ${JSON.stringify(BRIDGE_AUTH_HEADER)}: __LIBRECHAT_TOOL_TOKEN,\n }\n\n def request():\n req = urllib.request.Request(__LIBRECHAT_TOOL_BRIDGE, data=body, headers=headers, method=\"POST\")\n with urllib.request.urlopen(req, timeout=300) as response:\n return response.read().decode(\"utf-8\")\n\n raw = await asyncio.to_thread(request)\n result = json.loads(raw)\n if result.get(\"is_error\"):\n raise RuntimeError(result.get(\"error_message\") or f\"Tool {name} failed\")\n return result.get(\"result\")\n\n${functionDefs}\n\nasync def __librechat_main():\n${indent(code)}\n\nasyncio.run(__librechat_main())\n`.trimStart();\n}\n\nexport function _createBashProgramForTests(\n code: string,\n toolDefs: t.LCTool[],\n bridgeUrl: string,\n bridgeToken: string\n): string {\n return createBashProgram(code, toolDefs, bridgeUrl, bridgeToken);\n}\n\nfunction createBashProgram(\n code: string,\n toolDefs: t.LCTool[],\n bridgeUrl: string,\n bridgeToken: string\n): string {\n const functions = toolDefs\n .map((def) => {\n const bashName = normalizeToBashIdentifier(def.name);\n return [\n `${bashName}() {`,\n ' local payload=\"${1:-}\"',\n ' if [ -z \"$payload\" ]; then payload=\\'{}\\'; fi',\n ` __librechat_call_tool ${shellQuote(def.name)} \"$payload\"`,\n '}',\n ].join('\\n');\n })\n .join('\\n\\n');\n\n return `\n__LIBRECHAT_TOOL_BRIDGE=${shellQuote(bridgeUrl)}\n__LIBRECHAT_TOOL_HEADER=${shellQuote(BRIDGE_AUTH_HEADER)}\n__LIBRECHAT_TOOL_TOKEN=${shellQuote(bridgeToken)}\n\n# Bridge call helper. Tries curl first (universally available, no\n# JSON parser needed thanks to the bridge's ?mode=text endpoint),\n# falls back to python3 for environments without curl. Codex P2 #19\n# flagged that the prior python3-only path broke minimal containers\n# (and Windows hosts without a python3 binary on PATH). Tool names\n# come from Constants.* and are always safe identifiers, so we can\n# splice them into JSON without an escape pass.\n__librechat_call_tool() {\n local tool_name=\"$1\"\n local payload=\"$2\"\n if command -v curl >/dev/null 2>&1; then\n local body=\"{\\\\\"name\\\\\":\\\\\"$tool_name\\\\\",\\\\\"input\\\\\":$payload}\"\n local response\n local http_code\n response=$(curl -sS -X POST \\\n -H \"Content-Type: application/json\" \\\n -H \"$__LIBRECHAT_TOOL_HEADER: $__LIBRECHAT_TOOL_TOKEN\" \\\n --data-binary \"$body\" \\\n -w '\\\\n__LIBRECHAT_HTTP_CODE_%{http_code}__' \\\n \"$__LIBRECHAT_TOOL_BRIDGE?mode=text\")\n http_code=$(printf '%s' \"$response\" | sed -n 's/.*__LIBRECHAT_HTTP_CODE_\\\\([0-9][0-9]*\\\\)__$/\\\\1/p')\n local body_only\n body_only=$(printf '%s' \"$response\" | sed 's/__LIBRECHAT_HTTP_CODE_[0-9][0-9]*__$//')\n if [ \"$http_code\" = \"200\" ]; then\n printf '%s' \"$body_only\"\n return 0\n fi\n printf '%s\\\\n' \"$body_only\" >&2\n return 1\n elif command -v python3 >/dev/null 2>&1; then\n python3 - \"$__LIBRECHAT_TOOL_BRIDGE\" \"$tool_name\" \"$payload\" \"$__LIBRECHAT_TOOL_HEADER\" \"$__LIBRECHAT_TOOL_TOKEN\" <<'PY'\nimport json\nimport sys\nimport urllib.request\n\nurl, name, payload, header, token = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]\nbody = json.dumps({\"name\": name, \"input\": json.loads(payload)}).encode(\"utf-8\")\nreq = urllib.request.Request(url, data=body, headers={\"Content-Type\": \"application/json\", header: token}, method=\"POST\")\nwith urllib.request.urlopen(req, timeout=300) as response:\n result = json.loads(response.read().decode(\"utf-8\"))\nif result.get(\"is_error\"):\n print(result.get(\"error_message\") or f\"Tool {name} failed\", file=sys.stderr)\n sys.exit(1)\nvalue = result.get(\"result\")\nif isinstance(value, str):\n print(value)\nelse:\n print(json.dumps(value))\nPY\n else\n printf 'librechat: tool bridge needs either curl or python3 on PATH\\\\n' >&2\n return 1\n fi\n}\n\n${functions}\n\n${code}\n`.trimStart();\n}\n\nfunction getProgrammaticContext(config?: {\n toolCall?: unknown;\n}): Partial<t.ProgrammaticCache> {\n return (config?.toolCall ?? {}) as Partial<t.ProgrammaticCache>;\n}\n\nfunction createEffectiveToolMap(\n toolMap: t.ToolMap,\n toolDefs: t.LCTool[],\n code: string,\n filterTools: ToolFilter\n): { effectiveTools: t.LCTool[]; effectiveMap: t.ToolMap } {\n const effectiveTools = filterTools(toolDefs, code);\n const effectiveMap = new Map<string, t.GenericTool>(\n effectiveTools\n .map((def) => {\n const executable = toolMap.get(def.name);\n return executable == null\n ? undefined\n : ([def.name, executable] as [string, t.GenericTool]);\n })\n .filter((entry): entry is [string, t.GenericTool] => entry != null)\n );\n\n return { effectiveTools, effectiveMap };\n}\n\nasync function runLocalProgrammaticTool(args: {\n params: LocalProgrammaticParams;\n config?: { toolCall?: unknown };\n localConfig: t.LocalExecutionConfig;\n runtime: LocalProgrammaticRuntime;\n}): Promise<[string, t.ProgrammaticExecutionArtifact]> {\n const { toolMap, toolDefs, hookContext } = getProgrammaticContext(\n args.config\n );\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error('No toolMap provided for local programmatic execution.');\n }\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided for local programmatic execution.'\n );\n }\n\n const { effectiveTools, effectiveMap } = createEffectiveToolMap(\n toolMap,\n toolDefs,\n args.params.code,\n args.runtime === 'bash' ? filterBashToolsByUsage : filterToolsByUsage\n );\n const bridge = await createToolBridge(effectiveMap, hookContext);\n\n try {\n const timeoutMs =\n args.params.timeout ?? args.localConfig.timeoutMs ?? DEFAULT_TIMEOUT;\n const result =\n args.runtime === 'bash'\n ? await executeLocalBash(\n createBashProgram(\n args.params.code,\n effectiveTools,\n bridge.url,\n bridge.token\n ),\n { ...args.localConfig, timeoutMs }\n )\n : await executeLocalCode(\n {\n lang: 'py',\n code: createPythonProgram(\n args.params.code,\n effectiveTools,\n bridge.url,\n bridge.token\n ),\n },\n { ...args.localConfig, timeoutMs }\n );\n\n if (result.exitCode !== 0 || result.timedOut) {\n throw new Error(\n result.stderr !== ''\n ? result.stderr\n : `Local ${args.runtime} programmatic execution exited with code ${\n result.exitCode ?? 'unknown'\n }`\n );\n }\n\n return formatCompletedResponse({\n status: 'completed',\n session_id: getLocalSessionId(args.localConfig),\n stdout: result.stdout,\n stderr: result.stderr,\n files: [],\n });\n } finally {\n await bridge.close();\n }\n}\n\nexport function createLocalProgrammaticToolCallingTool(\n localConfig: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as LocalProgrammaticParams;\n return runLocalProgrammaticTool({\n params,\n config,\n localConfig,\n runtime: resolveRuntime(params),\n });\n },\n {\n name: ProgrammaticToolCallingName,\n description: `${ProgrammaticToolCallingDescription}\\n\\nLocal engine: runs bash by default, or Python when \\`lang\\` is \\`py\\` or \\`python\\`, on the host machine and calls tools through an in-process localhost bridge.`,\n schema: LocalProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalBashProgrammaticToolCallingTool(\n localConfig: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as LocalProgrammaticParams;\n return runLocalProgrammaticTool({\n params,\n config,\n localConfig,\n runtime: 'bash',\n });\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: `${BashProgrammaticToolCallingDescription}\\n\\nLocal engine: runs this bash orchestration code on the host machine and calls tools through an in-process localhost bridge.`,\n schema: BashProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;AA+BA,MAAM,eAAe,GAAG,KAAK;AAC7B,MAAM,kCAAkC,GAAG;AACzC,IA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AAA,CAAC;AACJ,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,2BAA2B;QACjC,WAAW,EAAE,CAAA,EAAG,kCAAkC,CAAA,oKAAA,CAAsK;AACxN,QAAA,MAAM,EAAE,kCAAkC;QAC1C,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;AAEM,SAAU,0CAA0C,CACxD,WAAA,GAAsC,EAAE,EAAA;IAExC,OAAO,IAAI,CACT,OAAO,SAAS,EAAE,MAAM,KAAI;QAC1B,MAAM,MAAM,GAAG,SAAoC;AACnD,QAAA,OAAO,wBAAwB,CAAC;YAC9B,MAAM;YACN,MAAM;YACN,WAAW;AACX,YAAA,OAAO,EAAE,MAAM;AAChB,SAAA,CAAC;AACJ,IAAA,CAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,8BAA8B;QAC9C,WAAW,EAAE,CAAA,EAAG,sCAAsC,CAAA,+HAAA,CAAiI;AACvL,QAAA,MAAM,EAAE,iCAAiC;QACzC,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"LocalProgrammaticToolCalling.mjs","sources":["../../../../src/tools/local/LocalProgrammaticToolCalling.ts"],"sourcesContent":["import { randomBytes, randomUUID, timingSafeEqual } from 'crypto';\nimport { createServer } from 'http';\nimport { tool } from '@langchain/core/tools';\nimport type { AddressInfo } from 'net';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { executeHooks } from '@/hooks';\nimport {\n executeTools,\n filterToolsByUsage,\n formatCompletedResponse,\n normalizeToPythonIdentifier,\n ProgrammaticToolCallingName,\n ProgrammaticToolCallingSchema,\n ProgrammaticToolCallingDescription,\n} from '@/tools/ProgrammaticToolCalling';\nimport {\n BashProgrammaticToolCallingSchema,\n BashProgrammaticToolCallingDescription,\n filterBashToolsByUsage,\n normalizeToBashIdentifier,\n} from '@/tools/BashProgrammaticToolCalling';\nimport {\n executeLocalBash,\n executeLocalCode,\n getLocalSessionId,\n shellQuote,\n} from './LocalExecutionEngine';\nimport { Constants } from '@/common';\n\nconst DEFAULT_TIMEOUT = 60000;\nconst LOCAL_MIN_TIMEOUT = 1000;\nconst LOCAL_MAX_TIMEOUT = 300000;\n\ntype LocalTimeoutSchema = {\n type: 'integer';\n minimum: number;\n maximum: number;\n default: number;\n description: string;\n};\n\ntype LocalProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: typeof ProgrammaticToolCallingSchema.properties & {\n timeout: LocalTimeoutSchema;\n lang: {\n type: 'string';\n enum: readonly ['py', 'python', 'bash', 'sh'];\n default: 'bash';\n description: string;\n };\n };\n required: readonly ['code'];\n};\n\ntype LocalBashProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: typeof BashProgrammaticToolCallingSchema.properties & {\n timeout: LocalTimeoutSchema;\n };\n required: readonly ['code'];\n};\n\nfunction normalizeLocalTimeout(timeoutMs: number | undefined): number {\n if (timeoutMs == null || !Number.isFinite(timeoutMs)) {\n return DEFAULT_TIMEOUT;\n }\n\n return Math.max(LOCAL_MIN_TIMEOUT, Math.floor(timeoutMs));\n}\n\nfunction formatLocalTimeout(timeoutMs: number): string {\n return timeoutMs % 1000 === 0\n ? `${timeoutMs / 1000} seconds`\n : `${timeoutMs} milliseconds`;\n}\n\nfunction createLocalTimeoutSchema(timeoutMs?: number): LocalTimeoutSchema {\n const defaultTimeout = normalizeLocalTimeout(timeoutMs);\n const maxTimeout = Math.max(LOCAL_MAX_TIMEOUT, defaultTimeout);\n const formattedDefault = formatLocalTimeout(defaultTimeout);\n const formattedMax = formatLocalTimeout(maxTimeout);\n\n return {\n type: 'integer',\n minimum: LOCAL_MIN_TIMEOUT,\n maximum: maxTimeout,\n default: defaultTimeout,\n description:\n 'Maximum local execution time in milliseconds. ' +\n `Default: ${formattedDefault}. Max: ${formattedMax}.`,\n };\n}\n\nfunction createLocalProgrammaticToolCallingSchema(\n localConfig: t.LocalExecutionConfig = {}\n): LocalProgrammaticToolCallingJsonSchema {\n return {\n ...ProgrammaticToolCallingSchema,\n properties: {\n ...ProgrammaticToolCallingSchema.properties,\n timeout: createLocalTimeoutSchema(localConfig.timeoutMs),\n lang: {\n type: 'string',\n enum: ['py', 'python', 'bash', 'sh'],\n default: 'bash',\n description:\n 'Local engine runtime for orchestration code. Defaults to bash; use py/python for Python orchestration.',\n },\n },\n } as const;\n}\n\nfunction createLocalBashProgrammaticToolCallingSchema(\n localConfig: t.LocalExecutionConfig = {}\n): LocalBashProgrammaticToolCallingJsonSchema {\n return {\n ...BashProgrammaticToolCallingSchema,\n properties: {\n ...BashProgrammaticToolCallingSchema.properties,\n timeout: createLocalTimeoutSchema(localConfig.timeoutMs),\n },\n } as const;\n}\n\ntype ToolBridge = {\n url: string;\n token: string;\n close: () => Promise<void>;\n};\n\ntype ToolRequest = {\n id?: string;\n name?: string;\n input?: Record<string, unknown>;\n};\n\nconst BRIDGE_AUTH_HEADER = 'x-librechat-bridge-token';\n\nfunction constantTimeEquals(a: string, b: string): boolean {\n const aBuf = Buffer.from(a, 'utf8');\n const bBuf = Buffer.from(b, 'utf8');\n if (aBuf.length !== bBuf.length) {\n return false;\n }\n return timingSafeEqual(aBuf, bBuf);\n}\n\ntype LocalProgrammaticRuntime = 'python' | 'bash';\n\ntype LocalProgrammaticParams = {\n code: string;\n timeout?: number;\n lang?: string;\n runtime?: string;\n language?: string;\n};\n\ntype ToolFilter = (toolDefs: t.LCTool[], code: string) => t.LCTool[];\n\nfunction resolveRuntime(\n params: LocalProgrammaticParams\n): LocalProgrammaticRuntime {\n const rawRuntime = params.lang ?? params.runtime ?? params.language ?? 'bash';\n return rawRuntime === 'py' || rawRuntime === 'python' ? 'python' : 'bash';\n}\n\nfunction toSerializable(value: unknown): unknown {\n if (value === undefined) {\n return null;\n }\n return value;\n}\n\nasync function readRequestBody(req: IncomingMessage): Promise<ToolRequest> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const raw = Buffer.concat(chunks).toString('utf8');\n if (raw === '') {\n return {};\n }\n return JSON.parse(raw) as ToolRequest;\n}\n\nfunction writeJson(res: ServerResponse, status: number, value: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(value));\n}\n\n/**\n * Run the host's `PreToolUse` hook chain for a single bridge call.\n * Returns the (possibly rewritten) input and a `denyReason` if any\n * matcher returned `decision: 'deny'` or `'ask'`. `'ask'` collapses\n * to deny because the bridge can't raise a LangGraph interrupt from\n * inside an HTTP handler — fail-closed matches the rest of the SDK\n * when HITL is unavailable.\n *\n * @internal Exported for tests so the deny / allow / updatedInput /\n * ask branches can be exercised without standing up the full HTTP\n * bridge.\n */\nexport async function applyPreToolUseHooksForBridge(\n hookContext: t.ProgrammaticHookContext,\n toolName: string,\n toolUseId: string,\n toolInput: Record<string, unknown>\n): Promise<{ input: Record<string, unknown>; denyReason?: string }> {\n if (hookContext.registry == null) {\n return { input: toolInput };\n }\n const result = await executeHooks({\n registry: hookContext.registry,\n input: {\n hook_event_name: 'PreToolUse',\n runId: hookContext.runId,\n threadId: hookContext.threadId,\n agentId: hookContext.agentId,\n toolName,\n toolInput,\n toolUseId,\n stepId: '',\n turn: 0,\n },\n sessionId: hookContext.runId,\n matchQuery: toolName,\n }).catch(() => undefined);\n if (result == null) {\n return { input: toolInput };\n }\n const nextInput =\n result.updatedInput != null\n ? (result.updatedInput as Record<string, unknown>)\n : toolInput;\n if (result.decision === 'deny' || result.decision === 'ask') {\n return {\n input: nextInput,\n denyReason:\n result.reason ??\n (result.decision === 'ask'\n ? `Tool \"${toolName}\" requires human approval; bridge cannot raise an interrupt — denying.`\n : `Tool \"${toolName}\" denied by PreToolUse hook.`),\n };\n }\n return { input: nextInput };\n}\n\nasync function createToolBridge(\n toolMap: t.ToolMap,\n hookContext?: t.ProgrammaticHookContext\n): Promise<ToolBridge> {\n const token = randomBytes(32).toString('hex');\n const server = createServer((req, res) => {\n // `?mode=text` returns the already-serialized result as the body\n // (or the error message at non-2xx). Python/Node callers stay on\n // JSON; bash callers using curl can avoid pulling in a JSON\n // parser dependency (Codex P2 #19 — `python3` was a hard\n // requirement for the bash bridge, breaking minimal containers).\n const url = new URL(req.url ?? '/', 'http://127.0.0.1');\n const isTextMode = url.searchParams.get('mode') === 'text';\n if (req.method !== 'POST' || url.pathname !== '/tool') {\n if (isTextMode) {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not found');\n } else {\n writeJson(res, 404, { error: 'Not found' });\n }\n return;\n }\n\n const presented = req.headers[BRIDGE_AUTH_HEADER];\n const presentedToken = Array.isArray(presented) ? presented[0] : presented;\n if (\n typeof presentedToken !== 'string' ||\n !constantTimeEquals(presentedToken, token)\n ) {\n if (isTextMode) {\n res.writeHead(401, { 'Content-Type': 'text/plain' });\n res.end('Unauthorized');\n } else {\n writeJson(res, 401, { error: 'Unauthorized' });\n }\n return;\n }\n\n readRequestBody(req)\n .then(async (body) => {\n if (typeof body.name !== 'string' || body.name === '') {\n const message = 'Tool request is missing a tool name.';\n if (isTextMode) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end(message);\n } else {\n writeJson(res, 400, {\n call_id: body.id ?? 'invalid',\n result: null,\n is_error: true,\n error_message: message,\n });\n }\n return;\n }\n\n const callId = body.id ?? `local_call_${randomUUID()}`;\n let effectiveInput: Record<string, unknown> = body.input ?? {};\n if (hookContext != null) {\n const gate = await applyPreToolUseHooksForBridge(\n hookContext,\n body.name,\n callId,\n effectiveInput\n );\n if (gate.denyReason != null) {\n const denyMsg = gate.denyReason;\n if (isTextMode) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(denyMsg);\n } else {\n writeJson(res, 500, {\n call_id: callId,\n result: null,\n is_error: true,\n error_message: denyMsg,\n });\n }\n return;\n }\n effectiveInput = gate.input;\n }\n\n const [result] = await executeTools(\n [\n {\n id: callId,\n name: body.name,\n input: effectiveInput,\n },\n ],\n toolMap\n );\n\n if (isTextMode) {\n if (result.is_error === true) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(result.error_message ?? `Tool ${body.name} failed`);\n } else {\n const value = toSerializable(result.result);\n const text =\n typeof value === 'string' ? value : JSON.stringify(value);\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end(text);\n }\n return;\n }\n\n writeJson(res, 200, {\n ...result,\n result: toSerializable(result.result),\n });\n })\n .catch((error: Error) => {\n if (isTextMode) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(error.message);\n } else {\n writeJson(res, 500, {\n call_id: 'error',\n result: null,\n is_error: true,\n error_message: error.message,\n });\n }\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', resolve);\n });\n\n const address = server.address() as AddressInfo;\n return {\n url: `http://127.0.0.1:${address.port}/tool`,\n token,\n close: () =>\n new Promise((resolve, reject) => {\n server.close((error) => (error ? reject(error) : resolve()));\n }),\n };\n}\n\nfunction indent(code: string): string {\n return code\n .split('\\n')\n .map((line) => ` ${line}`)\n .join('\\n');\n}\n\nfunction createPythonProgram(\n code: string,\n toolDefs: t.LCTool[],\n bridgeUrl: string,\n bridgeToken: string\n): string {\n const functionDefs = toolDefs\n .map((def) => {\n const pythonName = normalizeToPythonIdentifier(def.name);\n return [\n `async def ${pythonName}(**kwargs):`,\n ` return await __librechat_call_tool(${JSON.stringify(def.name)}, kwargs)`,\n ].join('\\n');\n })\n .join('\\n\\n');\n\n return `\nimport asyncio\nimport json\nimport urllib.request\n\n__LIBRECHAT_TOOL_BRIDGE = ${JSON.stringify(bridgeUrl)}\n__LIBRECHAT_TOOL_TOKEN = ${JSON.stringify(bridgeToken)}\n\nasync def __librechat_call_tool(name, payload):\n body = json.dumps({\"name\": name, \"input\": payload}).encode(\"utf-8\")\n headers = {\n \"Content-Type\": \"application/json\",\n ${JSON.stringify(BRIDGE_AUTH_HEADER)}: __LIBRECHAT_TOOL_TOKEN,\n }\n\n def request():\n req = urllib.request.Request(__LIBRECHAT_TOOL_BRIDGE, data=body, headers=headers, method=\"POST\")\n with urllib.request.urlopen(req, timeout=300) as response:\n return response.read().decode(\"utf-8\")\n\n raw = await asyncio.to_thread(request)\n result = json.loads(raw)\n if result.get(\"is_error\"):\n raise RuntimeError(result.get(\"error_message\") or f\"Tool {name} failed\")\n return result.get(\"result\")\n\n${functionDefs}\n\nasync def __librechat_main():\n${indent(code)}\n\nasyncio.run(__librechat_main())\n`.trimStart();\n}\n\nexport function _createBashProgramForTests(\n code: string,\n toolDefs: t.LCTool[],\n bridgeUrl: string,\n bridgeToken: string\n): string {\n return createBashProgram(code, toolDefs, bridgeUrl, bridgeToken);\n}\n\nfunction createBashProgram(\n code: string,\n toolDefs: t.LCTool[],\n bridgeUrl: string,\n bridgeToken: string\n): string {\n const functions = toolDefs\n .map((def) => {\n const bashName = normalizeToBashIdentifier(def.name);\n return [\n `${bashName}() {`,\n ' local payload=\"${1:-}\"',\n ' if [ -z \"$payload\" ]; then payload=\\'{}\\'; fi',\n ` __librechat_call_tool ${shellQuote(def.name)} \"$payload\"`,\n '}',\n ].join('\\n');\n })\n .join('\\n\\n');\n\n return `\n__LIBRECHAT_TOOL_BRIDGE=${shellQuote(bridgeUrl)}\n__LIBRECHAT_TOOL_HEADER=${shellQuote(BRIDGE_AUTH_HEADER)}\n__LIBRECHAT_TOOL_TOKEN=${shellQuote(bridgeToken)}\n\n# Bridge call helper. Tries curl first (universally available, no\n# JSON parser needed thanks to the bridge's ?mode=text endpoint),\n# falls back to python3 for environments without curl. Codex P2 #19\n# flagged that the prior python3-only path broke minimal containers\n# (and Windows hosts without a python3 binary on PATH). Tool names\n# come from Constants.* and are always safe identifiers, so we can\n# splice them into JSON without an escape pass.\n__librechat_call_tool() {\n local tool_name=\"$1\"\n local payload=\"$2\"\n if command -v curl >/dev/null 2>&1; then\n local body=\"{\\\\\"name\\\\\":\\\\\"$tool_name\\\\\",\\\\\"input\\\\\":$payload}\"\n local response\n local http_code\n response=$(curl -sS -X POST \\\n -H \"Content-Type: application/json\" \\\n -H \"$__LIBRECHAT_TOOL_HEADER: $__LIBRECHAT_TOOL_TOKEN\" \\\n --data-binary \"$body\" \\\n -w '\\\\n__LIBRECHAT_HTTP_CODE_%{http_code}__' \\\n \"$__LIBRECHAT_TOOL_BRIDGE?mode=text\")\n http_code=$(printf '%s' \"$response\" | sed -n 's/.*__LIBRECHAT_HTTP_CODE_\\\\([0-9][0-9]*\\\\)__$/\\\\1/p')\n local body_only\n body_only=$(printf '%s' \"$response\" | sed 's/__LIBRECHAT_HTTP_CODE_[0-9][0-9]*__$//')\n if [ \"$http_code\" = \"200\" ]; then\n printf '%s' \"$body_only\"\n return 0\n fi\n printf '%s\\\\n' \"$body_only\" >&2\n return 1\n elif command -v python3 >/dev/null 2>&1; then\n python3 - \"$__LIBRECHAT_TOOL_BRIDGE\" \"$tool_name\" \"$payload\" \"$__LIBRECHAT_TOOL_HEADER\" \"$__LIBRECHAT_TOOL_TOKEN\" <<'PY'\nimport json\nimport sys\nimport urllib.request\n\nurl, name, payload, header, token = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]\nbody = json.dumps({\"name\": name, \"input\": json.loads(payload)}).encode(\"utf-8\")\nreq = urllib.request.Request(url, data=body, headers={\"Content-Type\": \"application/json\", header: token}, method=\"POST\")\nwith urllib.request.urlopen(req, timeout=300) as response:\n result = json.loads(response.read().decode(\"utf-8\"))\nif result.get(\"is_error\"):\n print(result.get(\"error_message\") or f\"Tool {name} failed\", file=sys.stderr)\n sys.exit(1)\nvalue = result.get(\"result\")\nif isinstance(value, str):\n print(value)\nelse:\n print(json.dumps(value))\nPY\n else\n printf 'librechat: tool bridge needs either curl or python3 on PATH\\\\n' >&2\n return 1\n fi\n}\n\n${functions}\n\n${code}\n`.trimStart();\n}\n\nfunction getProgrammaticContext(config?: {\n toolCall?: unknown;\n}): Partial<t.ProgrammaticCache> {\n return (config?.toolCall ?? {}) as Partial<t.ProgrammaticCache>;\n}\n\nfunction createEffectiveToolMap(\n toolMap: t.ToolMap,\n toolDefs: t.LCTool[],\n code: string,\n filterTools: ToolFilter\n): { effectiveTools: t.LCTool[]; effectiveMap: t.ToolMap } {\n const effectiveTools = filterTools(toolDefs, code);\n const effectiveMap = new Map<string, t.GenericTool>(\n effectiveTools\n .map((def) => {\n const executable = toolMap.get(def.name);\n return executable == null\n ? undefined\n : ([def.name, executable] as [string, t.GenericTool]);\n })\n .filter((entry): entry is [string, t.GenericTool] => entry != null)\n );\n\n return { effectiveTools, effectiveMap };\n}\n\nasync function runLocalProgrammaticTool(args: {\n params: LocalProgrammaticParams;\n config?: { toolCall?: unknown };\n localConfig: t.LocalExecutionConfig;\n runtime: LocalProgrammaticRuntime;\n}): Promise<[string, t.ProgrammaticExecutionArtifact]> {\n const { toolMap, toolDefs, hookContext } = getProgrammaticContext(\n args.config\n );\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error('No toolMap provided for local programmatic execution.');\n }\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided for local programmatic execution.'\n );\n }\n\n const { effectiveTools, effectiveMap } = createEffectiveToolMap(\n toolMap,\n toolDefs,\n args.params.code,\n args.runtime === 'bash' ? filterBashToolsByUsage : filterToolsByUsage\n );\n const bridge = await createToolBridge(effectiveMap, hookContext);\n\n try {\n const timeoutMs =\n args.params.timeout ?? args.localConfig.timeoutMs ?? DEFAULT_TIMEOUT;\n const result =\n args.runtime === 'bash'\n ? await executeLocalBash(\n createBashProgram(\n args.params.code,\n effectiveTools,\n bridge.url,\n bridge.token\n ),\n { ...args.localConfig, timeoutMs }\n )\n : await executeLocalCode(\n {\n lang: 'py',\n code: createPythonProgram(\n args.params.code,\n effectiveTools,\n bridge.url,\n bridge.token\n ),\n },\n { ...args.localConfig, timeoutMs }\n );\n\n if (result.exitCode !== 0 || result.timedOut) {\n throw new Error(\n result.stderr !== ''\n ? result.stderr\n : `Local ${args.runtime} programmatic execution exited with code ${\n result.exitCode ?? 'unknown'\n }`\n );\n }\n\n return formatCompletedResponse({\n status: 'completed',\n session_id: getLocalSessionId(args.localConfig),\n stdout: result.stdout,\n stderr: result.stderr,\n files: [],\n });\n } finally {\n await bridge.close();\n }\n}\n\nexport function createLocalProgrammaticToolCallingTool(\n localConfig: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as LocalProgrammaticParams;\n return runLocalProgrammaticTool({\n params,\n config,\n localConfig,\n runtime: resolveRuntime(params),\n });\n },\n {\n name: ProgrammaticToolCallingName,\n description: `${ProgrammaticToolCallingDescription}\\n\\nLocal engine: runs bash by default, or Python when \\`lang\\` is \\`py\\` or \\`python\\`, on the host machine and calls tools through an in-process localhost bridge.`,\n schema: createLocalProgrammaticToolCallingSchema(localConfig),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalBashProgrammaticToolCallingTool(\n localConfig: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n return tool(\n async (rawParams, config) => {\n const params = rawParams as LocalProgrammaticParams;\n return runLocalProgrammaticTool({\n params,\n config,\n localConfig,\n runtime: 'bash',\n });\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: `${BashProgrammaticToolCallingDescription}\\n\\nLocal engine: runs this bash orchestration code on the host machine and calls tools through an in-process localhost bridge.`,\n schema: createLocalBashProgrammaticToolCallingSchema(localConfig),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;AA+BA,MAAM,eAAe,GAAG,KAAK;AAC7B,MAAM,iBAAiB,GAAG,IAAI;AAC9B,MAAM,iBAAiB,GAAG,MAAM;AAgChC,SAAS,qBAAqB,CAAC,SAA6B,EAAA;AAC1D,IAAA,IAAI,SAAS,IAAI,IAAI,IAAI,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N,WAAW;AACX,YAAA,OAAO,EAAE,cAAc,CAAC,MAAM,CAAC;AAChC,SAAA,CAAC;AACJ,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,2BAA2B;QACjC,WAAW,EAAE,CAAA,EAAG,kCAAkC,CAAA,oKAAA,CAAsK;AACxN,QAAA,MAAM,EAAE,wCAAwC,CAAC,WAAW,CAAC;QAC7D,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;AAEM,SAAU,0CAA0C,CACxD,WAAA,GAAsC,EAAE,EAAA;IAExC,OAAO,IAAI,CACT,OAAO,SAAS,EAAE,MAAM,KAAI;QAC1B,MAAM,MAAM,GAAG,SAAoC;AACnD,QAAA,OAAO,wBAAwB,CAAC;YAC9B,MAAM;YACN,MAAM;YACN,WAAW;AACX,YAAA,OAAO,EAAE,MAAM;AAChB,SAAA,CAAC;AACJ,IAAA,CAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,8BAA8B;QAC9C,WAAW,EAAE,CAAA,EAAG,sCAAsC,CAAA,+HAAA,CAAiI;AACvL,QAAA,MAAM,EAAE,4CAA4C,CAAC,WAAW,CAAC;QACjE,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { EnvVar } from '../common/enum.mjs';
|
|
2
|
+
|
|
3
|
+
const DEFAULT_CODE_API_RUN_TIMEOUT_MS = 15_000;
|
|
4
|
+
const MIN_CODE_API_RUN_TIMEOUT_MS = 1_000;
|
|
5
|
+
function normalizeTimeoutMs(value) {
|
|
6
|
+
if (value == null || !Number.isFinite(value)) {
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
9
|
+
return Math.max(MIN_CODE_API_RUN_TIMEOUT_MS, Math.floor(value));
|
|
10
|
+
}
|
|
11
|
+
function parseTimeoutMs(value) {
|
|
12
|
+
if (value == null || value.trim() === '') {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
return normalizeTimeoutMs(Number(value));
|
|
16
|
+
}
|
|
17
|
+
function formatTimeout(timeoutMs) {
|
|
18
|
+
return timeoutMs % 1000 === 0
|
|
19
|
+
? `${timeoutMs / 1000} seconds`
|
|
20
|
+
: `${timeoutMs} milliseconds`;
|
|
21
|
+
}
|
|
22
|
+
function resolveCodeApiRunTimeoutMs(override) {
|
|
23
|
+
return (normalizeTimeoutMs(override) ??
|
|
24
|
+
parseTimeoutMs(process.env[EnvVar.CODE_API_RUN_TIMEOUT_MS]) ??
|
|
25
|
+
DEFAULT_CODE_API_RUN_TIMEOUT_MS);
|
|
26
|
+
}
|
|
27
|
+
function clampCodeApiRunTimeoutMs(timeoutMs, maxRunTimeoutMs = resolveCodeApiRunTimeoutMs()) {
|
|
28
|
+
const normalizedMaxRunTimeoutMs = normalizeTimeoutMs(maxRunTimeoutMs) ?? DEFAULT_CODE_API_RUN_TIMEOUT_MS;
|
|
29
|
+
const normalizedTimeoutMs = normalizeTimeoutMs(timeoutMs);
|
|
30
|
+
if (normalizedTimeoutMs == null) {
|
|
31
|
+
return normalizedMaxRunTimeoutMs;
|
|
32
|
+
}
|
|
33
|
+
return Math.min(normalizedTimeoutMs, normalizedMaxRunTimeoutMs);
|
|
34
|
+
}
|
|
35
|
+
function createCodeApiRunTimeoutSchema(maxRunTimeoutMs = resolveCodeApiRunTimeoutMs()) {
|
|
36
|
+
const normalizedMaxRunTimeoutMs = normalizeTimeoutMs(maxRunTimeoutMs) ?? DEFAULT_CODE_API_RUN_TIMEOUT_MS;
|
|
37
|
+
const formattedTimeout = formatTimeout(normalizedMaxRunTimeoutMs);
|
|
38
|
+
return {
|
|
39
|
+
type: 'integer',
|
|
40
|
+
minimum: MIN_CODE_API_RUN_TIMEOUT_MS,
|
|
41
|
+
maximum: normalizedMaxRunTimeoutMs,
|
|
42
|
+
default: normalizedMaxRunTimeoutMs,
|
|
43
|
+
description: 'Maximum wall-clock time in milliseconds for one sandbox run or replay iteration. ' +
|
|
44
|
+
'This is not the total multi-round-trip task budget. ' +
|
|
45
|
+
`Default: ${formattedTimeout}. Max: ${formattedTimeout}.`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export { DEFAULT_CODE_API_RUN_TIMEOUT_MS, MIN_CODE_API_RUN_TIMEOUT_MS, clampCodeApiRunTimeoutMs, createCodeApiRunTimeoutSchema, resolveCodeApiRunTimeoutMs };
|
|
50
|
+
//# sourceMappingURL=ptcTimeout.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ptcTimeout.mjs","sources":["../../../src/tools/ptcTimeout.ts"],"sourcesContent":["import { EnvVar } from '@/common';\n\nexport const DEFAULT_CODE_API_RUN_TIMEOUT_MS = 15_000;\nexport const MIN_CODE_API_RUN_TIMEOUT_MS = 1_000;\n\ntype TimeoutSchema = {\n type: 'integer';\n minimum: number;\n maximum: number;\n default: number;\n description: string;\n};\n\nexport type ProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: {\n code: {\n type: 'string';\n minLength: number;\n description: string;\n };\n timeout: TimeoutSchema;\n };\n required: readonly ['code'];\n};\n\nfunction normalizeTimeoutMs(value: number | undefined): number | undefined {\n if (value == null || !Number.isFinite(value)) {\n return undefined;\n }\n\n return Math.max(MIN_CODE_API_RUN_TIMEOUT_MS, Math.floor(value));\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (value == null || value.trim() === '') {\n return undefined;\n }\n\n return normalizeTimeoutMs(Number(value));\n}\n\nfunction formatTimeout(timeoutMs: number): string {\n return timeoutMs % 1000 === 0\n ? `${timeoutMs / 1000} seconds`\n : `${timeoutMs} milliseconds`;\n}\n\nexport function resolveCodeApiRunTimeoutMs(override?: number): number {\n return (\n normalizeTimeoutMs(override) ??\n parseTimeoutMs(process.env[EnvVar.CODE_API_RUN_TIMEOUT_MS]) ??\n DEFAULT_CODE_API_RUN_TIMEOUT_MS\n );\n}\n\nexport function clampCodeApiRunTimeoutMs(\n timeoutMs: number | undefined,\n maxRunTimeoutMs = resolveCodeApiRunTimeoutMs()\n): number {\n const normalizedMaxRunTimeoutMs =\n normalizeTimeoutMs(maxRunTimeoutMs) ?? DEFAULT_CODE_API_RUN_TIMEOUT_MS;\n const normalizedTimeoutMs = normalizeTimeoutMs(timeoutMs);\n\n if (normalizedTimeoutMs == null) {\n return normalizedMaxRunTimeoutMs;\n }\n\n return Math.min(normalizedTimeoutMs, normalizedMaxRunTimeoutMs);\n}\n\nexport function createCodeApiRunTimeoutSchema(\n maxRunTimeoutMs = resolveCodeApiRunTimeoutMs()\n): TimeoutSchema {\n const normalizedMaxRunTimeoutMs =\n normalizeTimeoutMs(maxRunTimeoutMs) ?? DEFAULT_CODE_API_RUN_TIMEOUT_MS;\n const formattedTimeout = formatTimeout(normalizedMaxRunTimeoutMs);\n\n return {\n type: 'integer',\n minimum: MIN_CODE_API_RUN_TIMEOUT_MS,\n maximum: normalizedMaxRunTimeoutMs,\n default: normalizedMaxRunTimeoutMs,\n description:\n 'Maximum wall-clock time in milliseconds for one sandbox run or replay iteration. ' +\n 'This is not the total multi-round-trip task budget. ' +\n `Default: ${formattedTimeout}. Max: ${formattedTimeout}.`,\n };\n}\n"],"names":[],"mappings":";;AAEO,MAAM,+BAA+B,GAAG;AACxC,MAAM,2BAA2B,GAAG;AAuB3C,SAAS,kBAAkB,CAAC,KAAyB,EAAA;AACnD,IAAA,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;AAC5C,QAAA,OAAO,SAAS;IAClB;AAEA,IAAA,OAAO,IAAI,CAAC,GAAG,CAAC,2BAA2B,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACjE;AAEA,SAAS,cAAc,CAAC,KAAyB,EAAA;IAC/C,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AACxC,Q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AAA,EAAU,gBAAgB,CAAA,CAAA,CAAG;KAC5D;AACH;;;;"}
|
|
@@ -186,13 +186,15 @@ export declare class AgentContext {
|
|
|
186
186
|
/**
|
|
187
187
|
* Builds instructions text for tools that are ONLY callable via programmatic code execution.
|
|
188
188
|
* These tools cannot be called directly by the LLM but are available through the
|
|
189
|
-
*
|
|
189
|
+
* configured programmatic tool.
|
|
190
190
|
*
|
|
191
191
|
* Includes:
|
|
192
192
|
* - Code_execution-only tools that are NOT deferred
|
|
193
193
|
* - Code_execution-only tools that ARE deferred but have been discovered via tool search
|
|
194
194
|
*/
|
|
195
195
|
private buildProgrammaticOnlyToolsInstructions;
|
|
196
|
+
private getProgrammaticToolInstructionTarget;
|
|
197
|
+
private hasAvailableTool;
|
|
196
198
|
/**
|
|
197
199
|
* Gets the system runnable, creating it lazily if needed.
|
|
198
200
|
* Includes stable instructions, dynamic additional instructions, and
|
|
@@ -1,47 +1,15 @@
|
|
|
1
1
|
import { DynamicStructuredTool } from '@langchain/core/tools';
|
|
2
|
+
import type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';
|
|
2
3
|
import type * as t from '@/types';
|
|
3
4
|
import { Constants } from '@/common';
|
|
4
|
-
export declare
|
|
5
|
-
|
|
6
|
-
readonly properties: {
|
|
7
|
-
readonly code: {
|
|
8
|
-
readonly type: "string";
|
|
9
|
-
readonly minLength: 1;
|
|
10
|
-
readonly description: "Bash code that calls tools programmatically. Tools are available as bash functions.\n\nCRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\nExample (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n web_search '{\"query\": \"SF weather\"}' > /tmp/sf.txt &\n web_search '{\"query\": \"NY weather\"}' > /tmp/ny.txt &\n wait\n echo \"SF: $(cat /tmp/sf.txt)\"\n echo \"NY: $(cat /tmp/ny.txt)\"\n\nRules:\n- EVERYTHING in one call—no state persists between executions\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Only echo/printf output returns to the model\n- Generated files are automatically available in /mnt/data/ for subsequent executions";
|
|
11
|
-
};
|
|
12
|
-
readonly timeout: {
|
|
13
|
-
readonly type: "integer";
|
|
14
|
-
readonly minimum: 1000;
|
|
15
|
-
readonly maximum: 300000;
|
|
16
|
-
readonly default: 60000;
|
|
17
|
-
readonly description: "Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.";
|
|
18
|
-
};
|
|
19
|
-
};
|
|
20
|
-
readonly required: readonly ["code"];
|
|
21
|
-
};
|
|
5
|
+
export declare function createBashProgrammaticToolCallingSchema(maxRunTimeoutMs?: number): ProgrammaticToolCallingJsonSchema;
|
|
6
|
+
export declare const BashProgrammaticToolCallingSchema: ProgrammaticToolCallingJsonSchema;
|
|
22
7
|
export declare const BashProgrammaticToolCallingName = Constants.BASH_PROGRAMMATIC_TOOL_CALLING;
|
|
23
8
|
export declare const BashProgrammaticToolCallingDescription: string;
|
|
24
9
|
export declare const BashProgrammaticToolCallingDefinition: {
|
|
25
10
|
readonly name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING;
|
|
26
11
|
readonly description: string;
|
|
27
|
-
readonly schema:
|
|
28
|
-
readonly type: "object";
|
|
29
|
-
readonly properties: {
|
|
30
|
-
readonly code: {
|
|
31
|
-
readonly type: "string";
|
|
32
|
-
readonly minLength: 1;
|
|
33
|
-
readonly description: "Bash code that calls tools programmatically. Tools are available as bash functions.\n\nCRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\nExample (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n web_search '{\"query\": \"SF weather\"}' > /tmp/sf.txt &\n web_search '{\"query\": \"NY weather\"}' > /tmp/ny.txt &\n wait\n echo \"SF: $(cat /tmp/sf.txt)\"\n echo \"NY: $(cat /tmp/ny.txt)\"\n\nRules:\n- EVERYTHING in one call—no state persists between executions\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Only echo/printf output returns to the model\n- Generated files are automatically available in /mnt/data/ for subsequent executions";
|
|
34
|
-
};
|
|
35
|
-
readonly timeout: {
|
|
36
|
-
readonly type: "integer";
|
|
37
|
-
readonly minimum: 1000;
|
|
38
|
-
readonly maximum: 300000;
|
|
39
|
-
readonly default: 60000;
|
|
40
|
-
readonly description: "Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.";
|
|
41
|
-
};
|
|
42
|
-
};
|
|
43
|
-
readonly required: readonly ["code"];
|
|
44
|
-
};
|
|
12
|
+
readonly schema: ProgrammaticToolCallingJsonSchema;
|
|
45
13
|
};
|
|
46
14
|
/**
|
|
47
15
|
* Normalizes a tool name to a valid bash function identifier.
|
|
@@ -25,6 +25,11 @@ export declare const CodeExecutionToolSchema: {
|
|
|
25
25
|
};
|
|
26
26
|
readonly required: readonly ["lang", "code"];
|
|
27
27
|
};
|
|
28
|
+
export declare function resolveCodeApiAuthHeaders(authHeaders?: t.CodeApiAuthHeaders): Promise<t.CodeApiAuthHeaderMap>;
|
|
29
|
+
export declare function buildCodeApiHttpErrorMessage(method: string, endpoint: string, response: {
|
|
30
|
+
status: number;
|
|
31
|
+
text: () => Promise<string>;
|
|
32
|
+
}): Promise<string>;
|
|
28
33
|
export declare const CodeExecutionToolDescription: string;
|
|
29
34
|
export declare const CodeExecutionToolName = Constants.EXECUTE_CODE;
|
|
30
35
|
export declare const CodeExecutionToolDefinition: {
|
|
@@ -1,47 +1,24 @@
|
|
|
1
1
|
import { DynamicStructuredTool } from '@langchain/core/tools';
|
|
2
|
+
import type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';
|
|
2
3
|
import type * as t from '@/types';
|
|
3
4
|
import { Constants } from '@/common';
|
|
4
|
-
export declare
|
|
5
|
-
|
|
6
|
-
readonly properties: {
|
|
7
|
-
readonly code: {
|
|
8
|
-
readonly type: "string";
|
|
9
|
-
readonly minLength: 1;
|
|
10
|
-
readonly description: "Python code that calls tools programmatically. Tools are available as async functions.\n\nCRITICAL - STATELESS EXECUTION:\nEach call is a fresh Python interpreter. Variables, imports, and data do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block: query → process → output.\nDO NOT split work across multiple calls expecting to reuse variables.\n\nYour code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.\n\nExample (Complete workflow in one call):\n # Query data\n data = await query_database(sql=\"SELECT * FROM users\")\n # Process it\n df = pd.DataFrame(data)\n summary = df.groupby('region').sum()\n # Output results\n await write_to_sheet(spreadsheet_id=sid, data=summary.to_dict())\n print(f\"Wrote {len(summary)} rows\")\n\nExample (Parallel calls):\n sf, ny = await asyncio.gather(get_weather(city=\"SF\"), get_weather(city=\"NY\"))\n print(f\"SF: {sf}, NY: {ny}\")\n\nRules:\n- EVERYTHING in one call—no state persists between executions\n- Just write code with await—auto-wrapped in async context\n- DO NOT define async def main() or call asyncio.run()\n- Tools are pre-defined—DO NOT write function definitions\n- Only print() output returns to the model";
|
|
11
|
-
};
|
|
12
|
-
readonly timeout: {
|
|
13
|
-
readonly type: "integer";
|
|
14
|
-
readonly minimum: 1000;
|
|
15
|
-
readonly maximum: 300000;
|
|
16
|
-
readonly default: 60000;
|
|
17
|
-
readonly description: "Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.";
|
|
18
|
-
};
|
|
19
|
-
};
|
|
20
|
-
readonly required: readonly ["code"];
|
|
21
|
-
};
|
|
5
|
+
export declare function createProgrammaticToolCallingSchema(maxRunTimeoutMs?: number): ProgrammaticToolCallingJsonSchema;
|
|
6
|
+
export declare const ProgrammaticToolCallingSchema: ProgrammaticToolCallingJsonSchema;
|
|
22
7
|
export declare const ProgrammaticToolCallingName = Constants.PROGRAMMATIC_TOOL_CALLING;
|
|
23
8
|
export declare const ProgrammaticToolCallingDescription: string;
|
|
24
9
|
export declare const ProgrammaticToolCallingDefinition: {
|
|
25
10
|
readonly name: Constants.PROGRAMMATIC_TOOL_CALLING;
|
|
26
11
|
readonly description: string;
|
|
27
|
-
readonly schema:
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
readonly minimum: 1000;
|
|
38
|
-
readonly maximum: 300000;
|
|
39
|
-
readonly default: 60000;
|
|
40
|
-
readonly description: "Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.";
|
|
41
|
-
};
|
|
42
|
-
};
|
|
43
|
-
readonly required: readonly ["code"];
|
|
44
|
-
};
|
|
12
|
+
readonly schema: ProgrammaticToolCallingJsonSchema;
|
|
13
|
+
};
|
|
14
|
+
export type FetchSessionFilesScope = {
|
|
15
|
+
kind: 'skill';
|
|
16
|
+
id: string;
|
|
17
|
+
version: number;
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'agent' | 'user';
|
|
20
|
+
id: string;
|
|
21
|
+
version?: never;
|
|
45
22
|
};
|
|
46
23
|
/**
|
|
47
24
|
* Normalizes a tool name to Python identifier format.
|
|
@@ -76,10 +53,12 @@ export declare function filterToolsByUsage(toolDefs: t.LCTool[], code: string, d
|
|
|
76
53
|
* Files are returned as CodeEnvFile references to be included in the request.
|
|
77
54
|
* @param baseUrl - The base URL for the Code API
|
|
78
55
|
* @param sessionId - The session ID to fetch files from
|
|
56
|
+
* @param scope - Resource scope used by CodeAPI to authorize the session
|
|
79
57
|
* @param proxy - Optional HTTP proxy URL
|
|
80
58
|
* @returns Array of CodeEnvFile references, or empty array if fetch fails
|
|
81
59
|
*/
|
|
82
|
-
export declare function fetchSessionFiles(baseUrl: string, sessionId: string, proxy?: string): Promise<t.CodeEnvFile[]>;
|
|
60
|
+
export declare function fetchSessionFiles(baseUrl: string, sessionId: string, proxy?: string, authHeaders?: t.CodeApiAuthHeaders): Promise<t.CodeEnvFile[]>;
|
|
61
|
+
export declare function fetchSessionFiles(baseUrl: string, sessionId: string, scope: FetchSessionFilesScope, proxyOrAuthHeaders?: string | t.CodeApiAuthHeaders, authHeaders?: t.CodeApiAuthHeaders): Promise<t.CodeEnvFile[]>;
|
|
83
62
|
/**
|
|
84
63
|
* Makes an HTTP request to the Code API.
|
|
85
64
|
* @param endpoint - The API endpoint URL
|
|
@@ -87,7 +66,7 @@ export declare function fetchSessionFiles(baseUrl: string, sessionId: string, pr
|
|
|
87
66
|
* @param proxy - Optional HTTP proxy URL
|
|
88
67
|
* @returns The parsed API response
|
|
89
68
|
*/
|
|
90
|
-
export declare function makeRequest(endpoint: string, body: Record<string, unknown>, proxy?: string): Promise<t.ProgrammaticExecutionResponse>;
|
|
69
|
+
export declare function makeRequest(endpoint: string, body: Record<string, unknown>, proxy?: string, authHeaders?: t.CodeApiAuthHeaders): Promise<t.ProgrammaticExecutionResponse>;
|
|
91
70
|
/**
|
|
92
71
|
* Unwraps tool responses that may be formatted as tuples or content blocks.
|
|
93
72
|
* MCP tools return [content, artifacts], we need to extract the raw data.
|
|
@@ -104,7 +83,7 @@ export declare function unwrapToolResponse(result: unknown, isMCPTool: boolean):
|
|
|
104
83
|
* @param toolMap - Map of tool names to executable tools
|
|
105
84
|
* @returns Array of tool results
|
|
106
85
|
*/
|
|
107
|
-
export declare function executeTools(toolCalls: t.PTCToolCall[], toolMap: t.ToolMap): Promise<t.PTCToolResult[]>;
|
|
86
|
+
export declare function executeTools(toolCalls: t.PTCToolCall[], toolMap: t.ToolMap, programmaticToolName?: Constants): Promise<t.PTCToolResult[]>;
|
|
108
87
|
/**
|
|
109
88
|
* Formats the completed response for the agent.
|
|
110
89
|
*
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare const DEFAULT_CODE_API_RUN_TIMEOUT_MS = 15000;
|
|
2
|
+
export declare const MIN_CODE_API_RUN_TIMEOUT_MS = 1000;
|
|
3
|
+
type TimeoutSchema = {
|
|
4
|
+
type: 'integer';
|
|
5
|
+
minimum: number;
|
|
6
|
+
maximum: number;
|
|
7
|
+
default: number;
|
|
8
|
+
description: string;
|
|
9
|
+
};
|
|
10
|
+
export type ProgrammaticToolCallingJsonSchema = {
|
|
11
|
+
type: 'object';
|
|
12
|
+
properties: {
|
|
13
|
+
code: {
|
|
14
|
+
type: 'string';
|
|
15
|
+
minLength: number;
|
|
16
|
+
description: string;
|
|
17
|
+
};
|
|
18
|
+
timeout: TimeoutSchema;
|
|
19
|
+
};
|
|
20
|
+
required: readonly ['code'];
|
|
21
|
+
};
|
|
22
|
+
export declare function resolveCodeApiRunTimeoutMs(override?: number): number;
|
|
23
|
+
export declare function clampCodeApiRunTimeoutMs(timeoutMs: number | undefined, maxRunTimeoutMs?: number): number;
|
|
24
|
+
export declare function createCodeApiRunTimeoutSchema(maxRunTimeoutMs?: number): TimeoutSchema;
|
|
25
|
+
export {};
|
|
@@ -205,7 +205,11 @@ export type CodeExecutionToolParams = undefined | {
|
|
|
205
205
|
session_id?: string;
|
|
206
206
|
user_id?: string;
|
|
207
207
|
files?: CodeEnvFile[];
|
|
208
|
+
/** Optional host-supplied Code API auth headers. */
|
|
209
|
+
authHeaders?: CodeApiAuthHeaders;
|
|
208
210
|
};
|
|
211
|
+
export type CodeApiAuthHeaderMap = Record<string, string>;
|
|
212
|
+
export type CodeApiAuthHeaders = CodeApiAuthHeaderMap | (() => CodeApiAuthHeaderMap | Promise<CodeApiAuthHeaderMap>);
|
|
209
213
|
export type FileRef = {
|
|
210
214
|
/**
|
|
211
215
|
* Storage file id (the per-file uuid). See `CodeEnvFile.id` for
|
|
@@ -821,10 +825,14 @@ export type ProgrammaticToolCallingParams = {
|
|
|
821
825
|
baseUrl?: string;
|
|
822
826
|
/** Safety limit for round-trips (default: 20) */
|
|
823
827
|
maxRoundTrips?: number;
|
|
828
|
+
/** Maximum per-sandbox-run timeout for PTC's legacy `timeout` field. */
|
|
829
|
+
runTimeoutMs?: number;
|
|
824
830
|
/** HTTP proxy URL */
|
|
825
831
|
proxy?: string;
|
|
826
832
|
/** Enable debug logging (or set PTC_DEBUG=true env var) */
|
|
827
833
|
debug?: boolean;
|
|
834
|
+
/** Optional host-supplied Code API auth headers. */
|
|
835
|
+
authHeaders?: CodeApiAuthHeaders;
|
|
828
836
|
};
|
|
829
837
|
/**
|
|
830
838
|
* Tracks code execution session state for automatic file persistence.
|