managed-environment.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import { BrowserWindow, ipcMain, webContents, type WebContents } from "electron";
  2. import assert from "node:assert/strict";
  3. import { join } from "node:path";
  4. import { V4_WIRE_PROTOCOL_VERSION } from "@zcode/shared/zcode-protocol-v4";
  5. import { installPluginSandboxHost } from "../../src/main/pluginSandbox/index.js";
  6. import { createPluginUiBridgeService } from "../../../services/src/plugin-ui-bridge/pluginUiBridgeService.js";
  7. import { createPluginUiSamplingService } from "../../../services/src/plugin-ui-bridge/pluginUiSamplingService.js";
  8. import { Events, startAgent } from "./agent.js";
  9. import { startModel } from "./model.js";
  10. import { evaluateGuest } from "./guest-evaluation.js";
  11. export async function managedEnvironment(root: string, node: string, cli: string) {
  12. const model = await startModel(root, cli);
  13. const agent = await startAgent(root, node, cli, model.env);
  14. const events = new Events<any>();
  15. const windows: BrowserWindow[] = [];
  16. const modes = new Map<number, string>();
  17. const scopes = new Map<number, any>();
  18. const gates = new Map<string, Promise<void>>();
  19. const handles = new Map<number, any>();
  20. const guests = new Map<number, WebContents>();
  21. const native = installPluginSandboxHost({
  22. rendererDir: root,
  23. aliasDir: root,
  24. preloadPath: join(root, "guest.cjs"),
  25. });
  26. const wire = (p: any) => {
  27. const {
  28. workspacePath,
  29. workspaceIdentity,
  30. scopeId: _scope,
  31. resourceUri: _uri,
  32. ownerWebContentsId: _owner,
  33. csp: _csp,
  34. prefersBorder: _border,
  35. ...rest
  36. } = p;
  37. return {
  38. ...rest,
  39. workspace: {
  40. workspacePath,
  41. workspaceKey: workspaceIdentity?.trim() || workspacePath,
  42. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  43. },
  44. };
  45. };
  46. const sampling = createPluginUiSamplingService({
  47. sample: (p) => agent.call("mcp/uiSampling", wire(p)),
  48. cancelSampling: (p) => agent.call("mcp/uiCancelSampling", wire(p)),
  49. });
  50. const bridge = createPluginUiBridgeService({
  51. openInstance: (p) =>
  52. agent.call("mcp/uiOpenInstance", {
  53. ...wire(p),
  54. resourceUri: p.resourceUri,
  55. scopeId: p.scopeId,
  56. ownerWebContentsId: p.ownerWebContentsId,
  57. }),
  58. validateInstance: (p) => agent.call("mcp/uiValidateInstance", wire(p)),
  59. closeInstance: (p) => agent.call("mcp/uiCloseInstance", wire(p)),
  60. recycleInstance: async (p) =>
  61. (await agent.call("mcp/uiCloseInstance", { ...wire(p), onlyIfIdle: true })).closed,
  62. readMcpResource: (p) => agent.call("mcp/readResource", wire(p)),
  63. callMcpToolForUi: (p) => agent.call("mcp/uiCallTool", wire(p)),
  64. cancelMcpToolCallForUi: (p) => agent.call("mcp/uiCancelCall", wire(p)),
  65. readMcpResourceForUi: (p) => agent.call("mcp/uiReadResource", wire(p)),
  66. listMcpResourcesForUi: (p) => agent.call("mcp/uiListResources", wire(p)),
  67. listMcpResourceTemplatesForUi: (p) => agent.call("mcp/uiListResourceTemplates", wire(p)),
  68. subscribeMcpResourceForUi: (p) =>
  69. agent.call("mcp/uiSubscribeResource", { ...wire(p), scopeId: p.scopeId }),
  70. unsubscribeMcpResourceForUi: (p) =>
  71. agent.call("mcp/uiUnsubscribeResource", { ...wire(p), scopeId: p.scopeId }),
  72. registerSandbox: async (p) => {
  73. const handle = native.registerFromHost(p);
  74. handles.set(p.ownerWebContentsId, handle);
  75. events.emit({ type: "registered", owner: p.ownerWebContentsId, handle });
  76. return handle;
  77. },
  78. });
  79. agent.client.onNotification((event) => {
  80. if (event.method !== "v4/conversation/frame") return;
  81. for (const win of windows) {
  82. if (
  83. !win.isDestroyed() &&
  84. event.params.topic === `conversation/${scopes.get(win.webContents.id)?.sessionId}`
  85. )
  86. win.webContents.send("fixture-notification", { kind: "frame", value: event.params });
  87. }
  88. });
  89. ipcMain.handle("fixture-config", (event) => {
  90. const scope = scopes.get(event.sender.id);
  91. return {
  92. mode: modes.get(event.sender.id),
  93. scope: {
  94. ...scope.workspace,
  95. sessionId: scope.sessionId,
  96. scope: { kind: "surface", surfaceId: "same" },
  97. },
  98. presentation: {
  99. pluginId: scope.pluginId,
  100. serverName: scope.serverName,
  101. resourceUri: scope.resourceUri ?? "ui://fixture",
  102. },
  103. };
  104. });
  105. ipcMain.handle("fixture-event", (event, value) =>
  106. events.emit({ ...value, owner: event.sender.id }),
  107. );
  108. ipcMain.handle("fixture-bridge", async (event, method, params) => {
  109. const scope = scopes.get(event.sender.id);
  110. assert.equal(params.sessionId, scope.sessionId);
  111. assert.equal(params.serverName, scope.serverName);
  112. const result = await ({ ...bridge, ...sampling } as any)[method](params);
  113. events.emit({ type: "bridge", method, owner: event.sender.id });
  114. await gates.get(`return:${method}`);
  115. return result;
  116. });
  117. ipcMain.handle("fixture-app-tools", async (event, method, params) => {
  118. const methods: Record<string, string> = {
  119. registerAppTools: "mcp/uiRegisterAppTools",
  120. unregisterAppTools: "mcp/uiUnregisterAppTools",
  121. claimAppToolCall: "mcp/uiClaimAppToolCall",
  122. resolveAppToolCall: "mcp/uiResolveAppToolCall",
  123. };
  124. assert.ok(methods[method]);
  125. events.emit({ type: "app-tools-arrived", method, owner: event.sender.id, params });
  126. await gates.get(method);
  127. const result = await agent.call(methods[method]!, { ...wire(params), scopeId: params.scopeId });
  128. events.emit({ type: method, owner: event.sender.id, params, result });
  129. return result;
  130. });
  131. ipcMain.handle("fixture-v4", async (event, method, params) => {
  132. const scope = scopes.get(event.sender.id);
  133. const connectionId = `managed-${event.sender.id}`;
  134. if (method === "helloConversationV4")
  135. return {
  136. kind: "hello",
  137. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  138. connectionId,
  139. clientMode: "desktop-continuous",
  140. deliveryProfile: "continuous",
  141. serverTime: Date.now(),
  142. capabilities: {
  143. nativeDialogs: true,
  144. localTerminal: true,
  145. binaryFrames: false,
  146. compression: "none",
  147. independentPlanState: true,
  148. },
  149. auth: {},
  150. };
  151. if (method === "initializeConversationV4") return;
  152. if (method === "subscribeConversationV4") {
  153. const result = await agent.call("v4/conversation/subscribe", {
  154. connectionId,
  155. clientMode: "desktop-continuous",
  156. workspace: scope.workspace,
  157. topic: `conversation/${params.sessionId}`,
  158. ...(params.visibility ? { visibility: params.visibility } : {}),
  159. });
  160. events.emit({ type: "subscribed", owner: event.sender.id });
  161. return result;
  162. }
  163. if (method === "unsubscribeConversationV4") {
  164. const result = await agent.call("v4/conversation/unsubscribe", {
  165. connectionId,
  166. topic: `conversation/${params.sessionId}`,
  167. subscriptionId: params.subscriptionId,
  168. });
  169. events.emit({ type: "unsubscribed", owner: event.sender.id });
  170. return result;
  171. }
  172. if (method === "resyncConversationV4")
  173. return agent.call("v4/conversation/resync", { connectionId, ...params });
  174. throw new Error(`Unexpected managed service call ${method}`);
  175. });
  176. async function createWindow(scope: any, mode = "local") {
  177. const win = new BrowserWindow({
  178. show: false,
  179. width: 1000,
  180. height: 700,
  181. webPreferences: {
  182. preload: join(root, "preload.cjs"),
  183. webviewTag: true,
  184. backgroundThrottling: false,
  185. },
  186. });
  187. windows.push(win);
  188. modes.set(win.webContents.id, mode);
  189. scopes.set(win.webContents.id, scope);
  190. win.webContents.on("console-message", (e) => process.stderr.write(`${e.message}\n`));
  191. const pending: string[] = [];
  192. win.webContents.on("will-attach-webview", (event, webPreferences, params) => {
  193. const result = native.configureGuest({
  194. webPreferences,
  195. params,
  196. ownerWebContentsId: win.webContents.id,
  197. });
  198. if (!result.ok) event.preventDefault();
  199. else pending.push(result.sandboxId);
  200. });
  201. win.webContents.on("did-attach-webview", (_event, guest) => {
  202. guests.set(win.webContents.id, guest);
  203. native.attachGuest({ guest, hostWebContents: win.webContents, sandboxId: pending.shift()! });
  204. });
  205. await win.loadFile(join(root, "managed.html"));
  206. await win.webContents.executeJavaScript("window.harnessReady");
  207. if (mode !== "local" && mode !== "sampling") return win;
  208. await evaluateGuest(
  209. guests.get(win.webContents.id)!,
  210. scope.resourceUri ? "window.showcaseReady" : "window.fixtureReady",
  211. );
  212. await events.wait((e) => e.type === "subscribed" && e.owner === win.webContents.id);
  213. return win;
  214. }
  215. return {
  216. gates,
  217. model,
  218. agent,
  219. events,
  220. windows,
  221. scopes,
  222. handles,
  223. guests,
  224. native,
  225. wire,
  226. bridge,
  227. createWindow,
  228. evalPage: (win: BrowserWindow, code: string) =>
  229. evaluateGuest(guests.get(win.webContents.id)!, code),
  230. countGuests: () =>
  231. webContents.getAllWebContents().filter((c) => c.getType() === "webview").length,
  232. async close() {
  233. for (const win of windows) if (!win.isDestroyed()) win.destroy();
  234. await agent.close();
  235. await model.close();
  236. },
  237. };
  238. }