| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231 |
- import { createPaasRuntime } from "../src/main/paas-runtime"
- import { mkdtemp, rm } from "node:fs/promises"
- import { join } from "node:path"
- import { tmpdir } from "node:os"
- // Isolated source-runtime acceptance. All model/tool endpoints and credentials
- // below are synthetic; no existing app, service or account is used.
- const source = process.env.LAMBDA_AGENT_PAAS_SOURCE
- const python = process.env.LAMBDA_AGENT_PAAS_PYTHON
- const binary = process.env.LAMBDA_AGENT_PAAS_BINARY
- if (!binary && (!source || !python))
- throw new Error("Set LAMBDA_AGENT_PAAS_SOURCE and LAMBDA_AGENT_PAAS_PYTHON for the source runtime.")
- if (source && !binary)
- process.env.PYTHONPATH = [join(source, "agentpaas/src"), join(source, "lambdagent/src"), process.env.PYTHONPATH]
- .filter(Boolean)
- .join(process.platform === "win32" ? ";" : ":")
- const root = await mkdtemp(join(tmpdir(), "lambda-native-setup-"))
- const runtime = createPaasRuntime({
- root,
- bundled: "",
- command: async () => (binary ? { file: binary, args: [] } : { file: python!, args: ["-m", "agentpaas"] }),
- timeout: 60000,
- })
- let modelCalls = 0
- const model = Bun.serve({
- hostname: "127.0.0.1",
- port: 0,
- fetch: async (req) => {
- if (req.headers.get("authorization") !== "Bearer synthetic-local-model-key")
- return new Response("invalid test credential", { status: 401 })
- modelCalls++
- const body = await req.json()
- const ping = body.tools?.find((tool: { function?: { name?: string }; name?: string }) =>
- tool.function?.name?.endsWith("ping"),
- )
- if (ping && !body.messages.some((message: { role: string }) => message.role === "tool"))
- return Response.json({
- id: "test-tools",
- object: "chat.completion",
- created: 1,
- model: "synthetic-model",
- choices: [
- {
- index: 0,
- message: {
- role: "assistant",
- content: null,
- tool_calls: [
- {
- id: "synthetic-call",
- type: "function",
- function: { name: ping.function.name, arguments: JSON.stringify({ value: "round1" }) },
- },
- ],
- },
- finish_reason: "tool_calls",
- },
- ],
- usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 },
- })
- return Response.json({
- id: "synthetic-response",
- object: "chat.completion",
- created: 1,
- model: "synthetic-model",
- choices: [{ index: 0, message: { role: "assistant", content: "本机任务完成。" }, finish_reason: "stop" }],
- usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 },
- })
- },
- })
- let toolCalls = 0
- let toolAuth = 0
- const mcp = Bun.serve({
- hostname: "127.0.0.1",
- port: 0,
- fetch: async (req) => {
- if (req.headers.get("authorization") !== "Bearer synthetic-local-tool-key")
- return new Response("invalid synthetic credential", { status: 401 })
- toolAuth++
- if (req.method !== "POST") return new Response("", { status: 405 })
- const body = await req.json()
- if (body.id === undefined) return new Response(null, { status: 202 })
- const result =
- body.method === "initialize"
- ? {
- protocolVersion: "2025-03-26",
- capabilities: { tools: {} },
- serverInfo: { name: "synthetic", version: "1" },
- }
- : body.method === "tools/list"
- ? {
- tools: [
- {
- name: "ping",
- description: "Echo a test value",
- inputSchema: { type: "object", properties: { value: { type: "string" } }, required: ["value"] },
- },
- ],
- }
- : body.method === "tools/call"
- ? (toolCalls++,
- { content: [{ type: "text", text: "pong:" + body.params.arguments.value }], isError: false })
- : {}
- return Response.json({ jsonrpc: "2.0", id: body.id, result })
- },
- })
- try {
- await runtime.start()
- let connection = runtime.connection()!
- async function api(path: string, body?: unknown, method = body ? "POST" : "GET") {
- const res = await fetch(connection.url + "/api/v1" + path, {
- method,
- headers: { Authorization: `Bearer ${connection.apiKey}`, "Content-Type": "application/json" },
- body: body ? JSON.stringify(body) : undefined,
- })
- const data = await res.json()
- if (!res.ok) throw new Error(`Synthetic setup smoke ${path}: HTTP ${res.status} ${JSON.stringify(data)}`)
- return data
- }
- const setup = await api("/desktop/setup")
- const selfCheck = await api("/desktop/self-check", {})
- if (selfCheck.control_plane !== "passed" || selfCheck.mode !== "deterministic" || modelCalls !== 0)
- throw new Error("Self-check must verify file I/O through the executor without a model call")
- await api("/desktop/providers/openai", { api_key: "synthetic-local-model-key" })
- const created = await api("/agents", {
- name: "Synthetic setup acceptance",
- config: {
- type: "simple",
- systemPrompt: "Answer briefly.",
- model: { provider: "openai", name: "synthetic-model", baseUrl: `http://127.0.0.1:${model.port}/v1` },
- },
- })
- const id = created.agent_id || created.id
- if (!id) throw new Error("No agent identity returned")
- const detail = await api("/agents/" + id)
- await api(
- "/desktop/agents/" + id + "/model",
- {
- provider: "openai",
- name: "synthetic-model",
- base_url: `http://127.0.0.1:${model.port}/v1`,
- expected_updated_at: detail.updated_at,
- },
- "PUT",
- )
- const run = await api("/agents/" + id + "/run", { input: "Test first task", mode: "iterate" })
- const toolAgent = await api("/agents", {
- name: "Synthetic tool acceptance",
- config: {
- type: "react",
- systemPrompt: "Use the ping tool.",
- react: { maxSteps: 4 },
- model: { provider: "openai", name: "synthetic-model", baseUrl: `http://127.0.0.1:${model.port}/v1` },
- },
- })
- const toolID = toolAgent.agent_id || toolAgent.id
- const toolURL = `http://127.0.0.1:${mcp.port}/mcp`
- const credential = await api("/desktop/tool-credentials", {
- agent_id: toolID,
- connection_id: "desktop_synthetic",
- url: toolURL,
- token: "synthetic-local-tool-key",
- })
- const inspection = await api("/mcp/inspect", { url: toolURL, bearer_env: credential.name })
- if (
- inspection.status !== "ok" ||
- !inspection.tools.some((tool: { function?: { name?: string }; name?: string }) => tool.name === "ping")
- )
- throw new Error("MCP inspect failed " + JSON.stringify(inspection))
- const toolDetail = await api("/agents/" + toolID)
- const config = {
- ...toolDetail.config,
- mcp: { onlineTool: { desktop_synthetic: ["ping"] } },
- app: {
- mcp: {
- custom: {
- nodes: {
- desktop_synthetic: {
- url: toolURL,
- protocol: "streamable-http",
- headers: { Authorization: "Bearer ${" + credential.name + "}" },
- },
- },
- },
- },
- },
- }
- await api("/agents/" + toolID, { config, expected_updated_at: toolDetail.updated_at }, "PUT")
- const toolRun = await api("/agents/" + toolID + "/run", { input: "Use ping with value round1.", mode: "iterate" })
- if (toolCalls !== 1 || toolRun.status !== "completed")
- throw new Error("Tool execution failed " + JSON.stringify({ toolCalls, toolRun }))
- for await (const path of new Bun.Glob("**/config.yml").scan({ cwd: root, absolute: true, dot: true })) {
- const content = await Bun.file(path).text()
- if (content.includes("synthetic-local-model-key") || content.includes("synthetic-local-tool-key"))
- throw new Error("Credential persisted into task snapshot")
- }
- await runtime.stop()
- const callsBeforeRestart = modelCalls
- await runtime.start()
- connection = runtime.connection()!
- const restoredRun = await api(`/agents/${id}/runs/${run.run_id || run.id}`)
- const restoredToolRun = await api(`/agents/${toolID}/runs/${toolRun.run_id || toolRun.id}`)
- if (
- restoredRun.status !== "completed" ||
- restoredToolRun.status !== "completed" ||
- toolCalls !== 1 ||
- modelCalls !== callsBeforeRestart
- )
- throw new Error("Restart did not preserve results without replay")
- console.log(
- JSON.stringify({
- restartPreserved: true,
- selfCheck,
- replayedCalls: modelCalls - callsBeforeRestart,
- toolCalls,
- toolAuth,
- toolRunStatus: toolRun.status,
- phase: (await runtime.status()).phase,
- providers: setup.providers.length,
- linked: setup.executor_linked,
- runStatus: run.status,
- output: run.output,
- modelCalls,
- }),
- )
- if (!modelCalls || run.status === "failed") throw new Error("Synthetic task did not complete")
- } finally {
- mcp.stop(true)
- model.stop(true)
- await runtime.stop()
- await rm(root, { recursive: true, force: true })
- }
|