@fitchmultz/pi-mcp-adapter 5.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/OAUTH.md +3 -3
  3. package/README.md +160 -88
  4. package/dist/app-bridge.bundle.js +75 -33
  5. package/dist/commands.js +9 -6
  6. package/dist/config.js +41 -16
  7. package/dist/direct-tools.d.ts +2 -4
  8. package/dist/direct-tools.js +21 -319
  9. package/dist/gateway-arguments.d.ts +33 -0
  10. package/dist/gateway-arguments.js +63 -0
  11. package/dist/index.js +181 -276
  12. package/dist/init.js +6 -20
  13. package/dist/lifecycle.d.ts +2 -2
  14. package/dist/lifecycle.js +2 -2
  15. package/dist/mcp-auth-flow.js +2 -2
  16. package/dist/mcp-auth.d.ts +1 -1
  17. package/dist/mcp-auth.js +3 -3
  18. package/dist/mcp-code.d.ts +7 -6
  19. package/dist/mcp-code.js +98 -51
  20. package/dist/mcp-oauth-provider.d.ts +5 -5
  21. package/dist/mcp-oauth-provider.js +5 -5
  22. package/dist/mcp-output-guard.d.ts +57 -2
  23. package/dist/mcp-output-guard.js +129 -24
  24. package/dist/mcp-panel.d.ts +3 -3
  25. package/dist/mcp-panel.js +36 -99
  26. package/dist/mcp-script-worker.mjs +5 -2
  27. package/dist/mcp-setup-panel.d.ts +5 -4
  28. package/dist/mcp-setup-panel.js +15 -7
  29. package/dist/mcp-status.js +2 -1
  30. package/dist/mcp-trace.d.ts +1 -1
  31. package/dist/mcp-trace.js +1 -1
  32. package/dist/metadata-cache.d.ts +1 -1
  33. package/dist/metadata-cache.js +25 -88
  34. package/dist/npx-resolver.js +8 -4
  35. package/dist/prompts.d.ts +1 -1
  36. package/dist/prompts.js +1 -1
  37. package/dist/proxy-modes.d.ts +41 -7
  38. package/dist/proxy-modes.js +275 -490
  39. package/dist/resource-tools.d.ts +15 -0
  40. package/dist/resource-tools.js +26 -1
  41. package/dist/sampling-handler.js +5 -1
  42. package/dist/search-ranking.d.ts +0 -2
  43. package/dist/search-ranking.js +70 -137
  44. package/dist/server-manager.d.ts +2 -2
  45. package/dist/server-manager.js +44 -27
  46. package/dist/session-recovery.d.ts +7 -4
  47. package/dist/session-recovery.js +76 -10
  48. package/dist/state.d.ts +1 -1
  49. package/dist/tool-loader.d.ts +32 -0
  50. package/dist/tool-loader.js +152 -0
  51. package/dist/tool-metadata.d.ts +67 -0
  52. package/dist/tool-metadata.js +23 -17
  53. package/dist/tool-registrar.d.ts +4 -4
  54. package/dist/tool-registrar.js +18 -13
  55. package/dist/tool-result-renderer.d.ts +6 -3
  56. package/dist/tool-result-renderer.js +11 -6
  57. package/dist/types.d.ts +11 -36
  58. package/dist/ui-resource-handler.d.ts +2 -2
  59. package/dist/ui-resource-handler.js +2 -2
  60. package/dist/ui-server.js +4 -3
  61. package/dist/ui-stream-types.d.ts +8 -8
  62. package/dist/unix-socket-transport.d.ts +1 -1
  63. package/dist/unix-socket-transport.js +1 -1
  64. package/dist/utils.d.ts +1 -0
  65. package/dist/utils.js +16 -4
  66. package/package.json +37 -96
  67. package/skills/mcp-scripting/SKILL.md +67 -20
  68. package/abort.ts +0 -34
  69. package/agent-dir.ts +0 -24
  70. package/app-bridge.bundle.js +0 -67
  71. package/banner.png +0 -0
  72. package/checkpoint.ts +0 -55
  73. package/commands.ts +0 -619
  74. package/config.ts +0 -1204
  75. package/consent-manager.ts +0 -25
  76. package/direct-tools.ts +0 -408
  77. package/dist/ts-shape.d.ts +0 -2
  78. package/dist/ts-shape.js +0 -147
  79. package/elicitation-handler.ts +0 -349
  80. package/error-signal.ts +0 -21
  81. package/glimpse-ui.ts +0 -80
  82. package/host-html-template.ts +0 -456
  83. package/index.ts +0 -900
  84. package/init.ts +0 -627
  85. package/legacy-migration.ts +0 -47
  86. package/lifecycle.ts +0 -165
  87. package/logger.ts +0 -127
  88. package/mcp-auth-flow.ts +0 -975
  89. package/mcp-auth.ts +0 -793
  90. package/mcp-callback-server.ts +0 -450
  91. package/mcp-code.ts +0 -386
  92. package/mcp-keyring-helper.cjs +0 -89
  93. package/mcp-oauth-provider.ts +0 -774
  94. package/mcp-output-guard.ts +0 -412
  95. package/mcp-panel.ts +0 -978
  96. package/mcp-script-worker.mjs +0 -128
  97. package/mcp-setup-panel.ts +0 -666
  98. package/mcp-status.ts +0 -109
  99. package/mcp-trace.ts +0 -295
  100. package/metadata-cache.ts +0 -333
  101. package/npx-resolver.ts +0 -488
  102. package/onboarding-state.ts +0 -58
  103. package/panel-keys.ts +0 -37
  104. package/prompts.ts +0 -337
  105. package/proxy-modes.ts +0 -1361
  106. package/resource-tools.ts +0 -17
  107. package/runtime-owner.ts +0 -123
  108. package/sampling-handler.ts +0 -273
  109. package/scripts/build.mjs +0 -131
  110. package/scripts/prepare.mjs +0 -102
  111. package/search-ranking.ts +0 -196
  112. package/server-manager.ts +0 -1320
  113. package/session-recovery.ts +0 -316
  114. package/state.ts +0 -64
  115. package/tool-approval.ts +0 -78
  116. package/tool-metadata.ts +0 -235
  117. package/tool-registrar.ts +0 -69
  118. package/tool-result-renderer.ts +0 -286
  119. package/ts-shape.ts +0 -145
  120. package/tsconfig.build.json +0 -13
  121. package/tsconfig.json +0 -16
  122. package/types.ts +0 -810
  123. package/ui-resource-handler.ts +0 -249
  124. package/ui-server.ts +0 -808
  125. package/ui-session.ts +0 -568
  126. package/ui-stream-types.ts +0 -89
  127. package/ui-tool-visibility.ts +0 -25
  128. package/unix-socket-transport.ts +0 -85
  129. package/utils.ts +0 -309
@@ -1,349 +0,0 @@
1
- import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
2
- import type { Client } from "@modelcontextprotocol/client";
3
- import {
4
- ProtocolErrorCode,
5
- ProtocolError,
6
- type ElicitRequest,
7
- type ElicitRequestFormParams,
8
- type ElicitRequestURLParams,
9
- type ElicitResult,
10
- } from "@modelcontextprotocol/client";
11
- import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
12
- import type { JsonSchemaType } from "@modelcontextprotocol/client";
13
- import open from "open";
14
-
15
- export type ElicitationValue = string | number | boolean | string[] | undefined;
16
- type FormProperty = ElicitRequestFormParams["requestedSchema"]["properties"][string];
17
-
18
- export type ElicitationUIContext = ExtensionUIContext;
19
-
20
- export interface ElicitationHandlerOptions {
21
- serverName: string;
22
- ui: ElicitationUIContext;
23
- allowUrl: boolean;
24
- onUrlAccepted?: (elicitationId: string) => void;
25
- }
26
-
27
- export type ServerElicitationConfig = Omit<ElicitationHandlerOptions, "serverName" | "onUrlAccepted">;
28
-
29
- export function registerElicitationHandler(
30
- client: Client,
31
- options: ElicitationHandlerOptions,
32
- own: (run: () => Promise<ElicitResult>) => Promise<ElicitResult> = run => run(),
33
- ): void {
34
- client.setRequestHandler("elicitation/create", request => own(() => handleElicitationRequest(options, request)));
35
- }
36
-
37
- export async function handleElicitationRequest(
38
- options: ElicitationHandlerOptions,
39
- request: ElicitRequest,
40
- ): Promise<ElicitResult> {
41
- return request.params.mode === "url"
42
- ? handleUrlElicitation(options, request.params)
43
- : handleFormElicitation(options, request.params);
44
- }
45
-
46
- export async function handleFormElicitation(
47
- options: ElicitationHandlerOptions,
48
- params: ElicitRequestFormParams,
49
- ): Promise<ElicitResult> {
50
- const decision = await options.ui.select(
51
- `MCP Input Request\nServer: ${options.serverName}\n\n${params.message}`,
52
- ["Continue", "Decline"],
53
- );
54
- if (decision === undefined) return { action: "cancel" };
55
- if (decision === "Decline") return { action: "decline" };
56
-
57
- const values: Record<string, ElicitationValue> = {};
58
- const properties = Object.entries(params.requestedSchema.properties);
59
- for (const [name, schema] of properties) {
60
- const value = await collectValidField(options.ui, params, name, schema);
61
- if (!("value" in value)) return { action: "cancel" };
62
- values[name] = value.value;
63
- }
64
-
65
- while (true) {
66
- const content = coerceAndValidateFormValues(params, values);
67
- const action = await options.ui.select(
68
- formatReview(options.serverName, properties, content),
69
- properties.length > 0 ? ["Submit", "Edit", "Decline"] : ["Submit", "Decline"],
70
- );
71
- if (action === undefined) return { action: "cancel" };
72
- if (action === "Decline") return { action: "decline" };
73
- if (action === "Submit") return { action: "accept", content };
74
-
75
- const labels = properties.map(([name, schema]) => `${schema.title ?? humanizeName(name)} (${name})`);
76
- const selected = await options.ui.select("Choose a field to edit", labels);
77
- if (selected === undefined) return { action: "cancel" };
78
- const property = properties[labels.indexOf(selected)];
79
- if (!property) continue;
80
- const [name, schema] = property;
81
- const value = await collectValidField(options.ui, params, name, schema, values[name]);
82
- if (!("value" in value)) return { action: "cancel" };
83
- values[name] = value.value;
84
- }
85
- }
86
-
87
- async function collectValidField(
88
- ui: ElicitationUIContext,
89
- params: ElicitRequestFormParams,
90
- name: string,
91
- schema: FormProperty,
92
- current?: ElicitationValue,
93
- ): Promise<{ cancelled: true } | { cancelled: false; value: ElicitationValue }> {
94
- const required = params.requestedSchema.required?.includes(name) === true;
95
- while (true) {
96
- const result = await collectField(ui, params, name, schema, current);
97
- if (!("value" in result)) return result;
98
- try {
99
- coerceAndValidateFormValues({
100
- ...params,
101
- requestedSchema: {
102
- type: "object",
103
- properties: { [name]: schema },
104
- ...(required ? { required: [name] } : {}),
105
- },
106
- }, { [name]: result.value });
107
- return result;
108
- } catch (error) {
109
- ui.notify(error instanceof Error ? error.message : String(error), "error");
110
- current = result.value;
111
- }
112
- }
113
- }
114
-
115
- async function collectField(
116
- ui: ElicitationUIContext,
117
- params: ElicitRequestFormParams,
118
- name: string,
119
- schema: FormProperty,
120
- current?: ElicitationValue,
121
- ): Promise<{ cancelled: true } | { cancelled: false; value: ElicitationValue }> {
122
- const required = params.requestedSchema.required?.includes(name) === true;
123
- const title = [schema.title ?? humanizeName(name), required ? "(required)" : "", schema.description]
124
- .filter(Boolean)
125
- .join(" ");
126
-
127
- if (schema.type === "string" && ("enum" in schema || "oneOf" in schema)) {
128
- const choices = "oneOf" in schema
129
- ? schema.oneOf.map(option => ({ value: option.const, display: formatChoice(option.const, option.title) }))
130
- : schema.enum.map((value, index) => ({
131
- value,
132
- display: formatChoice(value, "enumNames" in schema ? schema.enumNames?.[index] : undefined),
133
- }));
134
- const displays = uniqueLabels(choices.map(choice => choice.display));
135
- const actions = [...displays];
136
- const useDefault = schema.default === undefined ? undefined : uniqueAction("Use default", actions);
137
- if (useDefault) actions.push(useDefault);
138
- const omit = required ? undefined : uniqueAction("Omit", actions);
139
- if (omit) actions.push(omit);
140
- const action = await ui.select(title, actions);
141
- if (action === undefined) return { cancelled: true };
142
- if (action === useDefault) return { cancelled: false, value: schema.default };
143
- if (action === omit) return { cancelled: false, value: undefined };
144
- return { cancelled: false, value: choices[displays.indexOf(action)]?.value };
145
- }
146
-
147
- if (schema.type === "boolean") {
148
- const actions = ["Yes", "No"];
149
- if (schema.default !== undefined) actions.push("Use default");
150
- if (!required) actions.push("Omit");
151
- const action = await ui.select(title, actions);
152
- if (action === undefined) return { cancelled: true };
153
- if (action === "Use default") return { cancelled: false, value: schema.default };
154
- if (action === "Omit") return { cancelled: false, value: undefined };
155
- return { cancelled: false, value: action === "Yes" };
156
- }
157
-
158
- if (schema.type === "array") {
159
- const actions = ["Choose values"];
160
- if (schema.default !== undefined) actions.push("Use default");
161
- if (!required) actions.push("Omit");
162
- const action = await ui.select(title, actions);
163
- if (action === undefined) return { cancelled: true };
164
- if (action === "Use default") return { cancelled: false, value: schema.default };
165
- if (action === "Omit") return { cancelled: false, value: undefined };
166
-
167
- const choices = extractMultiSelectOptions(schema);
168
- const selected = new Set(Array.isArray(current) ? current : []);
169
- while (true) {
170
- const displays = uniqueLabels(choices.map(choice => selected.has(choice.value) ? `✓ ${choice.display}` : choice.display));
171
- const done = uniqueAction("Done", displays);
172
- const picked = await ui.select(title, [...displays, done]);
173
- if (picked === undefined) return { cancelled: true };
174
- if (picked === done) return { cancelled: false, value: [...selected] };
175
- const choice = choices[displays.indexOf(picked)];
176
- if (!choice) continue;
177
- if (selected.has(choice.value)) selected.delete(choice.value);
178
- else selected.add(choice.value);
179
- }
180
- }
181
-
182
- const actions = ["Enter value"];
183
- if (schema.default !== undefined) actions.push("Use default");
184
- if (!required) actions.push("Omit");
185
- const action = await ui.select(title, actions);
186
- if (action === undefined) return { cancelled: true };
187
- if (action === "Use default") return { cancelled: false, value: schema.default };
188
- if (action === "Omit") return { cancelled: false, value: undefined };
189
- const entered = await ui.input(title, current === undefined ? undefined : String(current));
190
- return entered === undefined ? { cancelled: true } : { cancelled: false, value: entered };
191
- }
192
-
193
- export function coerceAndValidateFormValues(
194
- params: ElicitRequestFormParams,
195
- values: Record<string, ElicitationValue>,
196
- ): Record<string, string | number | boolean | string[]> {
197
- const output: Record<string, string | number | boolean | string[]> = {};
198
- const required = new Set(params.requestedSchema.required ?? []);
199
- for (const [name, schema] of Object.entries(params.requestedSchema.properties)) {
200
- const value = values[name];
201
- if (value === undefined) {
202
- if (required.has(name)) throw new Error(`Missing required elicitation field: ${name}`);
203
- continue;
204
- }
205
- if (schema.type === "string") {
206
- const stringValue = String(value);
207
- const limits = schema as typeof schema & { minLength?: number; maxLength?: number };
208
- if (limits.minLength !== undefined && stringValue.length < limits.minLength) {
209
- throw new Error(`Elicitation field ${name} is shorter than minimum length ${limits.minLength}`);
210
- }
211
- if (limits.maxLength !== undefined && stringValue.length > limits.maxLength) {
212
- throw new Error(`Elicitation field ${name} is longer than maximum length ${limits.maxLength}`);
213
- }
214
- if ("enum" in schema && !schema.enum.includes(stringValue)) {
215
- throw new Error(`Elicitation field ${name} is not an allowed value`);
216
- }
217
- if ("oneOf" in schema && !schema.oneOf.some(option => option.const === stringValue)) {
218
- throw new Error(`Elicitation field ${name} is not an allowed value`);
219
- }
220
- output[name] = stringValue;
221
- continue;
222
- }
223
- if (schema.type === "number" || schema.type === "integer") {
224
- if (typeof value === "string" && value.trim() === "") {
225
- throw new Error(`Elicitation field ${name} must be a number`);
226
- }
227
- const numberValue = typeof value === "number" ? value : Number(value);
228
- if (!Number.isFinite(numberValue)) throw new Error(`Elicitation field ${name} must be a number`);
229
- if (schema.type === "integer" && !Number.isInteger(numberValue)) {
230
- throw new Error(`Elicitation field ${name} must be an integer`);
231
- }
232
- if (schema.minimum !== undefined && numberValue < schema.minimum) {
233
- throw new Error(`Elicitation field ${name} is below minimum ${schema.minimum}`);
234
- }
235
- if (schema.maximum !== undefined && numberValue > schema.maximum) {
236
- throw new Error(`Elicitation field ${name} is above maximum ${schema.maximum}`);
237
- }
238
- output[name] = numberValue;
239
- continue;
240
- }
241
- if (schema.type === "boolean") {
242
- output[name] = typeof value === "boolean" ? value : value === "true";
243
- continue;
244
- }
245
- if (schema.type === "array") {
246
- if (!Array.isArray(value)) throw new Error(`Elicitation field ${name} must be a list`);
247
- const allowed = new Set(extractMultiSelectOptions(schema).map(option => option.value));
248
- const arrayValue = value.map(String);
249
- if (schema.minItems !== undefined && arrayValue.length < schema.minItems) {
250
- throw new Error(`Elicitation field ${name} has fewer than ${schema.minItems} selections`);
251
- }
252
- if (schema.maxItems !== undefined && arrayValue.length > schema.maxItems) {
253
- throw new Error(`Elicitation field ${name} has more than ${schema.maxItems} selections`);
254
- }
255
- if (arrayValue.some(item => !allowed.has(item))) {
256
- throw new Error(`Elicitation field ${name} contains an invalid selection`);
257
- }
258
- output[name] = arrayValue;
259
- }
260
- }
261
- const validation = new AjvJsonSchemaValidator()
262
- .getValidator(params.requestedSchema as JsonSchemaType)(output);
263
- if (!validation.valid) {
264
- throw new Error(`Invalid elicitation response: ${validation.errorMessage}`);
265
- }
266
- return output;
267
- }
268
-
269
- function formatChoice(value: string, title?: string): string {
270
- return title && title !== value ? `${title} (${value})` : value;
271
- }
272
-
273
- function uniqueLabels(labels: string[]): string[] {
274
- const used = new Set<string>();
275
- return labels.map(label => {
276
- let unique = label;
277
- while (used.has(unique)) unique += "…";
278
- used.add(unique);
279
- return unique;
280
- });
281
- }
282
-
283
- function uniqueAction(label: string, choices: string[]): string {
284
- let unique = label;
285
- while (choices.includes(unique)) unique += "…";
286
- return unique;
287
- }
288
-
289
- function extractMultiSelectOptions(schema: Extract<FormProperty, { type: "array" }>): Array<{ value: string; display: string }> {
290
- const items = schema.items as { enum?: string[]; anyOf?: Array<{ const: string; title: string }> };
291
- return items.anyOf
292
- ? items.anyOf.map(option => ({ value: option.const, display: formatChoice(option.const, option.title) }))
293
- : (items.enum ?? []).map(value => ({ value, display: value }));
294
- }
295
-
296
- function formatReview(
297
- serverName: string,
298
- properties: Array<[string, FormProperty]>,
299
- content: Record<string, string | number | boolean | string[]>,
300
- ): string {
301
- const rows = properties.map(([name, schema]) =>
302
- `${schema.title ?? humanizeName(name)}: ${content[name] === undefined ? "(omitted)" : String(content[name])}`);
303
- return [`Review input for ${serverName}`, "", ...rows].join("\n");
304
- }
305
-
306
- export async function handleUrlElicitation(
307
- options: ElicitationHandlerOptions,
308
- params: ElicitRequestURLParams,
309
- ): Promise<ElicitResult> {
310
- if (!options.allowUrl) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "URL elicitation is not supported");
311
-
312
- let parsed: URL;
313
- try {
314
- parsed = new URL(params.url);
315
- } catch {
316
- throw new ProtocolError(ProtocolErrorCode.InvalidParams, "URL elicitation supplied an invalid URL");
317
- }
318
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
319
- throw new ProtocolError(ProtocolErrorCode.InvalidParams, "URL elicitation only supports HTTP and HTTPS URLs");
320
- }
321
-
322
- const decision = await options.ui.select([
323
- "MCP Browser Request",
324
- `Server: ${options.serverName}`,
325
- "",
326
- params.message,
327
- "",
328
- `Host: ${parsed.host}`,
329
- `Full URL: ${params.url}`,
330
- "",
331
- "Open this URL in your browser?",
332
- ].join("\n"), ["Open", "Decline"]);
333
- if (decision === undefined) return { action: "cancel" };
334
- if (decision === "Decline") return { action: "decline" };
335
-
336
- try {
337
- await open(params.url);
338
- } catch (error) {
339
- options.ui.notify(`Could not open MCP elicitation URL: ${error instanceof Error ? error.message : String(error)}`, "error");
340
- return { action: "cancel" };
341
- }
342
- options.onUrlAccepted?.(params.elicitationId);
343
- options.ui.notify("Opened browser for MCP elicitation.", "info");
344
- return { action: "accept" };
345
- }
346
-
347
- function humanizeName(name: string): string {
348
- return name.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^./, char => char.toUpperCase());
349
- }
package/error-signal.ts DELETED
@@ -1,21 +0,0 @@
1
- /**
2
- * Decide the `isError` override for a finished tool result in the `tool_result` hook.
3
- *
4
- * A failed MCP tool call is *returned* (not thrown), tagged `details.error: "tool_error"` (the server
5
- * returned an error result) or `"call_failed"` (the call itself threw and was caught). pi never reads a
6
- * result-level `isError`, so without this such a call is recorded as a success. Returning
7
- * `{ isError: true }` (and nothing else) flips the flag; pi's field-by-field merge keeps the original
8
- * `content` and `details` intact.
9
- *
10
- * Limited to those two codes: the adapter's other `details.error` values (`auth_required`, connection
11
- * states, search/validation feedback, ...) are not failed tool calls, so they get no override.
12
- */
13
- export function toolErrorOverride(details: unknown): { isError: true } | undefined {
14
- if (details && typeof details === "object" && "error" in details) {
15
- const code = (details as { error?: unknown }).error;
16
- if (code === "tool_error" || code === "call_failed") {
17
- return { isError: true };
18
- }
19
- }
20
- return undefined;
21
- }
package/glimpse-ui.ts DELETED
@@ -1,80 +0,0 @@
1
- import { existsSync } from "node:fs";
2
- import { execFileSync } from "node:child_process";
3
- import { join, dirname } from "node:path";
4
- import { platform } from "node:os";
5
- import { createRequire } from "node:module";
6
-
7
- let glimpseAvailable: boolean | null = null;
8
- let resolvedBinaryPath: string | null = null;
9
-
10
- export function isGlimpseAvailable(): boolean {
11
- if (glimpseAvailable !== null) return glimpseAvailable;
12
-
13
- if (platform() !== "darwin") {
14
- glimpseAvailable = false;
15
- return false;
16
- }
17
-
18
- resolvedBinaryPath = getGlimpseBinaryPath();
19
- glimpseAvailable = resolvedBinaryPath !== null;
20
- return glimpseAvailable;
21
- }
22
-
23
- function getGlimpseBinaryPath(): string | null {
24
- if (process.env.GLIMPSE_BINARY && existsSync(process.env.GLIMPSE_BINARY)) {
25
- return process.env.GLIMPSE_BINARY;
26
- }
27
-
28
- // Local node_modules
29
- try {
30
- const require = createRequire(import.meta.url);
31
- const glimpseuiPath = require.resolve("glimpseui");
32
- const binaryPath = join(dirname(glimpseuiPath), "glimpse");
33
- if (existsSync(binaryPath)) return binaryPath;
34
- } catch {}
35
-
36
- // Global npm install
37
- try {
38
- const globalRoot = execFileSync("npm", ["root", "-g"], { encoding: "utf-8" }).trim();
39
- const binaryPath = join(globalRoot, "glimpseui", "src", "glimpse");
40
- if (existsSync(binaryPath)) return binaryPath;
41
- } catch {}
42
-
43
- return null;
44
- }
45
-
46
- export async function openGlimpseWindow(
47
- html: string,
48
- options: {
49
- title: string;
50
- width?: number;
51
- height?: number;
52
- onClosed: () => void;
53
- },
54
- ) {
55
- const modulePath = resolvedBinaryPath
56
- ? join(dirname(resolvedBinaryPath), "glimpse.mjs")
57
- : "glimpseui";
58
- const glimpse = await import(modulePath);
59
-
60
- let active = true;
61
- const win = glimpse.open(html, {
62
- width: options.width ?? 900,
63
- height: options.height ?? 700,
64
- title: options.title,
65
- });
66
-
67
- win.on("closed", () => {
68
- if (!active) return;
69
- active = false;
70
- options.onClosed();
71
- });
72
-
73
- return {
74
- close: () => {
75
- if (!active) return;
76
- active = false;
77
- win.close();
78
- },
79
- };
80
- }