smoke-paas-setup.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import { createPaasRuntime } from "../src/main/paas-runtime"
  2. import { mkdtemp, rm } from "node:fs/promises"
  3. import { join } from "node:path"
  4. import { tmpdir } from "node:os"
  5. // Isolated source-runtime acceptance. All model/tool endpoints and credentials
  6. // below are synthetic; no existing app, service or account is used.
  7. const source = process.env.LAMBDA_AGENT_PAAS_SOURCE
  8. const python = process.env.LAMBDA_AGENT_PAAS_PYTHON
  9. const binary = process.env.LAMBDA_AGENT_PAAS_BINARY
  10. if (!binary && (!source || !python))
  11. throw new Error("Set LAMBDA_AGENT_PAAS_SOURCE and LAMBDA_AGENT_PAAS_PYTHON for the source runtime.")
  12. if (source && !binary)
  13. process.env.PYTHONPATH = [join(source, "agentpaas/src"), join(source, "lambdagent/src"), process.env.PYTHONPATH]
  14. .filter(Boolean)
  15. .join(process.platform === "win32" ? ";" : ":")
  16. const root = await mkdtemp(join(tmpdir(), "lambda-native-setup-"))
  17. const runtime = createPaasRuntime({
  18. root,
  19. bundled: "",
  20. command: async () => (binary ? { file: binary, args: [] } : { file: python!, args: ["-m", "agentpaas"] }),
  21. timeout: 60000,
  22. })
  23. let modelCalls = 0
  24. const model = Bun.serve({
  25. hostname: "127.0.0.1",
  26. port: 0,
  27. fetch: async (req) => {
  28. if (req.headers.get("authorization") !== "Bearer synthetic-local-model-key")
  29. return new Response("invalid test credential", { status: 401 })
  30. modelCalls++
  31. const body = await req.json()
  32. const ping = body.tools?.find((tool: { function?: { name?: string }; name?: string }) =>
  33. tool.function?.name?.endsWith("ping"),
  34. )
  35. if (ping && !body.messages.some((message: { role: string }) => message.role === "tool"))
  36. return Response.json({
  37. id: "test-tools",
  38. object: "chat.completion",
  39. created: 1,
  40. model: "synthetic-model",
  41. choices: [
  42. {
  43. index: 0,
  44. message: {
  45. role: "assistant",
  46. content: null,
  47. tool_calls: [
  48. {
  49. id: "synthetic-call",
  50. type: "function",
  51. function: { name: ping.function.name, arguments: JSON.stringify({ value: "round1" }) },
  52. },
  53. ],
  54. },
  55. finish_reason: "tool_calls",
  56. },
  57. ],
  58. usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 },
  59. })
  60. return Response.json({
  61. id: "synthetic-response",
  62. object: "chat.completion",
  63. created: 1,
  64. model: "synthetic-model",
  65. choices: [{ index: 0, message: { role: "assistant", content: "本机任务完成。" }, finish_reason: "stop" }],
  66. usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 },
  67. })
  68. },
  69. })
  70. let toolCalls = 0
  71. let toolAuth = 0
  72. const mcp = Bun.serve({
  73. hostname: "127.0.0.1",
  74. port: 0,
  75. fetch: async (req) => {
  76. if (req.headers.get("authorization") !== "Bearer synthetic-local-tool-key")
  77. return new Response("invalid synthetic credential", { status: 401 })
  78. toolAuth++
  79. if (req.method !== "POST") return new Response("", { status: 405 })
  80. const body = await req.json()
  81. if (body.id === undefined) return new Response(null, { status: 202 })
  82. const result =
  83. body.method === "initialize"
  84. ? {
  85. protocolVersion: "2025-03-26",
  86. capabilities: { tools: {} },
  87. serverInfo: { name: "synthetic", version: "1" },
  88. }
  89. : body.method === "tools/list"
  90. ? {
  91. tools: [
  92. {
  93. name: "ping",
  94. description: "Echo a test value",
  95. inputSchema: { type: "object", properties: { value: { type: "string" } }, required: ["value"] },
  96. },
  97. ],
  98. }
  99. : body.method === "tools/call"
  100. ? (toolCalls++,
  101. { content: [{ type: "text", text: "pong:" + body.params.arguments.value }], isError: false })
  102. : {}
  103. return Response.json({ jsonrpc: "2.0", id: body.id, result })
  104. },
  105. })
  106. try {
  107. await runtime.start()
  108. let connection = runtime.connection()!
  109. async function api(path: string, body?: unknown, method = body ? "POST" : "GET") {
  110. const res = await fetch(connection.url + "/api/v1" + path, {
  111. method,
  112. headers: { Authorization: `Bearer ${connection.apiKey}`, "Content-Type": "application/json" },
  113. body: body ? JSON.stringify(body) : undefined,
  114. })
  115. const data = await res.json()
  116. if (!res.ok) throw new Error(`Synthetic setup smoke ${path}: HTTP ${res.status} ${JSON.stringify(data)}`)
  117. return data
  118. }
  119. const setup = await api("/desktop/setup")
  120. const selfCheck = await api("/desktop/self-check", {})
  121. if (selfCheck.control_plane !== "passed" || selfCheck.mode !== "deterministic" || modelCalls !== 0)
  122. throw new Error("Self-check must verify file I/O through the executor without a model call")
  123. await api("/desktop/providers/openai", { api_key: "synthetic-local-model-key" })
  124. const created = await api("/agents", {
  125. name: "Synthetic setup acceptance",
  126. config: {
  127. type: "simple",
  128. systemPrompt: "Answer briefly.",
  129. model: { provider: "openai", name: "synthetic-model", baseUrl: `http://127.0.0.1:${model.port}/v1` },
  130. },
  131. })
  132. const id = created.agent_id || created.id
  133. if (!id) throw new Error("No agent identity returned")
  134. const detail = await api("/agents/" + id)
  135. await api(
  136. "/desktop/agents/" + id + "/model",
  137. {
  138. provider: "openai",
  139. name: "synthetic-model",
  140. base_url: `http://127.0.0.1:${model.port}/v1`,
  141. expected_updated_at: detail.updated_at,
  142. },
  143. "PUT",
  144. )
  145. const run = await api("/agents/" + id + "/run", { input: "Test first task", mode: "iterate" })
  146. const toolAgent = await api("/agents", {
  147. name: "Synthetic tool acceptance",
  148. config: {
  149. type: "react",
  150. systemPrompt: "Use the ping tool.",
  151. react: { maxSteps: 4 },
  152. model: { provider: "openai", name: "synthetic-model", baseUrl: `http://127.0.0.1:${model.port}/v1` },
  153. },
  154. })
  155. const toolID = toolAgent.agent_id || toolAgent.id
  156. const toolURL = `http://127.0.0.1:${mcp.port}/mcp`
  157. const credential = await api("/desktop/tool-credentials", {
  158. agent_id: toolID,
  159. connection_id: "desktop_synthetic",
  160. url: toolURL,
  161. token: "synthetic-local-tool-key",
  162. })
  163. const inspection = await api("/mcp/inspect", { url: toolURL, bearer_env: credential.name })
  164. if (
  165. inspection.status !== "ok" ||
  166. !inspection.tools.some((tool: { function?: { name?: string }; name?: string }) => tool.name === "ping")
  167. )
  168. throw new Error("MCP inspect failed " + JSON.stringify(inspection))
  169. const toolDetail = await api("/agents/" + toolID)
  170. const config = {
  171. ...toolDetail.config,
  172. mcp: { onlineTool: { desktop_synthetic: ["ping"] } },
  173. app: {
  174. mcp: {
  175. custom: {
  176. nodes: {
  177. desktop_synthetic: {
  178. url: toolURL,
  179. protocol: "streamable-http",
  180. headers: { Authorization: "Bearer ${" + credential.name + "}" },
  181. },
  182. },
  183. },
  184. },
  185. },
  186. }
  187. await api("/agents/" + toolID, { config, expected_updated_at: toolDetail.updated_at }, "PUT")
  188. const toolRun = await api("/agents/" + toolID + "/run", { input: "Use ping with value round1.", mode: "iterate" })
  189. if (toolCalls !== 1 || toolRun.status !== "completed")
  190. throw new Error("Tool execution failed " + JSON.stringify({ toolCalls, toolRun }))
  191. for await (const path of new Bun.Glob("**/config.yml").scan({ cwd: root, absolute: true, dot: true })) {
  192. const content = await Bun.file(path).text()
  193. if (content.includes("synthetic-local-model-key") || content.includes("synthetic-local-tool-key"))
  194. throw new Error("Credential persisted into task snapshot")
  195. }
  196. await runtime.stop()
  197. const callsBeforeRestart = modelCalls
  198. await runtime.start()
  199. connection = runtime.connection()!
  200. const restoredRun = await api(`/agents/${id}/runs/${run.run_id || run.id}`)
  201. const restoredToolRun = await api(`/agents/${toolID}/runs/${toolRun.run_id || toolRun.id}`)
  202. if (
  203. restoredRun.status !== "completed" ||
  204. restoredToolRun.status !== "completed" ||
  205. toolCalls !== 1 ||
  206. modelCalls !== callsBeforeRestart
  207. )
  208. throw new Error("Restart did not preserve results without replay")
  209. console.log(
  210. JSON.stringify({
  211. restartPreserved: true,
  212. selfCheck,
  213. replayedCalls: modelCalls - callsBeforeRestart,
  214. toolCalls,
  215. toolAuth,
  216. toolRunStatus: toolRun.status,
  217. phase: (await runtime.status()).phase,
  218. providers: setup.providers.length,
  219. linked: setup.executor_linked,
  220. runStatus: run.status,
  221. output: run.output,
  222. modelCalls,
  223. }),
  224. )
  225. if (!modelCalls || run.status === "failed") throw new Error("Synthetic task did not complete")
  226. } finally {
  227. mcp.stop(true)
  228. model.stop(true)
  229. await runtime.stop()
  230. await rm(root, { recursive: true, force: true })
  231. }