@agimon-ai/po-web-components 0.0.0-alpha.122 → 0.0.0-alpha.124
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/mcpAppHost.cjs +1 -0
- package/dist/mcpAppHost.d.mts +4 -0
- package/dist/mcpAppHost.mjs +1 -0
- package/dist/packages/core/po-core/dist/src/schemas/workflow.d.mts +135 -4
- package/dist/packages/core/po-core/dist/src/schemas/workflow.d.mts.map +1 -1
- package/dist/packages/core/po-core/dist/src/web/types/webPlugin.d.mts +5 -0
- package/dist/packages/core/po-core/dist/src/web/types/webPlugin.d.mts.map +1 -1
- package/dist/packages/core/po-web-components/src/lib/mcpAppFrame.d.mts +47 -0
- package/dist/packages/core/po-web-components/src/lib/mcpAppFrame.d.mts.map +1 -0
- package/dist/packages/core/po-web-components/src/lib/mcpAppFrame.mjs +3 -0
- package/dist/packages/core/po-web-components/src/lib/mcpAppFrame.mjs.map +1 -0
- package/dist/packages/core/po-web-components/src/lib/mcpAppSandbox.d.mts +19 -0
- package/dist/packages/core/po-web-components/src/lib/mcpAppSandbox.d.mts.map +1 -0
- package/dist/packages/core/po-web-components/src/lib/mcpAppSandbox.mjs +2 -0
- package/dist/packages/core/po-web-components/src/lib/mcpAppSandbox.mjs.map +1 -0
- package/dist/packages/core/po-web-components/src/lib/mcpOpenAiBootstrap.d.mts +32 -0
- package/dist/packages/core/po-web-components/src/lib/mcpOpenAiBootstrap.d.mts.map +1 -0
- package/dist/packages/core/po-web-components/src/lib/mcpOpenAiBootstrap.mjs +2 -0
- package/dist/packages/core/po-web-components/src/lib/mcpOpenAiBootstrap.mjs.map +1 -0
- package/dist/src/lib/mcpAppFrame.cjs +3 -0
- package/dist/src/lib/mcpAppFrame.cjs.map +1 -0
- package/dist/src/lib/mcpAppSandbox.cjs +2 -0
- package/dist/src/lib/mcpAppSandbox.cjs.map +1 -0
- package/dist/src/lib/mcpOpenAiBootstrap.cjs +2 -0
- package/dist/src/lib/mcpOpenAiBootstrap.cjs.map +1 -0
- package/package.json +8 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./src/lib/mcpAppSandbox.cjs"),t=require("./src/lib/mcpOpenAiBootstrap.cjs"),n=require("./src/lib/mcpAppFrame.cjs");exports.connectMcpAppFrame=n.connectMcpAppFrame,exports.mcpAppCsp=e.mcpAppCsp,exports.mcpAppDocument=e.mcpAppDocument,exports.mcpAppHostTheme=e.mcpAppHostTheme,exports.mcpAppRelayHtml=e.mcpAppRelayHtml,exports.mcpOpenAiScript=t.mcpOpenAiScript,exports.supportsMcpAppSandbox=e.supportsMcpAppSandbox,exports.widgetThemeBootstrap=e.widgetThemeBootstrap;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { McpAppFrameOptions, connectMcpAppFrame } from "./packages/core/po-web-components/src/lib/mcpAppFrame.mjs";
|
|
2
|
+
import { mcpAppCsp, mcpAppDocument, mcpAppHostTheme, mcpAppRelayHtml, supportsMcpAppSandbox, widgetThemeBootstrap } from "./packages/core/po-web-components/src/lib/mcpAppSandbox.mjs";
|
|
3
|
+
import { mcpOpenAiScript } from "./packages/core/po-web-components/src/lib/mcpOpenAiBootstrap.mjs";
|
|
4
|
+
export { type McpAppFrameOptions, connectMcpAppFrame, mcpAppCsp, mcpAppDocument, mcpAppHostTheme, mcpAppRelayHtml, mcpOpenAiScript, supportsMcpAppSandbox, widgetThemeBootstrap };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mcpAppCsp as e,mcpAppDocument as t,mcpAppHostTheme as n,mcpAppRelayHtml as r,supportsMcpAppSandbox as i,widgetThemeBootstrap as a}from"./packages/core/po-web-components/src/lib/mcpAppSandbox.mjs";import{mcpOpenAiScript as o}from"./packages/core/po-web-components/src/lib/mcpOpenAiBootstrap.mjs";import{connectMcpAppFrame as s}from"./packages/core/po-web-components/src/lib/mcpAppFrame.mjs";export{s as connectMcpAppFrame,e as mcpAppCsp,t as mcpAppDocument,n as mcpAppHostTheme,r as mcpAppRelayHtml,o as mcpOpenAiScript,i as supportsMcpAppSandbox,a as widgetThemeBootstrap};
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import "../../../../../../node_modules/.pnpm/@deepseek-ai_cordis@4.0.5/node_modules/@deepseek-ai/cordis/lib/types/index.mjs";
|
|
2
|
+
import { TArray } from "../../../../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/array.mjs";
|
|
3
|
+
import { TBoolean } from "../../../../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/boolean.mjs";
|
|
2
4
|
import { TObject } from "../../../../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/object.mjs";
|
|
5
|
+
import { TLiteral } from "../../../../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/literal.mjs";
|
|
3
6
|
import { TString } from "../../../../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/string.mjs";
|
|
7
|
+
import { TUnion } from "../../../../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/union.mjs";
|
|
8
|
+
import { TRecord } from "../../../../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/record.mjs";
|
|
4
9
|
import { Static } from "../../../../../../node_modules/.pnpm/typebox@1.4.2/node_modules/typebox/build/type/types/static.mjs";
|
|
5
10
|
import { PoHubSessionUsage } from "./hubChannel.mjs";
|
|
6
11
|
//#region ../po-core/dist/src/schemas/workflow.d.mts
|
|
@@ -18,6 +23,106 @@ export declare const PoWorkflowRunRefSchema: TObject<{
|
|
|
18
23
|
registryWorkspace: TString;
|
|
19
24
|
}>;
|
|
20
25
|
export type PoWorkflowRunRef = Static<typeof PoWorkflowRunRefSchema>;
|
|
26
|
+
/** Derived from the effective graph. revision identifies the parsed definition, never a mutable path alone. */
|
|
27
|
+
export declare const PoWorkflowIdentityRequirementsSchema: TObject<{
|
|
28
|
+
definition: TObject<{
|
|
29
|
+
source: TString;
|
|
30
|
+
key: TString;
|
|
31
|
+
}>;
|
|
32
|
+
revision: TString;
|
|
33
|
+
roles: TArray<TString>;
|
|
34
|
+
groups: TArray<TObject<{
|
|
35
|
+
kind: TUnion<[TLiteral<"job">, TLiteral<"child">, TLiteral<"repair">]>;
|
|
36
|
+
job: TString;
|
|
37
|
+
roles: TArray<TString>;
|
|
38
|
+
}>>;
|
|
39
|
+
}>;
|
|
40
|
+
export type PoWorkflowIdentityRequirements = Static<typeof PoWorkflowIdentityRequirementsSchema>;
|
|
41
|
+
export declare const PoWorkflowAssignmentsSchema: TRecord<"^.*$", TString>;
|
|
42
|
+
export type PoWorkflowAssignments = Static<typeof PoWorkflowAssignmentsSchema>;
|
|
43
|
+
export declare const PoWorkflowIdentityDiscoverySchema: TObject<{
|
|
44
|
+
scope: TObject<{
|
|
45
|
+
workspaceId: TString;
|
|
46
|
+
product: TString;
|
|
47
|
+
revision: TString;
|
|
48
|
+
}>;
|
|
49
|
+
candidates: TArray<TObject<{
|
|
50
|
+
ref: TString;
|
|
51
|
+
label: TString;
|
|
52
|
+
roles: TArray<TString>;
|
|
53
|
+
voiceConfigured: TBoolean;
|
|
54
|
+
}>>;
|
|
55
|
+
}>;
|
|
56
|
+
export type PoWorkflowIdentityDiscovery = Static<typeof PoWorkflowIdentityDiscoverySchema>;
|
|
57
|
+
/** Persisted before effects. Profiles contain exact admitted evidence, never secrets or an implicit team selection. */
|
|
58
|
+
export declare const PoWorkflowAllocationSchema: TObject<{
|
|
59
|
+
version: TLiteral<1>;
|
|
60
|
+
requirements: TObject<{
|
|
61
|
+
definition: TObject<{
|
|
62
|
+
source: TString;
|
|
63
|
+
key: TString;
|
|
64
|
+
}>;
|
|
65
|
+
revision: TString;
|
|
66
|
+
roles: TArray<TString>;
|
|
67
|
+
groups: TArray<TObject<{
|
|
68
|
+
kind: TUnion<[TLiteral<"job">, TLiteral<"child">, TLiteral<"repair">]>;
|
|
69
|
+
job: TString;
|
|
70
|
+
roles: TArray<TString>;
|
|
71
|
+
}>>;
|
|
72
|
+
}>;
|
|
73
|
+
scope: TObject<{
|
|
74
|
+
workspaceId: TString;
|
|
75
|
+
product: TString;
|
|
76
|
+
revision: TString;
|
|
77
|
+
}>;
|
|
78
|
+
assignments: TRecord<"^.*$", TString>;
|
|
79
|
+
profiles: TArray<TObject<{
|
|
80
|
+
ref: TString;
|
|
81
|
+
profile: TString;
|
|
82
|
+
contentDigest: TString;
|
|
83
|
+
policyDigest: TString;
|
|
84
|
+
provider: TObject<{
|
|
85
|
+
provider: TString;
|
|
86
|
+
organizationId: TString;
|
|
87
|
+
mailboxId: TString;
|
|
88
|
+
credentialRef: TString;
|
|
89
|
+
}>;
|
|
90
|
+
}>>;
|
|
91
|
+
}>;
|
|
92
|
+
export type PoWorkflowAllocation = Static<typeof PoWorkflowAllocationSchema>;
|
|
93
|
+
/** Step bootstrap only. An allocation-owned role-less session explicitly has no profile. */
|
|
94
|
+
export declare const PoWorkflowExpectedIdentitySchema: TUnion<[TObject<{
|
|
95
|
+
kind: TLiteral<"none">;
|
|
96
|
+
}>, TObject<{
|
|
97
|
+
ref: TString;
|
|
98
|
+
profile: TString;
|
|
99
|
+
contentDigest: TString;
|
|
100
|
+
policyDigest: TString;
|
|
101
|
+
provider: TObject<{
|
|
102
|
+
provider: TString;
|
|
103
|
+
organizationId: TString;
|
|
104
|
+
mailboxId: TString;
|
|
105
|
+
credentialRef: TString;
|
|
106
|
+
}>;
|
|
107
|
+
kind: TLiteral<"profile">;
|
|
108
|
+
scope: TObject<{
|
|
109
|
+
workspaceId: TString;
|
|
110
|
+
product: TString;
|
|
111
|
+
revision: TString;
|
|
112
|
+
}>;
|
|
113
|
+
definitionRevision: TString;
|
|
114
|
+
roles: TArray<TString>;
|
|
115
|
+
}>]>;
|
|
116
|
+
export type PoWorkflowExpectedIdentity = Static<typeof PoWorkflowExpectedIdentitySchema>;
|
|
117
|
+
/** Read-only effective-graph requirements and provider discovery. identity is absent only for role-less graphs. */
|
|
118
|
+
export interface PoWorkflowRequirementsReport {
|
|
119
|
+
readonly requirements: PoWorkflowIdentityRequirements;
|
|
120
|
+
readonly identity?: PoWorkflowIdentityDiscovery;
|
|
121
|
+
}
|
|
122
|
+
export interface PoWorkflowAllocationRequest {
|
|
123
|
+
readonly requirements: PoWorkflowIdentityRequirements;
|
|
124
|
+
readonly assignments: Readonly<PoWorkflowAssignments>;
|
|
125
|
+
}
|
|
21
126
|
export interface PoWorkflowLaunchOverrides {
|
|
22
127
|
readonly runner?: string;
|
|
23
128
|
readonly command?: string;
|
|
@@ -27,7 +132,11 @@ export interface PoWorkflowLaunchOverrides {
|
|
|
27
132
|
readonly env?: Readonly<Record<string, string>>;
|
|
28
133
|
readonly prompt?: string;
|
|
29
134
|
readonly name?: string;
|
|
30
|
-
/**
|
|
135
|
+
/** Name for a newly created workflow session, not the run or an existing owner session. */
|
|
136
|
+
readonly sessionName?: string;
|
|
137
|
+
/** Exact per-launch role assignments. Teams, defaults and local profile names cannot fill missing assignments. */
|
|
138
|
+
readonly assignments?: Readonly<PoWorkflowAssignments>;
|
|
139
|
+
/** Legacy team override only. Never a substitute for explicit allocation. */
|
|
31
140
|
readonly team?: string;
|
|
32
141
|
}
|
|
33
142
|
/** Session-owned. Rejection means no observable registration was accepted. */
|
|
@@ -90,6 +199,8 @@ export interface PoWorkflowPolicyOptions {
|
|
|
90
199
|
}
|
|
91
200
|
export interface PoWorkflowAdmissionOverrides extends PoWorkflowLaunchOverrides {
|
|
92
201
|
readonly policy?: PoWorkflowPolicyAssociation;
|
|
202
|
+
/** Frozen preparation evidence. The destination revalidates it exactly, never treats it as authorization. */
|
|
203
|
+
readonly allocation?: PoWorkflowAllocation;
|
|
93
204
|
/**
|
|
94
205
|
* Run the workflow as this same-workspace session instead of the caller, for example a session in an
|
|
95
206
|
* isolated checkout. Trusted in-process launchers only: never accepted from tools, code mode or HTTP.
|
|
@@ -126,6 +237,8 @@ export interface PoWorkflowValidationReport {
|
|
|
126
237
|
}[];
|
|
127
238
|
/** Declared by the definition and reported only: the engine never provisions a checkout itself. */
|
|
128
239
|
readonly isolation?: 'checkout';
|
|
240
|
+
/** Trusted preparation evidence only. Ordinary namespace reports omit provider bindings. */
|
|
241
|
+
readonly allocation?: PoWorkflowAllocation;
|
|
129
242
|
}
|
|
130
243
|
export type PoWorkflowAdmission = {
|
|
131
244
|
readonly attemptId: string;
|
|
@@ -146,6 +259,8 @@ export type PoWorkflowAdmission = {
|
|
|
146
259
|
};
|
|
147
260
|
/** Trusted, session-bound opt-in capability, never exposed as a tool or code-mode namespace. */
|
|
148
261
|
export interface PoWorkflowAdmissionsService {
|
|
262
|
+
/** Discovery precedes assignment and creates no admission journal, claims or workflow effects. */
|
|
263
|
+
requirements?(definition: PoWorkflowDefinitionRef, options?: Pick<PoWorkflowLaunchOverrides, 'job'>): Promise<PoWorkflowRequirementsReport>;
|
|
149
264
|
validate(request: PoWorkflowAdmissionRequest): Promise<PoWorkflowValidationReport>;
|
|
150
265
|
launch(attemptId: string, definition: PoWorkflowDefinitionRef, overrides?: PoWorkflowAdmissionOverrides): Promise<PoWorkflowAdmission>;
|
|
151
266
|
recover(attemptId: string, previousRun: PoWorkflowRunRef, options?: PoWorkflowRecoveryOptions): Promise<PoWorkflowAdmission>;
|
|
@@ -287,6 +402,10 @@ export interface PoWorkflowContextService {
|
|
|
287
402
|
readonly instructions?: string;
|
|
288
403
|
readonly state: PoWorkflowRunsService;
|
|
289
404
|
readonly children?: PoWorkflowChildrenSession;
|
|
405
|
+
/** Trusted startup evidence, not a remote session-create field. */
|
|
406
|
+
readonly identity?: PoWorkflowExpectedIdentity;
|
|
407
|
+
/** Frozen run evidence for trusted child admission. Never read from environment or public config views. */
|
|
408
|
+
readonly allocation?: PoWorkflowAllocation;
|
|
290
409
|
}
|
|
291
410
|
export interface PoWorkflowIdentityRequest {
|
|
292
411
|
readonly team: string;
|
|
@@ -306,15 +425,26 @@ export interface PoWorkflowIdentityBinding {
|
|
|
306
425
|
readonly policyDigest: string;
|
|
307
426
|
}
|
|
308
427
|
/**
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
428
|
+
* Workspace-bound identity capability. New role-bound launches require the allocation methods;
|
|
429
|
+
* an older provider missing them must fail closed rather than falling back to legacy teams.
|
|
430
|
+
* Fresh admission narrows existing authorization and never grants credentials or changes the caller's profile.
|
|
312
431
|
*/
|
|
313
432
|
export interface PoWorkflowIdentityService {
|
|
433
|
+
/** Ordinary read-only discovery, available without Help or a selected profile. */
|
|
434
|
+
discover?(requirements: PoWorkflowIdentityRequirements): Promise<PoWorkflowIdentityDiscovery>;
|
|
435
|
+
/** Refreshes eligibility and admits exactly the requested references in the provider's trusted product scope. */
|
|
436
|
+
allocate?(request: PoWorkflowAllocationRequest): Promise<PoWorkflowAllocation>;
|
|
437
|
+
/** Revalidates exact persisted evidence; any change blocks instead of substituting profiles or digests. */
|
|
438
|
+
revalidateAllocation?(allocation: PoWorkflowAllocation): Promise<PoWorkflowAllocation>;
|
|
439
|
+
/** Legacy team-based admission, not used by allocation-aware launches. */
|
|
314
440
|
resolve(request: PoWorkflowIdentityRequest): Promise<PoWorkflowIdentityBinding>;
|
|
315
441
|
/** Rechecks a saved binding against the current team and authorization, returning it as it stands now. */
|
|
316
442
|
revalidate(binding: PoWorkflowIdentityBinding): Promise<PoWorkflowIdentityBinding>;
|
|
317
443
|
}
|
|
444
|
+
/** Required profile-version admission for allocation-owned prompts. Only the profile package supplies it. */
|
|
445
|
+
export interface PoWorkflowProfileAdmissionService {
|
|
446
|
+
assertReady(expected: PoWorkflowExpectedIdentity): Promise<void>;
|
|
447
|
+
}
|
|
318
448
|
declare module '@deepseek-ai/cordis' {
|
|
319
449
|
interface Context {
|
|
320
450
|
'po/workflow-launch': PoWorkflowLaunchService;
|
|
@@ -323,6 +453,7 @@ declare module '@deepseek-ai/cordis' {
|
|
|
323
453
|
'po/workflow-context': PoWorkflowContextService;
|
|
324
454
|
'po/workflow-admissions': PoWorkflowAdmissionsService;
|
|
325
455
|
'po/workflow-identity': PoWorkflowIdentityService;
|
|
456
|
+
'po/workflow-profile-admission': PoWorkflowProfileAdmissionService;
|
|
326
457
|
}
|
|
327
458
|
}
|
|
328
459
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow.d.mts","names":["Type.TString","Type.TObject"],"sources":["../../../../../../../../po-core/dist/src/schemas/workflow.d.mts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"workflow.d.mts","names":["Type.TString","Type.TObject","Type.TArray","Type.TLiteral","Type.TUnion","Type.TRecord","Type.TBoolean"],"sources":["../../../../../../../../po-core/dist/src/schemas/workflow.d.mts"],"mappings":";;;;;;;;;;;;qBAYqB,+BAA+BC;EAClD,QAAQD;EACR,KAAKA;;YAEK,0BAA0B,cAAc;;qBAE/B,wBAAwBC;EAC3C,OAAOD;EACP,gBAAgBA;EAChB,QAAQA;EACR,mBAAmBA;;YAET,mBAAmB,cAAc;;qBAQxB,sCAAsCC;EACzD,YAAYA;IACV,QAAQD;IACR,KAAKA;;EAEP,UAAUA;EACV,OAAOE,OAAYF;EACnB,QAAQE,OAAYD;IAClB,MAAMG,QAAaD,iBAAsBA,mBAAwBA;IACjE,KAAKH;IACL,OAAOE,OAAYF;;;YAGX,iCAAiC,cAAc;qBACtC,6BAA6BK,gBAAqBL;YAC3D,wBAAwB,cAAc;qBAgB7B,mCAAmCC;EACtD,OAAOA;IACL,aAAaD;IACb,SAASA;IACT,UAAUA;;EAEZ,YAAYE,OAAYD;IACtB,KAAKD;IACL,OAAOA;IACP,OAAOE,OAAYF;IACnB,iBAAiBM;;;YAGT,8BAA8B,cAAc;;qBAuBnC,4BAA4BL;EAC/C,SAASE;EACT,cAAcF;IACZ,YAAYA;MACV,QAAQD;MACR,KAAKA;;IAEP,UAAUA;IACV,OAAOE,OAAYF;IACnB,QAAQE,OAAYD;MAClB,MAAMG,QAAaD,iBAAs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P;MACA;;MAEA;;EAEJ,oBAAoB;IAClB;IACA,WAAW,SAAS;;;EAGtB,mBAAmB;IACjB;MACE;IACF;IACA,WAAW,SAAS;;;;iBAIP;WACN,KAAK;WACL;WACA;WACA;WACA,QAAQ;WACR,gBAAgB,SAAS;WACzB,iBAAiB,SAAS;WAC1B;;WAEA;WACA,OAAO;WACP,WAAW;;WAEX,WAAW;;WAEX,aAAa;;iBAEP;WACN;;WAEA;;;iBAGM;WACN;WACA;WACA;WACA;;WAEA;WACA;WACA;WACA;;;;;;;iBAOM;;EAEf,UAAU,cAAc,iCAAiC,QAAQ;;EAEjE,UAAU,SAAS,8BAA8B,QAAQ;;EAEzD,sBAAsB,YAAY,uBAAuB,QAAQ;;EAEjE,QAAQ,SAAS,4BAA4B,QAAQ;;EAErD,WAAW,SAAS,4BAA4B,QAAQ;;;iBAGzC;EACf,YAAY,UAAU,6BAA6B;;;YAGzC;IACR,sBAAsB;IACtB,kCAAkC;IAClC,oBAAoB;IACpB,uBAAuB;IACvB,0BAA0B;IAC1B,wBAAwB;IACxB,iCAAiC"}
|
|
@@ -349,6 +349,11 @@ export interface WebPluginSlotProps {
|
|
|
349
349
|
html: string;
|
|
350
350
|
title: string;
|
|
351
351
|
}) => ReactNode;
|
|
352
|
+
/** Host-isolated MCP App for a persisted tool result in this session. */
|
|
353
|
+
renderMcpApp?: (request: {
|
|
354
|
+
key: string;
|
|
355
|
+
toolCallId: string;
|
|
356
|
+
}) => ReactNode;
|
|
352
357
|
nativeAuthor?: NativeAuthorHost;
|
|
353
358
|
/** Bounded sealed media bytes. The host validates the MIME type and never fetches the optional path. */
|
|
354
359
|
/** Package-bound sealed reads only. The host owns user-picked file IO, never transport. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webPlugin.d.mts","names":[],"sources":["../../../../../../../../../po-core/dist/src/web/types/webPlugin.d.mts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;YA8BY,sBAAsB,mBAAmB,OAA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;EAEtB,wBAAwB,MAAM;;EAE9B,wBAAwB,SAAS;;EAEjC,iBAAiB,SAAS,oBAAoB;;EAE9C,oBAAoB,MAAM,kCAAkC;;EAE5D,kBAAkB;;EAElB,aAAa,iBAAiB;;EAE9B,WAAW,MAAM,MAAM,gBAAgB,mBAAmB,aAAa;;;;;;;EAOvE,UAAU,SAAS;;EAEnB,4BAA4B;;EAE5B;;EAEA;;EAEA,iBAAiB;;EAEjB,aAAa"}
|
|
1
|
+
{"version":3,"file":"webPlugin.d.mts","names":[],"sources":["../../../../../../../../../po-core/dist/src/web/types/webPlugin.d.mts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;YA8BY,sBAAsB,mBAAmB,OAAO;;;;;;;;;;iBAU3C,gBAAgB;EAC/B;;EAEA;;EAEA;;EAEA,OAAO,iBAAiB;;;iBAGT,aAAa;EAC5B;EACA;EACA;EACA,MAAM;;;iBAGS;;EAEf;;EAEA,SAAS;;;;;;;;iBAQM;;EAEf;EACA;EACA,OAAO,cAAc;;EAErB;;EAEA;;EAEA;;;;;EAKA,mBAAmB,sBAAsB;;EAEzC,UAAU;;EAEV,WAAW;;;;;;;iBAkDI;;EAEf;;EAEA;;;iBAGe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;iBAGe;;EAEf;EACA;;EAEA,SAAS;;;iBAkBM;;EAEf;EACA;EACA;EACA;;;iBAyBe;EACf;EACA;EACA;EACA;EACA;EACA;;;;;;iBAMe;WACN;WACA;WACA;;WAEA;;;;;;iBAMM;WACN;;;iBAGM;WACN;WACA;aACE;aACA;;;WAGF;;iBAEM;WACN,mBAAmB;;WAEnB;;;;;;;iBAOM;WACN;WACA;;EAET;;;;;EAKA,cAAc,eAAe,YAAY,oBAAoB;;;;;EAK7D,gBAAgB,SAAS,gBAAgB,QAAQ;;EAEjD,cAAc,sBAAsB;;EAEpC,oBAAoB,eAAe,OAAO,gBAAgB,QAAQ;;;iBAGnD;EACf;EACA,OAAO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IACA;IACA;IACA;QACI;;EAEN,wBAAwB;IACtB;IACA,OAAO,cAAc,gCAAgC,QAAQ,gBAAgB;MAC3E;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,QAAQ,iBAAiB;QACrB;;EAEN,kBAAkB;IAChB,YAAY,aAAa,QAAQ,gBAAgB;IACjD,UAAU;IACV,UAAU;MACR;MACA;MACA;MACA;MACA;;;IAGF,aAAa;IACb;IACA,OAAO;IACP;IACA,OAAO;;;EAGT;IACE,iBAAiB;MACf,QAAQ,KAAK;MACb,UAAU;QACR;QACA;QACA;QACA;;UAEE;MACJ,YAAY;QACV;QACA;QACA;QACA;;;IAGJ,UAAU,KAAK,eAAe;MAC5B,YAAY;MACZ;;IAEF,aAAa;;;EAGf,sBAAsB;;EAEtB,wBAAwB,MAAM;;EAE9B,wBAAwB,SAAS;;EAEjC,iBAAiB,SAAS,oBAAoB;;EAE9C,oBAAoB,MAAM,kCAAkC;;EAE5D,kBAAkB;;EAElB,aAAa,iBAAiB;;EAE9B,WAAW,MAAM,MAAM,gBAAgB,mBAAmB,aAAa;;;;;;;EAOvE,UAAU,SAAS;;EAEnB,4BAA4B;;EAE5B;;EAEA;;EAEA,iBAAiB;;EAEjB,aAAa"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
//#region src/lib/mcpAppFrame.d.ts
|
|
2
|
+
export interface McpAppFrameOptions {
|
|
3
|
+
data: {
|
|
4
|
+
html: string;
|
|
5
|
+
protocol: 'mcp' | 'openai';
|
|
6
|
+
resourceMeta: Record<string, unknown>;
|
|
7
|
+
args: Record<string, unknown>;
|
|
8
|
+
result: {
|
|
9
|
+
content: unknown[];
|
|
10
|
+
structuredContent?: unknown;
|
|
11
|
+
_meta?: Record<string, unknown>;
|
|
12
|
+
isError?: boolean;
|
|
13
|
+
};
|
|
14
|
+
tool: {
|
|
15
|
+
name: string;
|
|
16
|
+
description: string;
|
|
17
|
+
inputSchema: {
|
|
18
|
+
type: 'object';
|
|
19
|
+
[key: string]: unknown;
|
|
20
|
+
};
|
|
21
|
+
_meta: Record<string, unknown>;
|
|
22
|
+
};
|
|
23
|
+
readOnly: boolean;
|
|
24
|
+
};
|
|
25
|
+
toolCallId: string;
|
|
26
|
+
savedState: unknown;
|
|
27
|
+
hostOrigin: string;
|
|
28
|
+
theme: 'light' | 'dark';
|
|
29
|
+
locale: string;
|
|
30
|
+
device: 'mobile' | 'desktop';
|
|
31
|
+
hover?: boolean;
|
|
32
|
+
touch?: boolean;
|
|
33
|
+
request(method: string, input: Record<string, unknown>): Promise<unknown>;
|
|
34
|
+
openLink(url: unknown): Promise<Record<string, never>>;
|
|
35
|
+
resize(height: number): void;
|
|
36
|
+
ready(): void;
|
|
37
|
+
fail(message: string): void;
|
|
38
|
+
close(): void;
|
|
39
|
+
saveState(state: unknown): void;
|
|
40
|
+
}
|
|
41
|
+
/** Connect a sandbox relay. The caller owns the lease and closes it on unmount. */
|
|
42
|
+
export declare function connectMcpAppFrame(frame: HTMLIFrameElement, options: McpAppFrameOptions): {
|
|
43
|
+
setTheme(theme: 'light' | 'dark'): void;
|
|
44
|
+
dispose(): void;
|
|
45
|
+
};
|
|
46
|
+
//#endregion
|
|
47
|
+
//# sourceMappingURL=mcpAppFrame.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpAppFrame.d.mts","names":[],"sources":["../../../../../../src/lib/mcpAppFrame.ts"],"mappings":";iBAWiB;EACf;IACE;IACA;IACA,cAAc;IACd,MAAM;IACN;MAAU;MAAoB;MAA6B,QAAQ;MAAyB;;IAC5F;MACE;MACA;MACA;QAAe;SAAiB;;MAChC,OAAO;;IAET;;EAEF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ,gBAAgB,OAAO,0BAA0B;EACzD,SAAS,eAAe,QAAQ;EAChC,OAAO;EACP;EACA,KAAK;EACL;EACA,UAAU;;;wBAYI,mBACd,OAAO,mBACP,SAAS;EACN,SAAS;EAAgC"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{mcpAppCsp as e,mcpAppDocument as t,mcpAppRelayHtml as n}from"./mcpAppSandbox.mjs";import{mcpOpenAiScript as r}from"./mcpOpenAiBootstrap.mjs";import{AppBridge as i,PostMessageTransport as a}from"@modelcontextprotocol/ext-apps/app-bridge";const o=1200,s=`po.openai`;function c(e){return e instanceof Error?e.message:`The MCP App could not complete this request`}function l(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Invalid App request`);return e}function u(u,d){if(u.contentWindow===null)throw Error(`MCP App frame is not mounted`);let{data:f}=d,p=!0,m,h=new MessageChannel,g=(e,t)=>p?d.request(e,t):Promise.reject(/* @__PURE__ */ Error(`MCP App is closed`)),_=e=>{typeof e==`number`&&Number.isFinite(e)&&d.resize(Math.min(o,Math.max(80,Math.ceil(e))))},v=e=>{p&&(d.fail(c(e)),p=!1,u.srcdoc=``,y().catch(t=>{d.fail(`${c(e)}. Closing the App lease failed: ${c(t)}`)}))},y=()=>d.request(`close`,{}),b=setTimeout(()=>v(/* @__PURE__ */ Error(`MCP App initialization timed out`)),15e3),x=()=>{p&&(clearTimeout(b),d.ready())},S=async(e,t)=>{if(f.readOnly)throw Error(`Enable interactions in the conversation before calling tools`);if(typeof e!=`string`)throw Error(`Invalid App tool name`);return await g(`callTool`,{name:e,arguments:l(t??{})})},C=async e=>(await g(`setState`,{state:e}),d.saveState(e),{}),w=async e=>{if(f.readOnly)throw Error(`Enable interactions in the conversation before sending a follow-up`);if(typeof e!=`string`)throw Error(`Invalid App follow-up`);return await g(`followUp`,{prompt:e}),{}},T=async()=>(await g(`close`,{}),d.close(),{}),E=d.theme,D=E,O={toolInput:f.args,toolOutput:f.result.structuredContent??null,toolResponseMetadata:f.result._meta??{},widgetState:d.savedState,theme:E,locale:d.locale,displayMode:`inline`,maxHeight:o,safeArea:{insets:{top:0,right:0,bottom:0,left:0}},userAgent:{device:{type:d.device},capabilities:{hover:d.hover??!1,touch:d.touch??!1}}};try{let o=e(f.resourceMeta,d.hostOrigin);f.protocol===`mcp`&&(m=new i(null,{name:`Po`,version:`1`},{...f.readOnly?{}:{serverTools:{},message:{text:{}}},openLinks:{}},{hostContext:{theme:E,locale:d.locale,displayMode:`inline`,availableDisplayModes:[`inline`],toolInfo:{id:d.toolCallId,tool:f.tool}}}),m.oncalltool=({name:e,arguments:t})=>S(e,t),m.onmessage=async({content:e})=>{if(e.some(e=>e.type!==`text`))throw Error(`Only text follow-ups are supported`);return w(e.map(e=>e.type===`text`?e.text:``).join(`
|
|
2
|
+
`))},m.onopenlink=({url:e})=>d.openLink(e),m.onsizechange=({height:e})=>_(e),m.onrequestdisplaymode=async()=>({mode:`inline`}),m.onrequestteardown=()=>{T().catch(v)},m.oninitialized=()=>{(async()=>{await m.sendToolInput({arguments:f.args}),await m.sendToolResult(f.result),x()})().catch(v)},m.connect(new a(u.contentWindow,u.contentWindow)).catch(v)),h.port1.onmessage=e=>{if(!p)return;let t=e.data;if(t?.type===`revoked`){v(/* @__PURE__ */ Error(`MCP App navigation was blocked; reopen it to continue`));return}if(t?.type!==`legacy`)return;let n=t.data;n?.channel===s&&(async()=>{let e=l(n.input??{});switch(n.method){case`initialized`:{x();let e=D;return e!==E&&h.port1.postMessage({channel:s,globals:{theme:e}}),{}}case`height`:return _(e.height),{};case`callTool`:return S(e.name,e.arguments);case`setState`:return C(e.state);case`followUp`:return w(e.prompt);case`openLink`:return d.openLink(e.url);case`close`:return T();default:throw Error(`Unsupported ChatGPT widget method`)}})().then(e=>{if(!p||n.id===void 0)return;let t=n.method===`callTool`&&f.protocol===`openai`?e:void 0;h.port1.postMessage({channel:s,id:n.id,result:e,...t===void 0?{}:{globals:{toolOutput:t.structuredContent??null,toolResponseMetadata:t._meta??{}}}})},e=>{p&&n.id!==void 0&&h.port1.postMessage({channel:s,id:n.id,error:c(e)})})},h.port1.start();let g=()=>{u.contentWindow?.postMessage({html:t(f.html,o,r(O),E),policy:o,protocol:f.protocol},`*`,[h.port2])};return u.addEventListener(`load`,g,{once:!0}),u.srcdoc=n(o,E),{setTheme:e=>{D=e,m?.setHostContext({theme:e}),h.port1.postMessage({channel:s,globals:{theme:e}})},dispose:()=>{p=!1,clearTimeout(b),u.removeEventListener(`load`,g),h.port1.close(),h.port2.close(),m!==void 0&&m.close().catch(e=>d.fail(c(e))),u.srcdoc=``}}}catch(e){return v(e),{setTheme:()=>{},dispose:()=>{clearTimeout(b),h.port1.close(),h.port2.close()}}}}export{u as connectMcpAppFrame};
|
|
3
|
+
//# sourceMappingURL=mcpAppFrame.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpAppFrame.mjs","names":["MAX_HEIGHT","LEGACY_CHANNEL","errorText","error","object","value","connectMcpAppFrame","frame","options","live","bridge","channels","request","method","input","resize","fail","requestCloseLease","closeError","timeout","markReady","callTool","data","name","args","persist","state","followUp","prompt","close","theme","activeTheme","globals","policy","mcpAppCsp","AppBridge","content","block","url","next","PostMessageTransport","message","event","legacy","loadedTheme","returned","result","load","mcpAppDocument","mcpOpenAiScript","mcpAppRelayHtml","nextTheme"],"sources":["../../../../../../src/lib/mcpAppFrame.ts"],"sourcesContent":["import { AppBridge, PostMessageTransport } from '@modelcontextprotocol/ext-apps/app-bridge';\n\nimport { mcpAppCsp, mcpAppDocument, mcpAppRelayHtml } from './mcpAppSandbox';\nimport { mcpOpenAiScript } from './mcpOpenAiBootstrap';\n\ntype CallToolResult = Awaited<ReturnType<NonNullable<AppBridge['oncalltool']>>>;\nconst MAX_HEIGHT = 1200;\nconst MIN_HEIGHT = 80;\nconst OPEN_TIMEOUT = 15_000;\nconst LEGACY_CHANNEL = 'po.openai';\n\nexport interface McpAppFrameOptions {\n data: {\n html: string;\n protocol: 'mcp' | 'openai';\n resourceMeta: Record<string, unknown>;\n args: Record<string, unknown>;\n result: { content: unknown[]; structuredContent?: unknown; _meta?: Record<string, unknown>; isError?: boolean };\n tool: {\n name: string;\n description: string;\n inputSchema: { type: 'object'; [key: string]: unknown };\n _meta: Record<string, unknown>;\n };\n readOnly: boolean;\n };\n toolCallId: string;\n savedState: unknown;\n hostOrigin: string;\n theme: 'light' | 'dark';\n locale: string;\n device: 'mobile' | 'desktop';\n hover?: boolean;\n touch?: boolean;\n request(method: string, input: Record<string, unknown>): Promise<unknown>;\n openLink(url: unknown): Promise<Record<string, never>>;\n resize(height: number): void;\n ready(): void;\n fail(message: string): void;\n close(): void;\n saveState(state: unknown): void;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : 'The MCP App could not complete this request';\n}\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid App request');\n return value as Record<string, unknown>;\n}\n\n/** Connect a sandbox relay. The caller owns the lease and closes it on unmount. */\nexport function connectMcpAppFrame(\n frame: HTMLIFrameElement,\n options: McpAppFrameOptions,\n): { setTheme(theme: 'light' | 'dark'): void; dispose(): void } {\n if (frame.contentWindow === null) throw new Error('MCP App frame is not mounted');\n const { data } = options;\n let live = true;\n let bridge: AppBridge | undefined;\n const channels = new MessageChannel();\n const request = (method: string, input: Record<string, unknown>) => {\n if (!live) return Promise.reject(new Error('MCP App is closed'));\n return options.request(method, input);\n };\n const resize = (value: unknown): void => {\n if (typeof value === 'number' && Number.isFinite(value)) {\n options.resize(Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(value))));\n }\n };\n const fail = (error: unknown): void => {\n if (!live) return;\n options.fail(errorText(error));\n live = false;\n frame.srcdoc = '';\n void requestCloseLease().catch((closeError: unknown) => {\n options.fail(`${errorText(error)}. Closing the App lease failed: ${errorText(closeError)}`);\n });\n };\n const requestCloseLease = (): Promise<unknown> => options.request('close', {});\n const timeout = setTimeout(() => fail(new Error('MCP App initialization timed out')), OPEN_TIMEOUT);\n const markReady = (): void => {\n if (!live) return;\n clearTimeout(timeout);\n options.ready();\n };\n const callTool = async (name: unknown, args: unknown): Promise<CallToolResult> => {\n if (data.readOnly) throw new Error('Enable interactions in the conversation before calling tools');\n if (typeof name !== 'string') throw new Error('Invalid App tool name');\n const result = await request('callTool', { name, arguments: object(args ?? {}) });\n return result as CallToolResult;\n };\n const persist = async (state: unknown): Promise<Record<string, never>> => {\n await request('setState', { state });\n options.saveState(state);\n return {};\n };\n const followUp = async (prompt: unknown): Promise<Record<string, never>> => {\n if (data.readOnly) throw new Error('Enable interactions in the conversation before sending a follow-up');\n if (typeof prompt !== 'string') throw new Error('Invalid App follow-up');\n await request('followUp', { prompt });\n return {};\n };\n const close = async (): Promise<Record<string, never>> => {\n await request('close', {});\n options.close();\n return {};\n };\n const theme = options.theme;\n let activeTheme = theme;\n const globals = {\n toolInput: data.args,\n toolOutput: data.result.structuredContent ?? null,\n toolResponseMetadata: data.result._meta ?? {},\n widgetState: options.savedState,\n theme,\n locale: options.locale,\n displayMode: 'inline' as const,\n maxHeight: MAX_HEIGHT,\n safeArea: { insets: { top: 0, right: 0, bottom: 0, left: 0 } },\n userAgent: {\n device: { type: options.device },\n capabilities: { hover: options.hover ?? false, touch: options.touch ?? false },\n },\n };\n try {\n const policy = mcpAppCsp(data.resourceMeta, options.hostOrigin);\n if (data.protocol === 'mcp') {\n bridge = new AppBridge(\n null,\n { name: 'Po', version: '1' },\n {\n ...(data.readOnly ? {} : { serverTools: {}, message: { text: {} } }),\n openLinks: {},\n },\n {\n hostContext: {\n theme,\n locale: options.locale,\n displayMode: 'inline',\n availableDisplayModes: ['inline'],\n toolInfo: { id: options.toolCallId, tool: data.tool },\n },\n },\n );\n bridge.oncalltool = ({ name, arguments: args }) => callTool(name, args);\n bridge.onmessage = async ({ content }) => {\n if (content.some((block) => block.type !== 'text')) throw new Error('Only text follow-ups are supported');\n return followUp(content.map((block) => (block.type === 'text' ? block.text : '')).join('\\n'));\n };\n bridge.onopenlink = ({ url }) => options.openLink(url);\n bridge.onsizechange = ({ height: next }) => resize(next);\n bridge.onrequestdisplaymode = async () => ({ mode: 'inline' });\n bridge.onrequestteardown = () => {\n void close().catch(fail);\n };\n bridge.oninitialized = () => {\n void (async () => {\n await bridge!.sendToolInput({ arguments: data.args });\n await bridge!.sendToolResult(data.result as CallToolResult);\n markReady();\n })().catch(fail);\n };\n void bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)).catch(fail);\n }\n channels.port1.onmessage = (event: MessageEvent<unknown>) => {\n if (!live) return;\n const message = event.data as { type?: string; data?: unknown };\n if (message?.type === 'revoked') {\n fail(new Error('MCP App navigation was blocked; reopen it to continue'));\n return;\n }\n if (message?.type !== 'legacy') return;\n const legacy = message.data as { channel?: string; id?: number; method?: string; input?: unknown } | null;\n if (legacy?.channel !== LEGACY_CHANNEL) return;\n void (async () => {\n const input = object(legacy.input ?? {});\n switch (legacy.method) {\n case 'initialized': {\n markReady();\n // A theme change while the App document loaded reached no listener; this one runs after it.\n const loadedTheme = activeTheme;\n if (loadedTheme !== theme)\n channels.port1.postMessage({ channel: LEGACY_CHANNEL, globals: { theme: loadedTheme } });\n return {};\n }\n case 'height':\n resize(input.height);\n return {};\n case 'callTool':\n return callTool(input.name, input.arguments);\n case 'setState':\n return persist(input.state);\n case 'followUp':\n return followUp(input.prompt);\n case 'openLink':\n return options.openLink(input.url);\n case 'close':\n return close();\n default:\n throw new Error('Unsupported ChatGPT widget method');\n }\n })().then(\n (result) => {\n if (!live || legacy.id === undefined) return;\n // A widget's own call returns its result; replacing the rendered tool's output corrupts widgets that persist it.\n const returned =\n legacy.method === 'callTool' && data.protocol === 'openai' ? (result as CallToolResult) : undefined;\n channels.port1.postMessage({\n channel: LEGACY_CHANNEL,\n id: legacy.id,\n result,\n ...(returned === undefined\n ? {}\n : {\n globals: {\n toolOutput: returned.structuredContent ?? null,\n toolResponseMetadata: returned._meta ?? {},\n },\n }),\n });\n },\n (error: unknown) => {\n if (!live || legacy.id === undefined) return;\n channels.port1.postMessage({ channel: LEGACY_CHANNEL, id: legacy.id, error: errorText(error) });\n },\n );\n };\n channels.port1.start();\n const load = (): void => {\n frame.contentWindow?.postMessage(\n {\n html: mcpAppDocument(data.html, policy, mcpOpenAiScript(globals), theme),\n policy,\n protocol: data.protocol,\n },\n '*',\n [channels.port2],\n );\n };\n frame.addEventListener('load', load, { once: true });\n frame.srcdoc = mcpAppRelayHtml(policy, theme);\n const setTheme = (nextTheme: 'light' | 'dark'): void => {\n activeTheme = nextTheme;\n bridge?.setHostContext({ theme: nextTheme });\n channels.port1.postMessage({ channel: LEGACY_CHANNEL, globals: { theme: nextTheme } });\n };\n return {\n setTheme,\n dispose: () => {\n live = false;\n clearTimeout(timeout);\n frame.removeEventListener('load', load);\n channels.port1.close();\n channels.port2.close();\n if (bridge !== undefined) void bridge.close().catch((error: unknown) => options.fail(errorText(error)));\n frame.srcdoc = '';\n },\n };\n } catch (error) {\n fail(error);\n return {\n setTheme: () => {},\n dispose: () => {\n clearTimeout(timeout);\n channels.port1.close();\n channels.port2.close();\n },\n };\n }\n}\n"],"mappings":"oPAMA,MAAMA,EAAa,KAGbC,EAAiB,YAkCvB,SAASC,EAAU,EAAwB,CACzC,OAAOC,aAAiB,MAAQA,EAAM,QAAU,6CAClD,CACA,SAASC,EAAO,EAAyC,CACvD,GAAsB,OAAOC,GAAU,WAAnCA,GAA+C,MAAM,QAAQA,CAAK,EAAG,MAAU,MAAM,qBAAqB,EAC9G,OAAOA,CACT,CAGA,SAAgBC,EACd,EACA,EAC8D,CAC9D,GAAIC,EAAM,gBAAkB,KAAM,MAAU,MAAM,8BAA8B,EAChF,GAAM,CAAE,QAASC,EACbC,EAAO,GACPC,EACEC,EAAW,IAAI,eACfC,GAAW,EAAgB,IAC1BH,EACED,EAAQ,QAAQK,EAAQC,CAAK,EADlB,QAAQ,OAAO,gBAAI,MAAM,mBAAmB,CAAC,EAG3DC,EAAU,GAAyB,CACnC,OAAOV,GAAU,UAAY,OAAO,SAASA,CAAK,GACpDG,EAAQ,OAAO,KAAK,IAAIR,EAAY,KAAK,IAAI,GAAY,KAAK,KAAKK,CAAK,CAAC,CAAC,CAAC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MAAM,EACrBA,EAAS,MAAM,MAAM,CACvB,CACF,CACF,CACF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/lib/mcpAppSandbox.d.ts
|
|
2
|
+
export declare function mcpAppCsp(metadata: unknown, hostOrigin: string): string;
|
|
3
|
+
type HostTheme = 'light' | 'dark';
|
|
4
|
+
/** The theme a host message carries, from either bridge. Serialized into frames, so it stays self-contained. */
|
|
5
|
+
export declare function mcpAppHostTheme(data: unknown): HostTheme | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* Bundled trusted code, runs inside the App document. Waits for the App's own
|
|
8
|
+
* <html> attributes, which the parser merges only where the root has none, so
|
|
9
|
+
* an App-chosen class or data-theme wins until the host theme changes.
|
|
10
|
+
*/
|
|
11
|
+
export declare function widgetThemeBootstrap(hostTheme: (data: unknown) => HostTheme | undefined, initial: HostTheme): void;
|
|
12
|
+
export declare function mcpAppRelayHtml(policy: string, theme?: HostTheme): string;
|
|
13
|
+
/** No host <html> is injected, so the App's own root attributes survive parsing. */
|
|
14
|
+
export declare function mcpAppDocument(html: string, policy: string, bootstrap?: string, theme?: HostTheme): string;
|
|
15
|
+
/** Required CSP enforcement must survive self-navigation, not only initial srcdoc. */
|
|
16
|
+
export declare function supportsMcpAppSandbox(host: Document | HTMLIFrameElement): boolean;
|
|
17
|
+
//#endregion
|
|
18
|
+
export {};
|
|
19
|
+
//# sourceMappingURL=mcpAppSandbox.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpAppSandbox.d.mts","names":[],"sources":["../../../../../../src/lib/mcpAppSandbox.ts"],"mappings":";wBA0CgB,UAAU,mBAAmB;KAkCxC;;wBAGW,gBAAgB,gBAAgB;;;;;;wBAsBhC,qBAAqB,YAAY,kBAAkB,uBAAuB,SAAS;wBAgHnF,gBAAgB,gBAAgB,QAAO;;wBAUvC,eAAe,cAAc,gBAAgB,oBAAgB,QAAO;;wBAMpE,sBAAsB,MAAM,WAAW"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=/^(localhost|127(\.\d{1,3}){3}|\[::1\])$/u;function t(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function n(t,n){if(t===void 0)return[];if(!Array.isArray(t)||t.length>64)throw Error(`Invalid widget CSP domains`);return t.map(t=>{if(typeof t!=`string`||t.length>2048)throw Error(`Invalid widget CSP domain`);let r=new URL(t),i=r.hostname.replace(/^%2a\./iu,`*.`),a=i.startsWith(`*.`),o=new URL(n),s=e.test(r.hostname),c=s?e.test(o.hostname)&&r.port===o.port:i===o.hostname||a&&o.hostname.endsWith(i.slice(1));if(!(s?[`http:`,`https:`,`ws:`,`wss:`]:[`https:`,`wss:`]).includes(r.protocol)||r.username||r.password||r.pathname!==`/`||r.search||r.hash||c||r.hostname.startsWith(`0.`)||/[\s;'"<>]/u.test(t))throw Error(`Unsafe widget CSP domain`);return`${r.protocol}//${i}${r.port?`:${r.port}`:``}`})}function r(e,r){let i=t(e),a=t(i?.ui);if(i?.ui!==void 0&&a===void 0)throw Error(`Invalid widget UI metadata`);let o=a!==void 0&&`csp`in a,s=o?a.csp:i?.[`openai/widgetCSP`],c=s===void 0?{}:t(s);if(c===void 0)throw Error(`Invalid widget CSP`);let l=n(c[o?`resourceDomains`:`resource_domains`],r).join(` `),u=n(c[o?`connectDomains`:`connect_domains`],r).join(` `),d=n(c[o?`frameDomains`:`frame_domains`],r).join(` `);return[`default-src 'none'`,`script-src 'unsafe-inline' ${l}`,`style-src 'unsafe-inline' ${l}`,`img-src data: blob: ${l}`,`font-src data: ${l}`,`media-src blob: ${l}`,`connect-src ${u||`'none'`}`,`frame-src ${d||`'none'`}`,`child-src ${d||`'none'`}`,`worker-src 'none'`,`object-src 'none'`,`base-uri 'none'`,`form-action 'none'`].join(`; `)}function i(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`)}function a(e){let t=e,n=t?.channel===`po.openai`?t.globals?.theme:t?.jsonrpc===`2.0`&&t.method===`ui/notifications/host-context-changed`?t.params?.theme:void 0;return n===`light`||n===`dark`?n:void 0}function o(e,t){let n=document.documentElement,r=t,i=!1,a=()=>{!n.classList.contains(`light`)&&!n.classList.contains(`dark`)&&n.classList.add(r),n.getAttribute(`data-theme`)===null&&n.setAttribute(`data-theme`,r)},o=()=>{n.classList.remove(`light`,`dark`),n.classList.add(r);let e=n.getAttribute(`data-theme`);(e===null||e===`light`||e===`dark`)&&n.setAttribute(`data-theme`,r),n.style.colorScheme=r};window.addEventListener(`message`,t=>{let n=t.source===parent?e(t.data):void 0;n!==void 0&&(r=n,i=!0,document.readyState!==`loading`&&o())}),document.readyState===`loading`?document.addEventListener(`readystatechange`,()=>{document.readyState===`interactive`&&(i?o():a())}):a()}function s(e){let t=!1,n=t=>{let n=e(t);n!==void 0&&(document.documentElement.style.colorScheme=n)};window.addEventListener(`message`,e=>{if(e.source!==parent||t||e.ports.length!==1)return;let r=e.data;if(typeof r?.html!=`string`||typeof r.policy!=`string`)return;t=!0;let i=e.ports[0],a=document.createElement(`iframe`);a.title=`MCP App content`,a.setAttribute(`sandbox`,`allow-scripts`),r.policy.includes(`frame-src 'none'`)&&a.setAttribute(`csp`,r.policy),a.setAttribute(`allow`,`camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'`),a.style.cssText=`width:100%;height:100%;border:0;display:block`;let o=!1,s=!1,c=()=>{s||(s=!0,a.remove(),i.postMessage({type:`revoked`}),i.close())};a.addEventListener(`load`,()=>{o&&c(),o=!0});let l=Date.now(),u=0;window.addEventListener(`message`,e=>{if(s||e.source!==a.contentWindow)return;try{let t=JSON.stringify(e.data);if(t===void 0||new TextEncoder().encode(t).byteLength>65536)return c();let n=Date.now();if(n-l>=1e3&&(l=n,u=0),++u>128)return c()}catch{return c()}let t=e.data?.channel===`po.openai`;r.protocol===`mcp`&&!t?parent.postMessage(e.data,`*`):i.postMessage({type:`legacy`,data:e.data})}),i.onmessage=e=>{s||(n(e.data),a.contentWindow?.postMessage(e.data,`*`))},window.addEventListener(`message`,e=>{if(!s&&e.source===parent&&r.protocol===`mcp`){let t=e.data;if(t?.jsonrpc!==`2.0`)return;n(t),a.contentWindow?.postMessage(t,`*`)}}),i.start(),a.srcdoc=r.html,document.body.append(a),i.postMessage({type:`ready`})})}function c(e,t=`light`){return`<!doctype html><html style="color-scheme:${t}"><meta http-equiv="Content-Security-Policy" content="${i(e.replace(/\b(frame|child)-src ([^;]*)/gu,(e,t,n)=>n===`'none'`?`${t}-src about:`:`${t}-src about: ${n}`))}"><style>html,body{margin:0;height:100%;overflow:hidden}</style><script>(${s.toString()})(${a.toString()})<\/script>`}function l(e,t,n=``,r=`light`){let s=`<script>(${o.toString()})(${a.toString()}, ${JSON.stringify(r)})<\/script>`;return`<!doctype html><meta http-equiv="Content-Security-Policy" content="${i(t)}"><meta name="color-scheme" content="${r}">${s}${n}${e}`}function u(e){return`csp`in(`createElement`in e?e.createElement(`iframe`):e)}export{r as mcpAppCsp,l as mcpAppDocument,a as mcpAppHostTheme,c as mcpAppRelayHtml,s as relayBootstrap,u as supportsMcpAppSandbox,o as widgetThemeBootstrap};
|
|
2
|
+
//# sourceMappingURL=mcpAppSandbox.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpAppSandbox.mjs","names":["LOOPBACK_HOSTNAME","record","value","origins","domain","parsed","hostname","wildcard","host","hostOrigin","loopback","includesHost","mcpAppCsp","meta","metadata","ui","standard","raw","csp","resource","connect","frame","escapeAttribute","mcpAppHostTheme","message","data","theme","widgetThemeBootstrap","root","initial","changed","settle","follow","current","next","event","hostTheme","relayBootstrap","configured","config","port","inner","loaded","revoked","revoke","messageWindow","messageCount","childEvent","encoded","now","openai","hostEvent","mcpAppRelayHtml","policy","sources","kind","mcpAppDocument","themeScript","bootstrap","html","supportsMcpAppSandbox"],"sources":["../../../../../../src/lib/mcpAppSandbox.ts"],"sourcesContent":["const MAX_CSP_DOMAINS = 64;\nconst MAX_DOMAIN_LENGTH = 2048;\nconst LOOPBACK_HOSTNAME = /^(localhost|127(\\.\\d{1,3}){3}|\\[::1\\])$/u;\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Accept origins only, never CSP tokens, URL paths, credentials, or the host origin. */\nfunction origins(value: unknown, hostOrigin: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value) || value.length > MAX_CSP_DOMAINS) throw new Error('Invalid widget CSP domains');\n return value.map((domain: unknown) => {\n if (typeof domain !== 'string' || domain.length > MAX_DOMAIN_LENGTH) throw new Error('Invalid widget CSP domain');\n const parsed = new URL(domain);\n // Browsers percent-encode a wildcard label (`*.` becomes `%2A.`), which CSP ignores as an invalid source.\n const hostname = parsed.hostname.replace(/^%2a\\./iu, '*.');\n const wildcard = hostname.startsWith('*.');\n const host = new URL(hostOrigin);\n // Local dev servers serve widgets over plain HTTP on loopback; Po's own loopback origin stays excluded.\n const loopback = LOOPBACK_HOSTNAME.test(parsed.hostname);\n const includesHost = loopback\n ? LOOPBACK_HOSTNAME.test(host.hostname) && parsed.port === host.port\n : hostname === host.hostname || (wildcard && host.hostname.endsWith(hostname.slice(1)));\n if (\n !(loopback ? ['http:', 'https:', 'ws:', 'wss:'] : ['https:', 'wss:']).includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.pathname !== '/' ||\n parsed.search ||\n parsed.hash ||\n includesHost ||\n parsed.hostname.startsWith('0.') ||\n /[\\s;'\"<>]/u.test(domain)\n )\n throw new Error('Unsafe widget CSP domain');\n return `${parsed.protocol}//${hostname}${parsed.port ? `:${parsed.port}` : ''}`;\n });\n}\n\nexport function mcpAppCsp(metadata: unknown, hostOrigin: string): string {\n const meta = record(metadata);\n const ui = record(meta?.ui);\n if (meta?.ui !== undefined && ui === undefined) throw new Error('Invalid widget UI metadata');\n // A present standard field always wins, including malformed values (fail closed).\n const standard = ui !== undefined && 'csp' in ui;\n const raw = standard ? ui.csp : meta?.['openai/widgetCSP'];\n const csp = raw === undefined ? {} : record(raw);\n if (csp === undefined) throw new Error('Invalid widget CSP');\n const resource = origins(csp[standard ? 'resourceDomains' : 'resource_domains'], hostOrigin).join(' ');\n const connect = origins(csp[standard ? 'connectDomains' : 'connect_domains'], hostOrigin).join(' ');\n const frame = origins(csp[standard ? 'frameDomains' : 'frame_domains'], hostOrigin).join(' ');\n // Nested frames load only from declared frame domains; forms, base URLs, workers and navigation privileges are not admitted.\n return [\n \"default-src 'none'\",\n `script-src 'unsafe-inline' ${resource}`,\n `style-src 'unsafe-inline' ${resource}`,\n `img-src data: blob: ${resource}`,\n `font-src data: ${resource}`,\n `media-src blob: ${resource}`,\n `connect-src ${connect || \"'none'\"}`,\n `frame-src ${frame || \"'none'\"}`,\n `child-src ${frame || \"'none'\"}`,\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n ].join('; ');\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replaceAll('&', '&').replaceAll('\"', '"').replaceAll('<', '<');\n}\n\ntype HostTheme = 'light' | 'dark';\n\n/** The theme a host message carries, from either bridge. Serialized into frames, so it stays self-contained. */\nexport function mcpAppHostTheme(data: unknown): HostTheme | undefined {\n const message = data as {\n channel?: unknown;\n globals?: { theme?: unknown } | null;\n jsonrpc?: unknown;\n method?: unknown;\n params?: { theme?: unknown } | null;\n } | null;\n const theme =\n message?.channel === 'po.openai'\n ? message.globals?.theme\n : message?.jsonrpc === '2.0' && message.method === 'ui/notifications/host-context-changed'\n ? message.params?.theme\n : undefined;\n return theme === 'light' || theme === 'dark' ? theme : undefined;\n}\n\n/**\n * Bundled trusted code, runs inside the App document. Waits for the App's own\n * <html> attributes, which the parser merges only where the root has none, so\n * an App-chosen class or data-theme wins until the host theme changes.\n */\nexport function widgetThemeBootstrap(hostTheme: (data: unknown) => HostTheme | undefined, initial: HostTheme): void {\n const root = document.documentElement;\n let theme = initial;\n let changed = false;\n const settle = (): void => {\n if (!root.classList.contains('light') && !root.classList.contains('dark')) root.classList.add(theme);\n if (root.getAttribute('data-theme') === null) root.setAttribute('data-theme', theme);\n };\n const follow = (): void => {\n root.classList.remove('light', 'dark');\n root.classList.add(theme);\n const current = root.getAttribute('data-theme');\n if (current === null || current === 'light' || current === 'dark') root.setAttribute('data-theme', theme);\n root.style.colorScheme = theme;\n };\n window.addEventListener('message', (event: MessageEvent<unknown>) => {\n const next = event.source === parent ? hostTheme(event.data) : undefined;\n if (next === undefined) return;\n theme = next;\n changed = true;\n if (document.readyState !== 'loading') follow();\n });\n if (document.readyState !== 'loading') settle();\n else\n document.addEventListener('readystatechange', () => {\n if (document.readyState === 'interactive') {\n if (changed) follow();\n else settle();\n }\n });\n}\n\n/** Bundled trusted code, runs in an opaque relay separate from the untrusted App. */\nexport function relayBootstrap(hostTheme: (data: unknown) => HostTheme | undefined): void {\n let configured = false;\n // The relay canvas must match the App's color scheme or the browser paints it opaque.\n const follow = (data: unknown): void => {\n const theme = hostTheme(data);\n if (theme !== undefined) document.documentElement.style.colorScheme = theme;\n };\n window.addEventListener('message', (event: MessageEvent<unknown>) => {\n if (event.source !== parent || configured || event.ports.length !== 1) return;\n const config = event.data as { html: string; policy: string; protocol: string };\n if (typeof config?.html !== 'string' || typeof config.policy !== 'string') return;\n configured = true;\n const port = event.ports[0]!;\n const inner = document.createElement('iframe');\n inner.title = 'MCP App content';\n inner.setAttribute('sandbox', 'allow-scripts');\n // Required CSP also binds nested frames, so an App with declared frame domains relies on the inherited relay\n // policy instead: MCP Apps let those frames keep their own CSP, and the relay revokes any second document.\n if (config.policy.includes(\"frame-src 'none'\")) inner.setAttribute('csp', config.policy);\n inner.setAttribute(\n 'allow',\n \"camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'\",\n );\n inner.style.cssText = 'width:100%;height:100%;border:0;display:block';\n let loaded = false;\n let revoked = false;\n const revoke = (): void => {\n if (revoked) return;\n revoked = true;\n inner.remove();\n port.postMessage({ type: 'revoked' });\n port.close();\n };\n inner.addEventListener('load', () => {\n if (loaded) revoke();\n loaded = true;\n });\n let messageWindow = Date.now();\n let messageCount = 0;\n window.addEventListener('message', (childEvent: MessageEvent<unknown>) => {\n if (revoked || childEvent.source !== inner.contentWindow) return;\n try {\n const encoded = JSON.stringify(childEvent.data);\n if (encoded === undefined || new TextEncoder().encode(encoded).byteLength > 65536) return revoke();\n const now = Date.now();\n if (now - messageWindow >= 1000) {\n messageWindow = now;\n messageCount = 0;\n }\n if (++messageCount > 128) return revoke();\n } catch {\n return revoke();\n }\n // window.openai is in every App, so its channel reaches the host port whatever the protocol.\n const openai = (childEvent.data as { channel?: unknown } | null)?.channel === 'po.openai';\n if (config.protocol === 'mcp' && !openai) parent.postMessage(childEvent.data, '*');\n else port.postMessage({ type: 'legacy', data: childEvent.data });\n });\n // The parent alone owns the other end of this channel. No origin-based trust.\n port.onmessage = (hostEvent: MessageEvent<unknown>) => {\n if (revoked) return;\n follow(hostEvent.data);\n inner.contentWindow?.postMessage(hostEvent.data, '*');\n };\n window.addEventListener('message', (hostEvent: MessageEvent<unknown>) => {\n if (!revoked && hostEvent.source === parent && config.protocol === 'mcp') {\n const data = hostEvent.data as { jsonrpc?: string } | null;\n if (data?.jsonrpc !== '2.0') return;\n follow(data);\n inner.contentWindow?.postMessage(data, '*');\n }\n });\n port.start();\n inner.srcdoc = config.html;\n document.body.append(inner);\n port.postMessage({ type: 'ready' });\n });\n}\n\nexport function mcpAppRelayHtml(policy: string, theme: HostTheme = 'light'): string {\n // frame-src adds srcdoc/about for the App frame, never a host route or a remote sandbox URL. The App's\n // declared frame domains stay, because the srcdoc App inherits this policy for its own nested frames.\n const relayPolicy = policy.replace(/\\b(frame|child)-src ([^;]*)/gu, (_, kind: string, sources: string) =>\n sources === \"'none'\" ? `${kind}-src about:` : `${kind}-src about: ${sources}`,\n );\n return `<!doctype html><html style=\"color-scheme:${theme}\"><meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(relayPolicy)}\"><style>html,body{margin:0;height:100%;overflow:hidden}</style><script>(${relayBootstrap.toString()})(${mcpAppHostTheme.toString()})</script>`;\n}\n\n/** No host <html> is injected, so the App's own root attributes survive parsing. */\nexport function mcpAppDocument(html: string, policy: string, bootstrap = '', theme: HostTheme = 'light'): string {\n const themeScript = `<script>(${widgetThemeBootstrap.toString()})(${mcpAppHostTheme.toString()}, ${JSON.stringify(theme)})</script>`;\n return `<!doctype html><meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(policy)}\"><meta name=\"color-scheme\" content=\"${theme}\">${themeScript}${bootstrap}${html}`;\n}\n\n/** Required CSP enforcement must survive self-navigation, not only initial srcdoc. */\nexport function supportsMcpAppSandbox(host: Document | HTMLIFrameElement): boolean {\n const frame = 'createElement' in host ? host.createElement('iframe') : host;\n return 'csp' in frame;\n}\n"],"mappings":"AAAA,MAEMA,EAAoB,2CAE1B,SAASC,EAAO,EAAqD,CACnE,OAAyB,OAAOC,GAAU,UAAnCA,GAA+C,CAAC,MAAM,QAAQA,CAAK,EACrEA,EACD,IAAA,EACN,CAGA,SAASC,EAAQ,EAAgB,EAA8B,CAC7D,GAAID,IAAU,IAAA,GAAW,MAAO,CAAC,EACjC,GAAI,CAAC,MAAM,QAAQA,CAAK,GAAKA,EAAM,OAAS,GAAiB,MAAU,MAAM,4BAA4B,EACzG,OAAOA,EAAM,IAAK,GAAoB,CACpC,GAAI,OAAOE,GAAW,UAAYA,EAAO,OAAS,KAAmB,MAAU,MAAM,2BAA2B,EAChH,IAAMC,EAAS,IAAI,IAAID,CAAM,EAEvBE,EAAWD,EAAO,SAAS,QAAQ,WAAY,IAAI,EACnDE,EAAWD,EAAS,WAAW,IAAI,EACnCE,EAAO,IAAI,IAAIC,CAAU,EAEzBC,EAAWV,EAAkB,KAAKK,EAAO,QAAQ,EACjDM,EAAeD,EACjBV,EAAkB,KAAKQ,EAAK,QAA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EAAgB+B,CAAM,EAAE,uCAAuC3B,EAAM,IAAI+B,IAAcC,IAAYC,GAClL,CAGA,SAAgBC,EAAsB,EAA6C,CAEjF,MAAO,QADO,kBAAmBpD,EAAOA,EAAK,cAAc,QAAQ,EAAIA,EAEzE"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
//#region src/lib/mcpOpenAiBootstrap.d.ts
|
|
2
|
+
interface LegacyGlobals {
|
|
3
|
+
toolInput: Record<string, unknown>;
|
|
4
|
+
toolOutput: unknown;
|
|
5
|
+
toolResponseMetadata: Record<string, unknown>;
|
|
6
|
+
widgetState: unknown;
|
|
7
|
+
theme: 'light' | 'dark';
|
|
8
|
+
locale: string;
|
|
9
|
+
displayMode: 'inline';
|
|
10
|
+
maxHeight: number;
|
|
11
|
+
userAgent: {
|
|
12
|
+
device: {
|
|
13
|
+
type: 'desktop' | 'mobile';
|
|
14
|
+
};
|
|
15
|
+
capabilities: {
|
|
16
|
+
hover: boolean;
|
|
17
|
+
touch: boolean;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
safeArea: {
|
|
21
|
+
insets: {
|
|
22
|
+
top: number;
|
|
23
|
+
right: number;
|
|
24
|
+
bottom: number;
|
|
25
|
+
left: number;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export declare function mcpOpenAiScript(globals: LegacyGlobals): string;
|
|
30
|
+
//#endregion
|
|
31
|
+
export {};
|
|
32
|
+
//# sourceMappingURL=mcpOpenAiBootstrap.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpOpenAiBootstrap.d.mts","names":[],"sources":["../../../../../../src/lib/mcpOpenAiBootstrap.ts"],"mappings":";UAAU;EACR,WAAW;EACX;EACA,sBAAsB;EACtB;EACA;EACA;EACA;EACA;EACA;IAAa;MAAU;;IAA8B;MAAgB;MAAgB;;;EACrF;IAAY;MAAU;MAAa;MAAe;MAAgB;;;;wBAwGpD,gBAAgB,SAAS"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){let t=`po.openai`,n=/* @__PURE__ */ new Map,r=0,i=e,a=e=>{i={...i,...e},window.dispatchEvent(new CustomEvent(`openai:set_globals`,{detail:{globals:e}}))},o=(e,i)=>{if(n.size>=32)return Promise.reject(/* @__PURE__ */ Error(`Too many pending widget requests`));let a=++r;return new Promise((r,o)=>{let s=window.setTimeout(()=>{n.delete(a),o(/* @__PURE__ */ Error(`Widget request timed out`))},6e4);n.set(a,{resolve:r,reject:o,timer:s}),parent.postMessage({channel:t,id:a,method:e,input:i},`*`)})};Object.defineProperty(window,"openai",{value:Object.freeze({get toolInput(){return i.toolInput},get toolOutput(){return i.toolOutput},get toolResponseMetadata(){return i.toolResponseMetadata},get widgetState(){return i.widgetState},get theme(){return i.theme},get locale(){return i.locale},get displayMode(){return i.displayMode},get maxHeight(){return i.maxHeight},get safeArea(){return i.safeArea},get userAgent(){return i.userAgent},callTool:(e,t={})=>o(`callTool`,{name:e,arguments:t}),setWidgetState:e=>(a({widgetState:e}),o(`setState`,{state:e})),sendFollowUpMessage:e=>o(`followUp`,e),requestDisplayMode:()=>Promise.resolve({mode:`inline`}),openExternal:e=>o(`openLink`,{url:e.href}),requestClose:()=>o(`close`,{}),notifyIntrinsicHeight:e=>o(`height`,{height:e})}),configurable:!1,writable:!1}),window.addEventListener(`message`,e=>{if(e.source!==parent)return;let r=e.data;if(r?.channel!==t||(r.globals!==void 0&&a(r.globals),r.id===void 0))return;let i=n.get(r.id);i!==void 0&&(n.delete(r.id),clearTimeout(i.timer),typeof r.error==`string`?i.reject(Error(r.error)):i.resolve(r.result))}),parent.postMessage({channel:t,method:`initialized`,input:{}},`*`),document.addEventListener(`DOMContentLoaded`,()=>{a(i);let e=new ResizeObserver(()=>{let e=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);parent.postMessage({channel:t,method:`height`,input:{height:e}},`*`)});e.observe(document.body),window.addEventListener(`pagehide`,()=>e.disconnect(),{once:!0})},{once:!0})}function t(t){let n=JSON.stringify(t).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);return`<script>(${e.toString()})(${n})<\/script>`}export{e as bootstrap,t as mcpOpenAiScript};
|
|
2
|
+
//# sourceMappingURL=mcpOpenAiBootstrap.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpOpenAiBootstrap.mjs","names":["bootstrap","channel","pending","sequence","globals","initial","update","patch","request","id","timer","reject","args","state","input","event","message","callback","observer","height","mcpOpenAiScript","encoded"],"sources":["../../../../../../src/lib/mcpOpenAiBootstrap.ts"],"sourcesContent":["interface LegacyGlobals {\n toolInput: Record<string, unknown>;\n toolOutput: unknown;\n toolResponseMetadata: Record<string, unknown>;\n widgetState: unknown;\n theme: 'light' | 'dark';\n locale: string;\n displayMode: 'inline';\n maxHeight: number;\n userAgent: { device: { type: 'desktop' | 'mobile' }; capabilities: { hover: boolean; touch: boolean } };\n safeArea: { insets: { top: number; right: number; bottom: number; left: number } };\n}\n\nexport function bootstrap(initial: LegacyGlobals): void {\n const channel = 'po.openai';\n const requestTimeout = 60_000;\n const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void; timer: number }>();\n let sequence = 0;\n let globals = initial;\n const update = (patch: Partial<LegacyGlobals>): void => {\n globals = { ...globals, ...patch };\n window.dispatchEvent(new CustomEvent('openai:set_globals', { detail: { globals: patch } }));\n };\n const request = (method: string, input: unknown): Promise<unknown> => {\n if (pending.size >= 32) return Promise.reject(new Error('Too many pending widget requests'));\n const id = ++sequence;\n return new Promise((resolve, reject) => {\n const timer = window.setTimeout(() => {\n pending.delete(id);\n reject(new Error('Widget request timed out'));\n }, requestTimeout);\n pending.set(id, { resolve, reject, timer });\n parent.postMessage({ channel, id, method, input }, '*');\n });\n };\n const api = {\n get toolInput() {\n return globals.toolInput;\n },\n get toolOutput() {\n return globals.toolOutput;\n },\n get toolResponseMetadata() {\n return globals.toolResponseMetadata;\n },\n get widgetState() {\n return globals.widgetState;\n },\n get theme() {\n return globals.theme;\n },\n get locale() {\n return globals.locale;\n },\n get displayMode() {\n return globals.displayMode;\n },\n get maxHeight() {\n return globals.maxHeight;\n },\n get safeArea() {\n return globals.safeArea;\n },\n get userAgent() {\n return globals.userAgent;\n },\n callTool: (name: string, args: Record<string, unknown> = {}) => request('callTool', { name, arguments: args }),\n setWidgetState: (state: unknown) => {\n // Immediate local state, with await-compatible durable persistence.\n update({ widgetState: state });\n return request('setState', { state });\n },\n sendFollowUpMessage: (input: { prompt: string }) => request('followUp', input),\n requestDisplayMode: () => Promise.resolve({ mode: 'inline' }),\n openExternal: (input: { href: string }) => request('openLink', { url: input.href }),\n requestClose: () => request('close', {}),\n notifyIntrinsicHeight: (height: number) => request('height', { height }),\n };\n Object.defineProperty(window, 'openai', { value: Object.freeze(api), configurable: false, writable: false });\n window.addEventListener('message', (event: MessageEvent<unknown>) => {\n if (event.source !== parent) return;\n const message = event.data as {\n channel?: string;\n id?: number;\n error?: string;\n result?: unknown;\n globals?: Partial<LegacyGlobals>;\n };\n if (message?.channel !== channel) return;\n if (message.globals !== undefined) update(message.globals);\n if (message.id === undefined) return;\n const callback = pending.get(message.id);\n if (callback === undefined) return;\n pending.delete(message.id);\n clearTimeout(callback.timer);\n if (typeof message.error === 'string') callback.reject(new Error(message.error));\n else callback.resolve(message.result);\n });\n parent.postMessage({ channel, method: 'initialized', input: {} }, '*');\n document.addEventListener(\n 'DOMContentLoaded',\n () => {\n update(globals);\n const observer = new ResizeObserver(() => {\n const height = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);\n parent.postMessage({ channel, method: 'height', input: { height } }, '*');\n });\n observer.observe(document.body);\n window.addEventListener('pagehide', () => observer.disconnect(), { once: true });\n },\n { once: true },\n );\n}\n\nexport function mcpOpenAiScript(globals: LegacyGlobals): string {\n const encoded = JSON.stringify(globals)\n .replaceAll('<', '\\\\u003c')\n .replaceAll('\\u2028', '\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CAAE,QAAO,CAAE,EAAG,GAAG,CAC1E,CAAC,EACDD,EAAS,QAAQ,SAAS,IAAI,EAC9B,OAAO,iBAAiB,eAAkBA,EAAS,WAAW,EAAG,CAAE,KAAM,EAAK,CAAC,CACjF,EACA,CAAE,KAAM,EAAK,CACf,CACF,CAEA,SAAgBE,EAAgB,EAAgC,CAC9D,IAAMC,EAAU,KAAK,UAAUjB,CAAO,CAAC,CACpC,WAAW,IAAK,SAAS,CAAC,CAC1B,WAAW,SAAU,SAAS,CAAC,CAC/B,WAAW,SAAU,SAAS,EACjC,MAAO,YAAYJ,EAAU,SAAS,EAAE,IAAIqB,EAAQ,YACtD"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("./mcpAppSandbox.cjs"),t=require("./mcpOpenAiBootstrap.cjs");let n=require("@modelcontextprotocol/ext-apps/app-bridge");const r=1200,i=`po.openai`;function a(e){return e instanceof Error?e.message:`The MCP App could not complete this request`}function o(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Invalid App request`);return e}function s(s,c){if(s.contentWindow===null)throw Error(`MCP App frame is not mounted`);let{data:l}=c,u=!0,d,f=new MessageChannel,p=(e,t)=>u?c.request(e,t):Promise.reject(/* @__PURE__ */ Error(`MCP App is closed`)),m=e=>{typeof e==`number`&&Number.isFinite(e)&&c.resize(Math.min(r,Math.max(80,Math.ceil(e))))},h=e=>{u&&(c.fail(a(e)),u=!1,s.srcdoc=``,g().catch(t=>{c.fail(`${a(e)}. Closing the App lease failed: ${a(t)}`)}))},g=()=>c.request(`close`,{}),_=setTimeout(()=>h(/* @__PURE__ */ Error(`MCP App initialization timed out`)),15e3),v=()=>{u&&(clearTimeout(_),c.ready())},y=async(e,t)=>{if(l.readOnly)throw Error(`Enable interactions in the conversation before calling tools`);if(typeof e!=`string`)throw Error(`Invalid App tool name`);return await p(`callTool`,{name:e,arguments:o(t??{})})},b=async e=>(await p(`setState`,{state:e}),c.saveState(e),{}),x=async e=>{if(l.readOnly)throw Error(`Enable interactions in the conversation before sending a follow-up`);if(typeof e!=`string`)throw Error(`Invalid App follow-up`);return await p(`followUp`,{prompt:e}),{}},S=async()=>(await p(`close`,{}),c.close(),{}),C=c.theme,w=C,T={toolInput:l.args,toolOutput:l.result.structuredContent??null,toolResponseMetadata:l.result._meta??{},widgetState:c.savedState,theme:C,locale:c.locale,displayMode:`inline`,maxHeight:r,safeArea:{insets:{top:0,right:0,bottom:0,left:0}},userAgent:{device:{type:c.device},capabilities:{hover:c.hover??!1,touch:c.touch??!1}}};try{let r=e.mcpAppCsp(l.resourceMeta,c.hostOrigin);l.protocol===`mcp`&&(d=new n.AppBridge(null,{name:`Po`,version:`1`},{...l.readOnly?{}:{serverTools:{},message:{text:{}}},openLinks:{}},{hostContext:{theme:C,locale:c.locale,displayMode:`inline`,availableDisplayModes:[`inline`],toolInfo:{id:c.toolCallId,tool:l.tool}}}),d.oncalltool=({name:e,arguments:t})=>y(e,t),d.onmessage=async({content:e})=>{if(e.some(e=>e.type!==`text`))throw Error(`Only text follow-ups are supported`);return x(e.map(e=>e.type===`text`?e.text:``).join(`
|
|
2
|
+
`))},d.onopenlink=({url:e})=>c.openLink(e),d.onsizechange=({height:e})=>m(e),d.onrequestdisplaymode=async()=>({mode:`inline`}),d.onrequestteardown=()=>{S().catch(h)},d.oninitialized=()=>{(async()=>{await d.sendToolInput({arguments:l.args}),await d.sendToolResult(l.result),v()})().catch(h)},d.connect(new n.PostMessageTransport(s.contentWindow,s.contentWindow)).catch(h)),f.port1.onmessage=e=>{if(!u)return;let t=e.data;if(t?.type===`revoked`){h(/* @__PURE__ */ Error(`MCP App navigation was blocked; reopen it to continue`));return}if(t?.type!==`legacy`)return;let n=t.data;n?.channel===i&&(async()=>{let e=o(n.input??{});switch(n.method){case`initialized`:{v();let e=w;return e!==C&&f.port1.postMessage({channel:i,globals:{theme:e}}),{}}case`height`:return m(e.height),{};case`callTool`:return y(e.name,e.arguments);case`setState`:return b(e.state);case`followUp`:return x(e.prompt);case`openLink`:return c.openLink(e.url);case`close`:return S();default:throw Error(`Unsupported ChatGPT widget method`)}})().then(e=>{if(!u||n.id===void 0)return;let t=n.method===`callTool`&&l.protocol===`openai`?e:void 0;f.port1.postMessage({channel:i,id:n.id,result:e,...t===void 0?{}:{globals:{toolOutput:t.structuredContent??null,toolResponseMetadata:t._meta??{}}}})},e=>{u&&n.id!==void 0&&f.port1.postMessage({channel:i,id:n.id,error:a(e)})})},f.port1.start();let p=()=>{s.contentWindow?.postMessage({html:e.mcpAppDocument(l.html,r,t.mcpOpenAiScript(T),C),policy:r,protocol:l.protocol},`*`,[f.port2])};return s.addEventListener(`load`,p,{once:!0}),s.srcdoc=e.mcpAppRelayHtml(r,C),{setTheme:e=>{w=e,d?.setHostContext({theme:e}),f.port1.postMessage({channel:i,globals:{theme:e}})},dispose:()=>{u=!1,clearTimeout(_),s.removeEventListener(`load`,p),f.port1.close(),f.port2.close(),d!==void 0&&d.close().catch(e=>c.fail(a(e))),s.srcdoc=``}}}catch(e){return h(e),{setTheme:()=>{},dispose:()=>{clearTimeout(_),f.port1.close(),f.port2.close()}}}}exports.connectMcpAppFrame=s;
|
|
3
|
+
//# sourceMappingURL=mcpAppFrame.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpAppFrame.cjs","names":["mcpAppCsp","AppBridge","PostMessageTransport","mcpAppDocument","mcpOpenAiScript","mcpAppRelayHtml","require_mcpAppSandbox","require_mcpOpenAiBootstrap","_modelcontextprotocol_ext_apps_app_bridge","MAX_HEIGHT","LEGACY_CHANNEL","errorText","error","object","value","connectMcpAppFrame","frame","options","live","bridge","channels","request","method","input","resize","fail","requestCloseLease","closeError","timeout","markReady","callTool","data","name","args","persist","state","followUp","prompt","close","theme","activeTheme","globals","policy","content","block","url","next","message","event","legacy","loadedTheme","returned","result","load","nextTheme"],"sources":["../../../src/lib/mcpAppFrame.ts"],"sourcesContent":["import { AppBridge, PostMessageTransport } from '@modelcontextprotocol/ext-apps/app-bridge';\n\nimport { mcpAppCsp, mcpAppDocument, mcpAppRelayHtml } from './mcpAppSandbox';\nimport { mcpOpenAiScript } from './mcpOpenAiBootstrap';\n\ntype CallToolResult = Awaited<ReturnType<NonNullable<AppBridge['oncalltool']>>>;\nconst MAX_HEIGHT = 1200;\nconst MIN_HEIGHT = 80;\nconst OPEN_TIMEOUT = 15_000;\nconst LEGACY_CHANNEL = 'po.openai';\n\nexport interface McpAppFrameOptions {\n data: {\n html: string;\n protocol: 'mcp' | 'openai';\n resourceMeta: Record<string, unknown>;\n args: Record<string, unknown>;\n result: { content: unknown[]; structuredContent?: unknown; _meta?: Record<string, unknown>; isError?: boolean };\n tool: {\n name: string;\n description: string;\n inputSchema: { type: 'object'; [key: string]: unknown };\n _meta: Record<string, unknown>;\n };\n readOnly: boolean;\n };\n toolCallId: string;\n savedState: unknown;\n hostOrigin: string;\n theme: 'light' | 'dark';\n locale: string;\n device: 'mobile' | 'desktop';\n hover?: boolean;\n touch?: boolean;\n request(method: string, input: Record<string, unknown>): Promise<unknown>;\n openLink(url: unknown): Promise<Record<string, never>>;\n resize(height: number): void;\n ready(): void;\n fail(message: string): void;\n close(): void;\n saveState(state: unknown): void;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : 'The MCP App could not complete this request';\n}\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid App request');\n return value as Record<string, unknown>;\n}\n\n/** Connect a sandbox relay. The caller owns the lease and closes it on unmount. */\nexport function connectMcpAppFrame(\n frame: HTMLIFrameElement,\n options: McpAppFrameOptions,\n): { setTheme(theme: 'light' | 'dark'): void; dispose(): void } {\n if (frame.contentWindow === null) throw new Error('MCP App frame is not mounted');\n const { data } = options;\n let live = true;\n let bridge: AppBridge | undefined;\n const channels = new MessageChannel();\n const request = (method: string, input: Record<string, unknown>) => {\n if (!live) return Promise.reject(new Error('MCP App is closed'));\n return options.request(method, input);\n };\n const resize = (value: unknown): void => {\n if (typeof value === 'number' && Number.isFinite(value)) {\n options.resize(Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(value))));\n }\n };\n const fail = (error: unknown): void => {\n if (!live) return;\n options.fail(errorText(error));\n live = false;\n frame.srcdoc = '';\n void requestCloseLease().catch((closeError: unknown) => {\n options.fail(`${errorText(error)}. Closing the App lease failed: ${errorText(closeError)}`);\n });\n };\n const requestCloseLease = (): Promise<unknown> => options.request('close', {});\n const timeout = setTimeout(() => fail(new Error('MCP App initialization timed out')), OPEN_TIMEOUT);\n const markReady = (): void => {\n if (!live) return;\n clearTimeout(timeout);\n options.ready();\n };\n const callTool = async (name: unknown, args: unknown): Promise<CallToolResult> => {\n if (data.readOnly) throw new Error('Enable interactions in the conversation before calling tools');\n if (typeof name !== 'string') throw new Error('Invalid App tool name');\n const result = await request('callTool', { name, arguments: object(args ?? {}) });\n return result as CallToolResult;\n };\n const persist = async (state: unknown): Promise<Record<string, never>> => {\n await request('setState', { state });\n options.saveState(state);\n return {};\n };\n const followUp = async (prompt: unknown): Promise<Record<string, never>> => {\n if (data.readOnly) throw new Error('Enable interactions in the conversation before sending a follow-up');\n if (typeof prompt !== 'string') throw new Error('Invalid App follow-up');\n await request('followUp', { prompt });\n return {};\n };\n const close = async (): Promise<Record<string, never>> => {\n await request('close', {});\n options.close();\n return {};\n };\n const theme = options.theme;\n let activeTheme = theme;\n const globals = {\n toolInput: data.args,\n toolOutput: data.result.structuredContent ?? null,\n toolResponseMetadata: data.result._meta ?? {},\n widgetState: options.savedState,\n theme,\n locale: options.locale,\n displayMode: 'inline' as const,\n maxHeight: MAX_HEIGHT,\n safeArea: { insets: { top: 0, right: 0, bottom: 0, left: 0 } },\n userAgent: {\n device: { type: options.device },\n capabilities: { hover: options.hover ?? false, touch: options.touch ?? false },\n },\n };\n try {\n const policy = mcpAppCsp(data.resourceMeta, options.hostOrigin);\n if (data.protocol === 'mcp') {\n bridge = new AppBridge(\n null,\n { name: 'Po', version: '1' },\n {\n ...(data.readOnly ? {} : { serverTools: {}, message: { text: {} } }),\n openLinks: {},\n },\n {\n hostContext: {\n theme,\n locale: options.locale,\n displayMode: 'inline',\n availableDisplayModes: ['inline'],\n toolInfo: { id: options.toolCallId, tool: data.tool },\n },\n },\n );\n bridge.oncalltool = ({ name, arguments: args }) => callTool(name, args);\n bridge.onmessage = async ({ content }) => {\n if (content.some((block) => block.type !== 'text')) throw new Error('Only text follow-ups are supported');\n return followUp(content.map((block) => (block.type === 'text' ? block.text : '')).join('\\n'));\n };\n bridge.onopenlink = ({ url }) => options.openLink(url);\n bridge.onsizechange = ({ height: next }) => resize(next);\n bridge.onrequestdisplaymode = async () => ({ mode: 'inline' });\n bridge.onrequestteardown = () => {\n void close().catch(fail);\n };\n bridge.oninitialized = () => {\n void (async () => {\n await bridge!.sendToolInput({ arguments: data.args });\n await bridge!.sendToolResult(data.result as CallToolResult);\n markReady();\n })().catch(fail);\n };\n void bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)).catch(fail);\n }\n channels.port1.onmessage = (event: MessageEvent<unknown>) => {\n if (!live) return;\n const message = event.data as { type?: string; data?: unknown };\n if (message?.type === 'revoked') {\n fail(new Error('MCP App navigation was blocked; reopen it to continue'));\n return;\n }\n if (message?.type !== 'legacy') return;\n const legacy = message.data as { channel?: string; id?: number; method?: string; input?: unknown } | null;\n if (legacy?.channel !== LEGACY_CHANNEL) return;\n void (async () => {\n const input = object(legacy.input ?? {});\n switch (legacy.method) {\n case 'initialized': {\n markReady();\n // A theme change while the App document loaded reached no listener; this one runs after it.\n const loadedTheme = activeTheme;\n if (loadedTheme !== theme)\n channels.port1.postMessage({ channel: LEGACY_CHANNEL, globals: { theme: loadedTheme } });\n return {};\n }\n case 'height':\n resize(input.height);\n return {};\n case 'callTool':\n return callTool(input.name, input.arguments);\n case 'setState':\n return persist(input.state);\n case 'followUp':\n return followUp(input.prompt);\n case 'openLink':\n return options.openLink(input.url);\n case 'close':\n return close();\n default:\n throw new Error('Unsupported ChatGPT widget method');\n }\n })().then(\n (result) => {\n if (!live || legacy.id === undefined) return;\n // A widget's own call returns its result; replacing the rendered tool's output corrupts widgets that persist it.\n const returned =\n legacy.method === 'callTool' && data.protocol === 'openai' ? (result as CallToolResult) : undefined;\n channels.port1.postMessage({\n channel: LEGACY_CHANNEL,\n id: legacy.id,\n result,\n ...(returned === undefined\n ? {}\n : {\n globals: {\n toolOutput: returned.structuredContent ?? null,\n toolResponseMetadata: returned._meta ?? {},\n },\n }),\n });\n },\n (error: unknown) => {\n if (!live || legacy.id === undefined) return;\n channels.port1.postMessage({ channel: LEGACY_CHANNEL, id: legacy.id, error: errorText(error) });\n },\n );\n };\n channels.port1.start();\n const load = (): void => {\n frame.contentWindow?.postMessage(\n {\n html: mcpAppDocument(data.html, policy, mcpOpenAiScript(globals), theme),\n policy,\n protocol: data.protocol,\n },\n '*',\n [channels.port2],\n );\n };\n frame.addEventListener('load', load, { once: true });\n frame.srcdoc = mcpAppRelayHtml(policy, theme);\n const setTheme = (nextTheme: 'light' | 'dark'): void => {\n activeTheme = nextTheme;\n bridge?.setHostContext({ theme: nextTheme });\n channels.port1.postMessage({ channel: LEGACY_CHANNEL, globals: { theme: nextTheme } });\n };\n return {\n setTheme,\n dispose: () => {\n live = false;\n clearTimeout(timeout);\n frame.removeEventListener('load', load);\n channels.port1.close();\n channels.port2.close();\n if (bridge !== undefined) void bridge.close().catch((error: unknown) => options.fail(errorText(error)));\n frame.srcdoc = '';\n },\n };\n } catch (error) {\n fail(error);\n return {\n setTheme: () => {},\n dispose: () => {\n clearTimeout(timeout);\n channels.port1.close();\n channels.port2.close();\n },\n };\n }\n}\n"],"mappings":"wIAMA,MAAMS,EAAa,KAGbC,EAAiB,YAkCvB,SAASC,EAAU,EAAwB,CACzC,OAAOC,aAAiB,MAAQA,EAAM,QAAU,6CAClD,CACA,SAASC,EAAO,EAAyC,CACvD,GAAsB,OAAOC,GAAU,WAAnCA,GAA+C,MAAM,QA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ce,EACdnC,GAAQ,eAAe,CAAE,MAAOmC,CAAU,CAAC,EAC3ClC,EAAS,MAAM,YAAY,CAAE,QAASV,EAAgB,QAAS,CAAE,MAAO4C,CAAU,CAAE,CAAC,CACvF,EAGE,YAAe,CACb,EAAO,GACP,aAAa1B,CAAO,EACpBZ,EAAM,oBAAoB,OAAQqC,CAAI,EACtCjC,EAAS,MAAM,MAAM,EACrBA,EAAS,MAAM,MAAM,EACjBD,IAAW,IAAA,IAAWA,EAAY,MAAM,CAAC,CAAC,MAAO,GAAmBF,EAAQ,KAAKN,EAAUC,CAAK,CAAC,CAAC,EACtG,EAAM,OAAS,EACjB,CACF,CACF,OAASA,EAAO,CAEd,OADAa,EAAKb,CAAK,EACH,CACL,aAAgB,CAAC,EACjB,YAAe,CACb,aAAagB,CAAO,EACpBR,EAAS,MAAM,MAAM,EACrBA,EAAS,MAAM,MAAM,CACvB,CACF,CACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=/^(localhost|127(\.\d{1,3}){3}|\[::1\])$/u;function t(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function n(t,n){if(t===void 0)return[];if(!Array.isArray(t)||t.length>64)throw Error(`Invalid widget CSP domains`);return t.map(t=>{if(typeof t!=`string`||t.length>2048)throw Error(`Invalid widget CSP domain`);let r=new URL(t),i=r.hostname.replace(/^%2a\./iu,`*.`),a=i.startsWith(`*.`),o=new URL(n),s=e.test(r.hostname),c=s?e.test(o.hostname)&&r.port===o.port:i===o.hostname||a&&o.hostname.endsWith(i.slice(1));if(!(s?[`http:`,`https:`,`ws:`,`wss:`]:[`https:`,`wss:`]).includes(r.protocol)||r.username||r.password||r.pathname!==`/`||r.search||r.hash||c||r.hostname.startsWith(`0.`)||/[\s;'"<>]/u.test(t))throw Error(`Unsafe widget CSP domain`);return`${r.protocol}//${i}${r.port?`:${r.port}`:``}`})}function r(e,r){let i=t(e),a=t(i?.ui);if(i?.ui!==void 0&&a===void 0)throw Error(`Invalid widget UI metadata`);let o=a!==void 0&&`csp`in a,s=o?a.csp:i?.[`openai/widgetCSP`],c=s===void 0?{}:t(s);if(c===void 0)throw Error(`Invalid widget CSP`);let l=n(c[o?`resourceDomains`:`resource_domains`],r).join(` `),u=n(c[o?`connectDomains`:`connect_domains`],r).join(` `),d=n(c[o?`frameDomains`:`frame_domains`],r).join(` `);return[`default-src 'none'`,`script-src 'unsafe-inline' ${l}`,`style-src 'unsafe-inline' ${l}`,`img-src data: blob: ${l}`,`font-src data: ${l}`,`media-src blob: ${l}`,`connect-src ${u||`'none'`}`,`frame-src ${d||`'none'`}`,`child-src ${d||`'none'`}`,`worker-src 'none'`,`object-src 'none'`,`base-uri 'none'`,`form-action 'none'`].join(`; `)}function i(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`)}function a(e){let t=e,n=t?.channel===`po.openai`?t.globals?.theme:t?.jsonrpc===`2.0`&&t.method===`ui/notifications/host-context-changed`?t.params?.theme:void 0;return n===`light`||n===`dark`?n:void 0}function o(e,t){let n=document.documentElement,r=t,i=!1,a=()=>{!n.classList.contains(`light`)&&!n.classList.contains(`dark`)&&n.classList.add(r),n.getAttribute(`data-theme`)===null&&n.setAttribute(`data-theme`,r)},o=()=>{n.classList.remove(`light`,`dark`),n.classList.add(r);let e=n.getAttribute(`data-theme`);(e===null||e===`light`||e===`dark`)&&n.setAttribute(`data-theme`,r),n.style.colorScheme=r};window.addEventListener(`message`,t=>{let n=t.source===parent?e(t.data):void 0;n!==void 0&&(r=n,i=!0,document.readyState!==`loading`&&o())}),document.readyState===`loading`?document.addEventListener(`readystatechange`,()=>{document.readyState===`interactive`&&(i?o():a())}):a()}function s(e){let t=!1,n=t=>{let n=e(t);n!==void 0&&(document.documentElement.style.colorScheme=n)};window.addEventListener(`message`,e=>{if(e.source!==parent||t||e.ports.length!==1)return;let r=e.data;if(typeof r?.html!=`string`||typeof r.policy!=`string`)return;t=!0;let i=e.ports[0],a=document.createElement(`iframe`);a.title=`MCP App content`,a.setAttribute(`sandbox`,`allow-scripts`),r.policy.includes(`frame-src 'none'`)&&a.setAttribute(`csp`,r.policy),a.setAttribute(`allow`,`camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'`),a.style.cssText=`width:100%;height:100%;border:0;display:block`;let o=!1,s=!1,c=()=>{s||(s=!0,a.remove(),i.postMessage({type:`revoked`}),i.close())};a.addEventListener(`load`,()=>{o&&c(),o=!0});let l=Date.now(),u=0;window.addEventListener(`message`,e=>{if(s||e.source!==a.contentWindow)return;try{let t=JSON.stringify(e.data);if(t===void 0||new TextEncoder().encode(t).byteLength>65536)return c();let n=Date.now();if(n-l>=1e3&&(l=n,u=0),++u>128)return c()}catch{return c()}let t=e.data?.channel===`po.openai`;r.protocol===`mcp`&&!t?parent.postMessage(e.data,`*`):i.postMessage({type:`legacy`,data:e.data})}),i.onmessage=e=>{s||(n(e.data),a.contentWindow?.postMessage(e.data,`*`))},window.addEventListener(`message`,e=>{if(!s&&e.source===parent&&r.protocol===`mcp`){let t=e.data;if(t?.jsonrpc!==`2.0`)return;n(t),a.contentWindow?.postMessage(t,`*`)}}),i.start(),a.srcdoc=r.html,document.body.append(a),i.postMessage({type:`ready`})})}function c(e,t=`light`){return`<!doctype html><html style="color-scheme:${t}"><meta http-equiv="Content-Security-Policy" content="${i(e.replace(/\b(frame|child)-src ([^;]*)/gu,(e,t,n)=>n===`'none'`?`${t}-src about:`:`${t}-src about: ${n}`))}"><style>html,body{margin:0;height:100%;overflow:hidden}</style><script>(${s.toString()})(${a.toString()})<\/script>`}function l(e,t,n=``,r=`light`){let s=`<script>(${o.toString()})(${a.toString()}, ${JSON.stringify(r)})<\/script>`;return`<!doctype html><meta http-equiv="Content-Security-Policy" content="${i(t)}"><meta name="color-scheme" content="${r}">${s}${n}${e}`}function u(e){return`csp`in(`createElement`in e?e.createElement(`iframe`):e)}exports.mcpAppCsp=r,exports.mcpAppDocument=l,exports.mcpAppHostTheme=a,exports.mcpAppRelayHtml=c,exports.relayBootstrap=s,exports.supportsMcpAppSandbox=u,exports.widgetThemeBootstrap=o;
|
|
2
|
+
//# sourceMappingURL=mcpAppSandbox.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpAppSandbox.cjs","names":["LOOPBACK_HOSTNAME","record","value","origins","domain","parsed","hostname","wildcard","host","hostOrigin","loopback","includesHost","mcpAppCsp","meta","metadata","ui","standard","raw","csp","resource","connect","frame","escapeAttribute","mcpAppHostTheme","message","data","theme","widgetThemeBootstrap","root","initial","changed","settle","follow","current","next","event","hostTheme","relayBootstrap","configured","config","port","inner","loaded","revoked","revoke","messageWindow","messageCount","childEvent","encoded","now","openai","hostEvent","mcpAppRelayHtml","policy","sources","kind","mcpAppDocument","themeScript","bootstrap","html","supportsMcpAppSandbox"],"sources":["../../../src/lib/mcpAppSandbox.ts"],"sourcesContent":["const MAX_CSP_DOMAINS = 64;\nconst MAX_DOMAIN_LENGTH = 2048;\nconst LOOPBACK_HOSTNAME = /^(localhost|127(\\.\\d{1,3}){3}|\\[::1\\])$/u;\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Accept origins only, never CSP tokens, URL paths, credentials, or the host origin. */\nfunction origins(value: unknown, hostOrigin: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value) || value.length > MAX_CSP_DOMAINS) throw new Error('Invalid widget CSP domains');\n return value.map((domain: unknown) => {\n if (typeof domain !== 'string' || domain.length > MAX_DOMAIN_LENGTH) throw new Error('Invalid widget CSP domain');\n const parsed = new URL(domain);\n // Browsers percent-encode a wildcard label (`*.` becomes `%2A.`), which CSP ignores as an invalid source.\n const hostname = parsed.hostname.replace(/^%2a\\./iu, '*.');\n const wildcard = hostname.startsWith('*.');\n const host = new URL(hostOrigin);\n // Local dev servers serve widgets over plain HTTP on loopback; Po's own loopback origin stays excluded.\n const loopback = LOOPBACK_HOSTNAME.test(parsed.hostname);\n const includesHost = loopback\n ? LOOPBACK_HOSTNAME.test(host.hostname) && parsed.port === host.port\n : hostname === host.hostname || (wildcard && host.hostname.endsWith(hostname.slice(1)));\n if (\n !(loopback ? ['http:', 'https:', 'ws:', 'wss:'] : ['https:', 'wss:']).includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.pathname !== '/' ||\n parsed.search ||\n parsed.hash ||\n includesHost ||\n parsed.hostname.startsWith('0.') ||\n /[\\s;'\"<>]/u.test(domain)\n )\n throw new Error('Unsafe widget CSP domain');\n return `${parsed.protocol}//${hostname}${parsed.port ? `:${parsed.port}` : ''}`;\n });\n}\n\nexport function mcpAppCsp(metadata: unknown, hostOrigin: string): string {\n const meta = record(metadata);\n const ui = record(meta?.ui);\n if (meta?.ui !== undefined && ui === undefined) throw new Error('Invalid widget UI metadata');\n // A present standard field always wins, including malformed values (fail closed).\n const standard = ui !== undefined && 'csp' in ui;\n const raw = standard ? ui.csp : meta?.['openai/widgetCSP'];\n const csp = raw === undefined ? {} : record(raw);\n if (csp === undefined) throw new Error('Invalid widget CSP');\n const resource = origins(csp[standard ? 'resourceDomains' : 'resource_domains'], hostOrigin).join(' ');\n const connect = origins(csp[standard ? 'connectDomains' : 'connect_domains'], hostOrigin).join(' ');\n const frame = origins(csp[standard ? 'frameDomains' : 'frame_domains'], hostOrigin).join(' ');\n // Nested frames load only from declared frame domains; forms, base URLs, workers and navigation privileges are not admitted.\n return [\n \"default-src 'none'\",\n `script-src 'unsafe-inline' ${resource}`,\n `style-src 'unsafe-inline' ${resource}`,\n `img-src data: blob: ${resource}`,\n `font-src data: ${resource}`,\n `media-src blob: ${resource}`,\n `connect-src ${connect || \"'none'\"}`,\n `frame-src ${frame || \"'none'\"}`,\n `child-src ${frame || \"'none'\"}`,\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n ].join('; ');\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replaceAll('&', '&').replaceAll('\"', '"').replaceAll('<', '<');\n}\n\ntype HostTheme = 'light' | 'dark';\n\n/** The theme a host message carries, from either bridge. Serialized into frames, so it stays self-contained. */\nexport function mcpAppHostTheme(data: unknown): HostTheme | undefined {\n const message = data as {\n channel?: unknown;\n globals?: { theme?: unknown } | null;\n jsonrpc?: unknown;\n method?: unknown;\n params?: { theme?: unknown } | null;\n } | null;\n const theme =\n message?.channel === 'po.openai'\n ? message.globals?.theme\n : message?.jsonrpc === '2.0' && message.method === 'ui/notifications/host-context-changed'\n ? message.params?.theme\n : undefined;\n return theme === 'light' || theme === 'dark' ? theme : undefined;\n}\n\n/**\n * Bundled trusted code, runs inside the App document. Waits for the App's own\n * <html> attributes, which the parser merges only where the root has none, so\n * an App-chosen class or data-theme wins until the host theme changes.\n */\nexport function widgetThemeBootstrap(hostTheme: (data: unknown) => HostTheme | undefined, initial: HostTheme): void {\n const root = document.documentElement;\n let theme = initial;\n let changed = false;\n const settle = (): void => {\n if (!root.classList.contains('light') && !root.classList.contains('dark')) root.classList.add(theme);\n if (root.getAttribute('data-theme') === null) root.setAttribute('data-theme', theme);\n };\n const follow = (): void => {\n root.classList.remove('light', 'dark');\n root.classList.add(theme);\n const current = root.getAttribute('data-theme');\n if (current === null || current === 'light' || current === 'dark') root.setAttribute('data-theme', theme);\n root.style.colorScheme = theme;\n };\n window.addEventListener('message', (event: MessageEvent<unknown>) => {\n const next = event.source === parent ? hostTheme(event.data) : undefined;\n if (next === undefined) return;\n theme = next;\n changed = true;\n if (document.readyState !== 'loading') follow();\n });\n if (document.readyState !== 'loading') settle();\n else\n document.addEventListener('readystatechange', () => {\n if (document.readyState === 'interactive') {\n if (changed) follow();\n else settle();\n }\n });\n}\n\n/** Bundled trusted code, runs in an opaque relay separate from the untrusted App. */\nexport function relayBootstrap(hostTheme: (data: unknown) => HostTheme | undefined): void {\n let configured = false;\n // The relay canvas must match the App's color scheme or the browser paints it opaque.\n const follow = (data: unknown): void => {\n const theme = hostTheme(data);\n if (theme !== undefined) document.documentElement.style.colorScheme = theme;\n };\n window.addEventListener('message', (event: MessageEvent<unknown>) => {\n if (event.source !== parent || configured || event.ports.length !== 1) return;\n const config = event.data as { html: string; policy: string; protocol: string };\n if (typeof config?.html !== 'string' || typeof config.policy !== 'string') return;\n configured = true;\n const port = event.ports[0]!;\n const inner = document.createElement('iframe');\n inner.title = 'MCP App content';\n inner.setAttribute('sandbox', 'allow-scripts');\n // Required CSP also binds nested frames, so an App with declared frame domains relies on the inherited relay\n // policy instead: MCP Apps let those frames keep their own CSP, and the relay revokes any second document.\n if (config.policy.includes(\"frame-src 'none'\")) inner.setAttribute('csp', config.policy);\n inner.setAttribute(\n 'allow',\n \"camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'\",\n );\n inner.style.cssText = 'width:100%;height:100%;border:0;display:block';\n let loaded = false;\n let revoked = false;\n const revoke = (): void => {\n if (revoked) return;\n revoked = true;\n inner.remove();\n port.postMessage({ type: 'revoked' });\n port.close();\n };\n inner.addEventListener('load', () => {\n if (loaded) revoke();\n loaded = true;\n });\n let messageWindow = Date.now();\n let messageCount = 0;\n window.addEventListener('message', (childEvent: MessageEvent<unknown>) => {\n if (revoked || childEvent.source !== inner.contentWindow) return;\n try {\n const encoded = JSON.stringify(childEvent.data);\n if (encoded === undefined || new TextEncoder().encode(encoded).byteLength > 65536) return revoke();\n const now = Date.now();\n if (now - messageWindow >= 1000) {\n messageWindow = now;\n messageCount = 0;\n }\n if (++messageCount > 128) return revoke();\n } catch {\n return revoke();\n }\n // window.openai is in every App, so its channel reaches the host port whatever the protocol.\n const openai = (childEvent.data as { channel?: unknown } | null)?.channel === 'po.openai';\n if (config.protocol === 'mcp' && !openai) parent.postMessage(childEvent.data, '*');\n else port.postMessage({ type: 'legacy', data: childEvent.data });\n });\n // The parent alone owns the other end of this channel. No origin-based trust.\n port.onmessage = (hostEvent: MessageEvent<unknown>) => {\n if (revoked) return;\n follow(hostEvent.data);\n inner.contentWindow?.postMessage(hostEvent.data, '*');\n };\n window.addEventListener('message', (hostEvent: MessageEvent<unknown>) => {\n if (!revoked && hostEvent.source === parent && config.protocol === 'mcp') {\n const data = hostEvent.data as { jsonrpc?: string } | null;\n if (data?.jsonrpc !== '2.0') return;\n follow(data);\n inner.contentWindow?.postMessage(data, '*');\n }\n });\n port.start();\n inner.srcdoc = config.html;\n document.body.append(inner);\n port.postMessage({ type: 'ready' });\n });\n}\n\nexport function mcpAppRelayHtml(policy: string, theme: HostTheme = 'light'): string {\n // frame-src adds srcdoc/about for the App frame, never a host route or a remote sandbox URL. The App's\n // declared frame domains stay, because the srcdoc App inherits this policy for its own nested frames.\n const relayPolicy = policy.replace(/\\b(frame|child)-src ([^;]*)/gu, (_, kind: string, sources: string) =>\n sources === \"'none'\" ? `${kind}-src about:` : `${kind}-src about: ${sources}`,\n );\n return `<!doctype html><html style=\"color-scheme:${theme}\"><meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(relayPolicy)}\"><style>html,body{margin:0;height:100%;overflow:hidden}</style><script>(${relayBootstrap.toString()})(${mcpAppHostTheme.toString()})</script>`;\n}\n\n/** No host <html> is injected, so the App's own root attributes survive parsing. */\nexport function mcpAppDocument(html: string, policy: string, bootstrap = '', theme: HostTheme = 'light'): string {\n const themeScript = `<script>(${widgetThemeBootstrap.toString()})(${mcpAppHostTheme.toString()}, ${JSON.stringify(theme)})</script>`;\n return `<!doctype html><meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(policy)}\"><meta name=\"color-scheme\" content=\"${theme}\">${themeScript}${bootstrap}${html}`;\n}\n\n/** Required CSP enforcement must survive self-navigation, not only initial srcdoc. */\nexport function supportsMcpAppSandbox(host: Document | HTMLIFrameElement): boolean {\n const frame = 'createElement' in host ? host.createElement('iframe') : host;\n return 'csp' in frame;\n}\n"],"mappings":"AAAA,MAEMA,EAAoB,2CAE1B,SAASC,EAAO,EAAqD,C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C,EACDe,EAAK,MAAM,EACX,EAAM,OAASD,EAAO,KACtB,SAAS,KAAK,OAAOE,CAAK,EAC1BD,EAAK,YAAY,CAAE,KAAM,OAAQ,CAAC,CACpC,CAAC,CACH,CAEA,SAAgBY,EAAgB,EAAgB,EAAmB,QAAiB,CAMlF,MAAO,4CAA4C1B,EAAM,wDAAwDJ,EAH7F+B,EAAO,QAAQ,iCAAkC,EAAG,EAAc,IACpFC,IAAY,SAAW,GAAGC,EAAK,aAAe,GAAGA,EAAK,cAAcD,GAEqE,CAAC,EAAE,2EAA2EjB,EAAe,SAAS,EAAE,IAAId,EAAgB,SAAS,EAAE,YACpR,CAGA,SAAgBiC,EAAe,EAAc,EAAgB,EAAY,GAAI,EAAmB,QAAiB,CAC/G,IAAMC,EAAc,YAAY9B,EAAqB,SAAS,EAAE,IAAIJ,EAAgB,SAAS,EAAE,IAAI,KAAK,UAAUG,CAAK,EAAE,aACzH,MAAO,sEAAsEJ,EAAgB+B,CAAM,EAAE,uCAAuC3B,EAAM,IAAI+B,IAAcC,IAAYC,GAClL,CAGA,SAAgBC,EAAsB,EAA6C,CAEjF,MAAO,QADO,kBAAmBpD,EAAOA,EAAK,cAAc,QAAQ,EAAIA,EAEzE"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){let t=`po.openai`,n=/* @__PURE__ */ new Map,r=0,i=e,a=e=>{i={...i,...e},window.dispatchEvent(new CustomEvent(`openai:set_globals`,{detail:{globals:e}}))},o=(e,i)=>{if(n.size>=32)return Promise.reject(/* @__PURE__ */ Error(`Too many pending widget requests`));let a=++r;return new Promise((r,o)=>{let s=window.setTimeout(()=>{n.delete(a),o(/* @__PURE__ */ Error(`Widget request timed out`))},6e4);n.set(a,{resolve:r,reject:o,timer:s}),parent.postMessage({channel:t,id:a,method:e,input:i},`*`)})};Object.defineProperty(window,"openai",{value:Object.freeze({get toolInput(){return i.toolInput},get toolOutput(){return i.toolOutput},get toolResponseMetadata(){return i.toolResponseMetadata},get widgetState(){return i.widgetState},get theme(){return i.theme},get locale(){return i.locale},get displayMode(){return i.displayMode},get maxHeight(){return i.maxHeight},get safeArea(){return i.safeArea},get userAgent(){return i.userAgent},callTool:(e,t={})=>o(`callTool`,{name:e,arguments:t}),setWidgetState:e=>(a({widgetState:e}),o(`setState`,{state:e})),sendFollowUpMessage:e=>o(`followUp`,e),requestDisplayMode:()=>Promise.resolve({mode:`inline`}),openExternal:e=>o(`openLink`,{url:e.href}),requestClose:()=>o(`close`,{}),notifyIntrinsicHeight:e=>o(`height`,{height:e})}),configurable:!1,writable:!1}),window.addEventListener(`message`,e=>{if(e.source!==parent)return;let r=e.data;if(r?.channel!==t||(r.globals!==void 0&&a(r.globals),r.id===void 0))return;let i=n.get(r.id);i!==void 0&&(n.delete(r.id),clearTimeout(i.timer),typeof r.error==`string`?i.reject(Error(r.error)):i.resolve(r.result))}),parent.postMessage({channel:t,method:`initialized`,input:{}},`*`),document.addEventListener(`DOMContentLoaded`,()=>{a(i);let e=new ResizeObserver(()=>{let e=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);parent.postMessage({channel:t,method:`height`,input:{height:e}},`*`)});e.observe(document.body),window.addEventListener(`pagehide`,()=>e.disconnect(),{once:!0})},{once:!0})}function t(t){let n=JSON.stringify(t).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);return`<script>(${e.toString()})(${n})<\/script>`}exports.bootstrap=e,exports.mcpOpenAiScript=t;
|
|
2
|
+
//# sourceMappingURL=mcpOpenAiBootstrap.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcpOpenAiBootstrap.cjs","names":["bootstrap","channel","pending","sequence","globals","initial","update","patch","request","id","timer","reject","args","state","input","event","message","callback","observer","height","mcpOpenAiScript","encoded"],"sources":["../../../src/lib/mcpOpenAiBootstrap.ts"],"sourcesContent":["interface LegacyGlobals {\n toolInput: Record<string, unknown>;\n toolOutput: unknown;\n toolResponseMetadata: Record<string, unknown>;\n widgetState: unknown;\n theme: 'light' | 'dark';\n locale: string;\n displayMode: 'inline';\n maxHeight: number;\n userAgent: { device: { type: 'desktop' | 'mobile' }; capabilities: { hover: boolean; touch: boolean } };\n safeArea: { insets: { top: number; right: number; bottom: number; left: number } };\n}\n\nexport function bootstrap(initial: LegacyGlobals): void {\n const channel = 'po.openai';\n const requestTimeout = 60_000;\n const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void; timer: number }>();\n let sequence = 0;\n let globals = initial;\n const update = (patch: Partial<LegacyGlobals>): void => {\n globals = { ...globals, ...patch };\n window.dispatchEvent(new CustomEvent('openai:set_globals', { detail: { globals: patch } }));\n };\n const request = (method: string, input: unknown): Promise<unknown> => {\n if (pending.size >= 32) return Promise.reject(new Error('Too many pending widget requests'));\n const id = ++sequence;\n return new Promise((resolve, reject) => {\n const timer = window.setTimeout(() => {\n pending.delete(id);\n reject(new Error('Widget request timed out'));\n }, requestTimeout);\n pending.set(id, { resolve, reject, timer });\n parent.postMessage({ channel, id, method, input }, '*');\n });\n };\n const api = {\n get toolInput() {\n return globals.toolInput;\n },\n get toolOutput() {\n return globals.toolOutput;\n },\n get toolResponseMetadata() {\n return globals.toolResponseMetadata;\n },\n get widgetState() {\n return globals.widgetState;\n },\n get theme() {\n return globals.theme;\n },\n get locale() {\n return globals.locale;\n },\n get displayMode() {\n return globals.displayMode;\n },\n get maxHeight() {\n return globals.maxHeight;\n },\n get safeArea() {\n return globals.safeArea;\n },\n get userAgent() {\n return globals.userAgent;\n },\n callTool: (name: string, args: Record<string, unknown> = {}) => request('callTool', { name, arguments: args }),\n setWidgetState: (state: unknown) => {\n // Immediate local state, with await-compatible durable persistence.\n update({ widgetState: state });\n return request('setState', { state });\n },\n sendFollowUpMessage: (input: { prompt: string }) => request('followUp', input),\n requestDisplayMode: () => Promise.resolve({ mode: 'inline' }),\n openExternal: (input: { href: string }) => request('openLink', { url: input.href }),\n requestClose: () => request('close', {}),\n notifyIntrinsicHeight: (height: number) => request('height', { height }),\n };\n Object.defineProperty(window, 'openai', { value: Object.freeze(api), configurable: false, writable: false });\n window.addEventListener('message', (event: MessageEvent<unknown>) => {\n if (event.source !== parent) return;\n const message = event.data as {\n channel?: string;\n id?: number;\n error?: string;\n result?: unknown;\n globals?: Partial<LegacyGlobals>;\n };\n if (message?.channel !== channel) return;\n if (message.globals !== undefined) update(message.globals);\n if (message.id === undefined) return;\n const callback = pending.get(message.id);\n if (callback === undefined) return;\n pending.delete(message.id);\n clearTimeout(callback.timer);\n if (typeof message.error === 'string') callback.reject(new Error(message.error));\n else callback.resolve(message.result);\n });\n parent.postMessage({ channel, method: 'initialized', input: {} }, '*');\n document.addEventListener(\n 'DOMContentLoaded',\n () => {\n update(globals);\n const observer = new ResizeObserver(() => {\n const height = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);\n parent.postMessage({ channel, method: 'height', input: { height } }, '*');\n });\n observer.observe(document.body);\n window.addEventListener('pagehide', () => observer.disconnect(), { once: true });\n },\n { once: true },\n );\n}\n\nexport function mcpOpenAiScript(globals: LegacyGlobals): string {\n const encoded = JSON.stringify(globals)\n .replaceAll('<', '\\\\u003c')\n .replaceAll('\\u2028', '\\\\u2028')\n .replaceAll('\\u2029', '\\\\u2029');\n return `<script>(${bootstrap.toString()})(${encoded})</script>`;\n}\n"],"mappings":"AAaA,SAAgBA,EAAU,EAA8B,CACtD,IAAMC,EAAU,YAEVC,kBAAU,IAAI,IAChBC,EAAW,EACXC,EAAUC,EACRC,EAAU,GAAwC,CACtD,EAAU,CAAE,GAAGF,EAAS,GAAGG,CAAM,EACjC,OAAO,cAAc,IAAI,YAAY,qBAAsB,CAAE,OAAQ,CAAE,QAASA,CAAM,CAAE,CAAC,CAAC,CAC5F,EACMC,GAAW,EAAgB,IAAqC,CACpE,GAAIN,EAAQ,MAAQ,GAAI,OAAO,QAAQ,OAAO,gBAAI,MAAM,kCAAkC,CAAC,EAC3F,IAAMO,EAAK,EAAEN,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
"name": "@agimon-ai/po-web-components",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.124",
|
|
4
4
|
"description": "Shared web components and theme tokens for the Po cockpit and its web plugins: shadcn-style primitives on Radix, tuned to the Po palette, with runtime theme configs.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -63,6 +63,11 @@
|
|
|
63
63
|
"./styles.css": "./styles/tokens.css",
|
|
64
64
|
"./themes/*.json": "./themes/*.json",
|
|
65
65
|
"./package.json": "./package.json",
|
|
66
|
+
"./mcpAppHost": {
|
|
67
|
+
"types": "./dist/mcpAppHost.d.mts",
|
|
68
|
+
"import": "./dist/mcpAppHost.mjs",
|
|
69
|
+
"require": "./dist/mcpAppHost.cjs"
|
|
70
|
+
},
|
|
66
71
|
"./mcpWidget": {
|
|
67
72
|
"types": "./dist/mcpWidget.d.mts",
|
|
68
73
|
"import": "./dist/mcpWidget.mjs",
|
|
@@ -112,8 +117,8 @@
|
|
|
112
117
|
"tailwind-merge": "3.7.0"
|
|
113
118
|
},
|
|
114
119
|
"devDependencies": {
|
|
115
|
-
"@agimon-ai/po-core": "0.0.0-alpha.
|
|
116
|
-
"@agimon-ai/vibe-lint-plugin-po-web": "0.0.0-alpha.
|
|
120
|
+
"@agimon-ai/po-core": "0.0.0-alpha.124",
|
|
121
|
+
"@agimon-ai/vibe-lint-plugin-po-web": "0.0.0-alpha.124",
|
|
117
122
|
"@types/node": "26.6.5",
|
|
118
123
|
"@types/react": "19.3.0",
|
|
119
124
|
"@types/react-dom": "19.3.0",
|